def reportThread(request, thread_id): #user id if request.user.is_authenticated: User_id = request.user.id #get the category through the id thread = Thread.objects.get(pk=thread_id) if request.method == "POST": reportpost = report(request.POST) if reportpost.is_valid(): reportText = reportpost.cleaned_data['report'] reportChoice = reportpost.cleaned_data['report_type'] try: checkReport = ReportThread.objects.filter(thread_id=thread_id, reporter=User_id) if len(checkReport) == 0: new_report = ReportThread(thread_id=thread.id, report=reportText, rule_broken=reportChoice, reporter_id=request.user.id, report_time=timezone.now()) new_report.save() msg = f"You have new report <a class='tweet-color' href='/profile/report/'>check here</a>" message_to_referral = Messages(sender_id=request.user.id, msg=msg, receiver_id=1, msg_type="report", receiver_seen=False) message_to_referral.save() else: messages.error(request, f"{request.user.username}, you have already reported") return redirect(f"/forum/thread/?hamlet={ thread.thread_category.id }&slug={ thread.threadSlug }&thread_no={ thread.id }") except Exception as e: print(e) messages.success(request, f"you have reported {thread.user.username} successfully action are being taken") return redirect(f"/forum/thread/?hamlet={ thread.thread_category.id }&slug={ thread.threadSlug }&thread_no={ thread.id }") else: context = {"form": report, "thread_id": thread_id } return render(request, "forum/reportThread.html", context)
def jobpage(request): slug = request.GET["title"] job_id = request.GET['value'] User_id = request.user.id getJob = Job.objects.get(id=job_id) already_applied = AlreadyApplied.objects.filter(user_id=request.user.id, job_id=job_id) #get the category through the id if request.method == "POST": applyJob = request.FILES['files'] if not applyJob.name.endswith(".pdf"): messages.error(request, "Only PDF allowed here") return redirect( f"/jobs/jobpage/?title={getJob.slugTitle}&value={getJob.id}") if len(already_applied) > 0: messages.error(request, "You have already applied for this") return redirect( f"/jobs/jobpage/?title={getJob.slugTitle}&value={getJob.id}") applicant = Applicant(user_id=User_id, doc=applyJob, job_id=job_id, applydate=timezone.now()) appliedJob = AlreadyApplied(user_id=request.user.id, job_id=job_id) send_messages = Messages( sender_id=request.user.id, msg= f"{request.user.username} applied to your Job post click <a style='font-weight: 900'class='tweet-this' href='/jobs/applicant/?title={getJob.slugTitle}&value={getJob.id}'>here</a> to see", receiver_id=getJob.user_id, msg_type="application submitted", receiver_seen=False) send_messages.save() applicant.save() appliedJob.save() messages.success(request, "Job application submitted sucessfully") return redirect( f"/jobs/jobpage/?title={getJob.slugTitle}&value={getJob.id}") else: Job_title = generate_recommendation(getJob.title) string = Job_title.replace(" ", ")|(") search = r"({})".format(string) recommend = Job.objects.filter(~Q(id=job_id), title__iregex=r'{}'.format(search)) recommendation = recommend.order_by("-datetime")[0:5] fav = Favourite.objects.all() context = { "getJob": getJob, "fav": fav, "recommendation": recommendation } return render(request, "job/jobpage.html", context)
def create_category(request): if request.method == "POST": check_community_price = TransactionType.objects.filter(activity="communities") community_cost = check_community_price.first().cost userProfile = Profile.objects.get(user_id=request.user.id) user_ADs = userProfile.afrika_deeds if len(check_community_price) > 0: if user_ADs < community_cost: messages.error(request, f"{request.user.username}, you don't have enough ADSs, you can earn them through referrals and being liked for now") return redirect("/forum/all-categories/") else: form = create_thread_category(request.POST, request.FILES) if form.is_valid(): creating_category = form.save(commit=False) creating_category.created_by_id = request.user.id creating_category.name_of_creator = request.user.username creating_category.save() Members.objects.create(user_id=request.user.id, hamlet_id=creating_category.id, is_admin=True) # deduct points from ADS userProfile.afrika_deeds -= community_cost userProfile.save() # send message to the client send_messages = Messages(sender_id=1, msg=f"<p style='color: green'>Your community titled <b>{form.cleaned_data['title']}</b> has being created, Make sure you stay true to your community</p>", receiver_id=request.user.id, msg_type="community created successfully", receiver_seen=False) send_messages.save() messages.success(request, f"you have successfully a community titled {form.cleaned_data['title']}") return redirect(f"/forum/hamlet/{creating_category.title}/{creating_category.id}/") else: messages.error(request, "Something went wrong") return redirect("/forum/all-categories/") else: messages.error(request, "You are not allowed to create a community yet") return redirect("/forum/all-categories/") else: check_community_price = TransactionType.objects.filter(activity="communities") community_cost = check_community_price.first().cost userProfile = Profile.objects.get(user_id=request.user.id) user_ADs = userProfile.afrika_deeds context = {"form": create_thread_category, "warning": "you are currently not allow to create a community" } if len(check_community_price) > 0: context = {"form": create_thread_category, "community_cost": community_cost, "user_ADs": user_ADs } return render(request, "forum/create_category.html", context)
def result(request): result_id = request.GET["value"] slug = request.GET["title"] pollresult = Poll.objects.filter(settled=True, id=result_id) check = Poll.objects.filter(settled=True, id=result_id, graph_made=False) if check.exists(): all_voters = check.first().voter_set.all() for each_voter in all_voters: send_messages = Messages( sender_id=1, msg= f"The poll that you participated in has expired click below to check result<br><a class='tweet-color' href='/polls/poll/?title={each_voter.poll.slugTitle}&value={each_voter.poll.id}'>poll result</a>", receiver_id=each_voter.user_id, msg_type="poll expiry", receiver_seen=False) send_messages.save() poll_first_result = pollresult.first() choices = poll_first_result.pollchoice_set.all() choices_data = [] get_choice_name = [] for each_choice in choices: each_data = {each_choice.choice: each_choice.votes} choices_data.append(each_data) get_choice_name.append(each_choice.choice) df = pd.DataFrame(choices_data, index=get_choice_name) # visualise data df.plot(kind="bar", title=f"{poll_first_result.title}") output = BytesIO() # Resize/modify the image plt.savefig(output, format='png') output.seek(0) poll_first_result.graph = InMemoryUploadedFile( output, 'ImageField', f"{poll_first_result.title}-{poll_first_result.id}.png", 'image/png', sys.getsizeof(output), None) poll_first_result.graph_made = True poll_first_result.save() context = {"pollresult": pollresult.first()} return render(request, "polls/result.html", context)
def register(request): if request.method == "POST": form = Register_user(request.POST) # check if email already exist email = request.POST["email"] check_mail = User.objects.filter(email=email) if len(check_mail): messages.error(request, "User(E-mail) already exists, kindly reset your password") return redirect("/forum/signup/") name = request.POST["username"] if form.is_valid(): if "ref" in request.POST: ref = request.POST["ref"] try: referral = User.objects.get(id=ref) referral.profile.afrika_deeds += 10 referral.save() msg = f"Thank you for referring {name}, you have been rewarded with 10 ADs" message_to_referral = Messages(sender_id=1, msg=msg, receiver_id=ref, msg_type="referral", receiver_seen=False) message_to_referral.save() except: messages.error(request, "referer does not exist") return redirect("/forum/signup") post_signup = form.save(commit=False) lower_name = post_signup.username.lower() post_signup.username = lower_name # save the changes post_signup.save() try: introductory_thread = Thread.objects.get(id=7) msg = f"Welcome to Africonn and thanks for joining this wonderful platform, the link below is the guide on how and why to use Africonn <br> <a class='tweet-color' href='/forum/thread/?hamlet={introductory_thread.thread_category.id}&slug={introductory_thread.threadSlug}&thread_no={introductory_thread.id}'>{introductory_thread.title}</a>" introduction_msg = Messages(sender_id=1, msg=msg, receiver_id=post_signup.id, msg_type="platform introduction", receiver_seen=False) introduction_msg.save() except: print("no such thread exist") messages.success(request, "your account has been sucessfully created") return redirect("/login") else: messages.error(request, form.errors) return redirect("/forum/signup") else: if request.user.is_authenticated: messages.error(request, "you are already logged in") return redirect("/forum/home/") else: try: ref = request.GET["ref"] form = Register_user() context = {"form": form, "ref": ref} return render(request, "forum/signup.html", context) except: form = Register_user() context = {"form": form} return render(request, "forum/signup.html", context)
def create(request): if request.user.is_authenticated: User_id = request.user.id #get the category through the id if request.method == "POST": createJob = create_job(request.POST) if "job_Image" in request.FILES: image = request.FILES["job_Image"] else: image = "" if createJob.is_valid(): JobTitle = createJob.cleaned_data['title'] slugTitle = JobTitle.replace(" ", "-") name_of_company = createJob.cleaned_data['name_of_company'] JobPost = createJob.cleaned_data['details'] JobCategory = createJob.cleaned_data['category'] JobPay = createJob.cleaned_data['pay'] if not JobPay: JobPay = 0 JobPosition = createJob.cleaned_data['position'] jobTags = generate_recommendation(JobTitle) string = jobTags.replace(" ", ")|(") jobInterest = r"({})".format(string) job = Job.objects.create(user_id=User_id, slugTitle=slugTitle, pay=JobPay, position=JobPosition, category=JobCategory, title=JobTitle, details=JobPost, name_of_company=name_of_company, jobImage=image, datetime=timezone.now()) jobInvite = Profile.objects.filter( ~Q(user_id=job.user_id), are_you_currently_unemployed=True, job_tags__iregex=jobInterest) summary = JobPost[:70] + "..." mailing_list = [] mail_count = 0 for each_invite in jobInvite: send_messages = Messages( sender_id=job.user_id, msg= f"{JobTitle}<br>{summary} <a href='/jobs/jobpage/{job.slugTitle}/{job.id}/'>apply</a>", receiver_id=each_invite.user_id, msg_type="job alert", receiver_seen=False) send_messages.save() if mail_count <= 12: mailing_list.append(each_invite.user.email) mail_count += 1 url = f"/jobs/applicant/?title={job.slugTitle}&value={job.id}" subject = job.title html_message = render_to_string('job/mail_template.html', { 'message': JobPost, 'subject': subject, "url": url, "getJob": job }) plain_message = strip_tags(html_message) mail.send_mail(subject, plain_message, from_email="*****@*****.**", recipient_list=mailing_list, html_message=html_message, fail_silently=False) messages.success( request, f"{request.user.username}, you have sucessfully created a job, you will soon start recieving applications as interested candidates are being notified " ) return redirect( f'/jobs/applicant/?title={job.slugTitle}&value={job.id}') else: messages.error(request, f"Invalid form ") return redirect(f'/jobs/create/') else: context = {"job": create_job} return render(request, "job/create.html", context)
def home(request): new_replys = Reply.objects.filter(receiver_id=request.user.id, you_send=False, is_seen=False).count() new_comments = ThreadSeen.objects.filter(user_id=request.user.id, is_seen=False).count() expiredBans = Ban.objects.filter(expiry_time__lte=time()) for expired in expiredBans: send_messages = Messages( sender_id=1, msg=f"<p class='tweet-color'>Your ban has been lifted</p>", receiver_id=expired.user_id, msg_type="ban expired", receiver_seen=False) send_messages.save() expiredBans.delete() theme = Sitesettings.objects.filter(user_id=request.user.id, setting_name="theme").first() no_of_new_messages = Messages.objects.filter(receiver_id=request.user.id, receiver_seen=False).count() user = User.objects.all() thread = Thread.objects.all() 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') expiry_time = time() + 1200 objects, created = OnlineUser.objects.get_or_create( user_ip=ip, defaults={ "last_seen": expiry_time, "is_authenticated": request.user.is_authenticated }) if request.user.is_authenticated: updateUserLastSeen = Profile.objects.get(user_id=request.user.id) updateUserLastSeen.last_seen = timezone.now() updateUserLastSeen.save() # deleting expired ip OnlineUser.objects.filter(last_seen__lte=time()).delete() if not created: objects.last_seen = time() objects.is_authenticated = request.user.is_authenticated objects.save() try: theme_color = Sitesettings.objects.get(setting_name="theme_color", user_id=request.user.id) theme_color = theme_color.setting except Exception: theme_color = "orangered" #homepage return { "new_replies": new_replys, "new_messages": no_of_new_messages, "theme": theme, "new_comments": new_comments, "author": user, "thread": thread, "theme_color": theme_color }
def comment(request, thread_id): #user id if request.user.is_authenticated: User_id = request.user.id #get the category through the id thread = Thread.objects.get(pk=thread_id) if request.method == "POST": comment = create_comment(request.POST, request.FILES) if comment.is_valid(): commentpost = comment.cleaned_data['comment'] image = comment.cleaned_data['image'] try: if image: new_comment = thread.comment_set.create(comment=commentpost, image=image, user_id=User_id, datetime=timezone.now(), thread_id=thread_id) new_comment.save() # Update trending threading from comments comments_of_the_thread = Comment.objects.filter(thread_id=thread_id) # length of the comments len_comments_of_the_thread = len(comments_of_the_thread) #last comment last_comments_of_the_thread = comments_of_the_thread.last().datetime #us those information to update the thread thread.last_comment_datetime = last_comments_of_the_thread thread.last_comment_length = len_comments_of_the_thread thread.save() checkThread = ThreadSeen.objects.filter(thread_id=thread_id, user_id=User_id) if len(checkThread) == 0: threadUpdate = ThreadSeen(thread_id=thread_id, user_id=User_id, is_seen=False) threadUpdate.save() else: ThreadSeen.objects.filter(thread_id=thread_id).update(is_seen=False) # making invites invites = re.findall("@\w+", commentpost) if invites: for each_invite in invites: invite = each_invite.replace("@", "") receiver = User.objects.filter(username=invite) if len(receiver) > 0: msg = f"<a href='/forum/thread/?hamlet={ thread.thread_category.id }&slug={ thread.threadSlug }&thread_no={ thread.id }#{new_comment.id}'>{thread.title}</a><br><p class='tweet-color'>{commentpost}</p>" send_messages = Messages(sender_id=request.user.id, msg=msg, receiver_id=receiver.first().id, msg_type="mention", receiver_seen=False) send_messages.save() # updating timestamp thread.datetime = timezone.now() thread.save() else: new_comment = thread.comment_set.create(comment=commentpost, user_id=User_id, datetime=timezone.now(), thread_id=thread_id) new_comment.save() # Update trending threading from comments comments_of_the_thread = Comment.objects.filter(thread_id=thread_id) # length of the comments len_comments_of_the_thread = len(comments_of_the_thread) #last comment last_comments_of_the_thread = comments_of_the_thread.last().datetime #us those information to update the thread thread.last_comment_datetime = last_comments_of_the_thread thread.last_comment_length = len_comments_of_the_thread thread.save() # each thread that is commented on checkThread = ThreadSeen.objects.filter(thread_id=thread_id, user_id=User_id) if len(checkThread) == 0: threadUpdate = ThreadSeen(thread_id=thread_id, user_id=User_id, is_seen=False) threadUpdate.save() else: ThreadSeen.objects.filter(thread_id=thread_id).update(is_seen=False) # making invites invites = re.findall("@\w+", commentpost) if invites: for each_invite in invites: invite = each_invite.replace("@", "") receiver = User.objects.filter(username=invite) if len(receiver) > 0: msg = f"<a href='/forum/thread/?hamlet={ thread.thread_category.id }&slug={ thread.threadSlug }&thread_no={ thread.id }/#{new_comment.id}'>{thread.title}</a><br>{commentpost}" send_messages = Messages(sender_id=request.user.id, msg=msg, receiver_id=receiver.first().id, msg_type="mention", receiver_seen=False) send_messages.save() # updating timestamp thread.datetime = timezone.now() thread.save() except Exception as e: print(e) return redirect(f"/forum/thread/?hamlet={ thread.thread_category.id }&slug={ thread.threadSlug }&thread_no={ thread.id }") else: context = {"form": create_comment, "thread_id": thread_id, "thread_name": thread.thread_category.id}# "comments": comments} return render(request, "forum/comment.html", context) else: return redirect("/login/")
def ads_manager(category, numba_of_ads, user_id, your_country): if category == "feeds": advert = Advert.objects.filter(advert_category__iregex=f'(feeds)|(all)', ad_country__iregex=f'({your_country})|(all)', approved=True)#.values("advert_title", "advert_details", "advert_url", "advert",'advert_category', 'ad_country') expiredAdvert = Advert.objects.filter(expiryDate__lte=time(), approved=True) elif category == "home": advert = Advert.objects.filter(advert_category__iregex=f'(home)|(all)', ad_country__iregex=f'({your_country})|(all)', approved=True)#.values("advert_title", "advert_details", "advert_url", "advert", 'ad_country', 'advert_category') expiredAdvert = Advert.objects.filter(expiryDate__lte=time(), approved=True) else: advert = Advert.objects.filter(advert_category__iregex=f'({category})|(all)', ad_country__iregex=f'({your_country})|(all)', approved=True)#.values("advert_title", "advert_details", "advert_url", "advert", 'ad_country', 'advert_category') expiredAdvert = Advert.objects.filter(expiryDate__lte=time(), approved=True) if not user_id: # # selecting advert through random process random_ads = len(advert) - numba_of_ads if random_ads < 0: random_ads = 0 start = randint(0, random_ads) end = start + numba_of_ads advert = advert[start:end] # #this is not ideal it is to be change later for expired in expiredAdvert: send_messages = Messages(sender_id=1, msg=f"<p class='tweet-this'>Your ads has expired on {expired.ad_expirydatetime.strftime('%d %b %Y %I-%M%p')}</p>", receiver_id=expired.user_id, msg_type="ads expired", receiver_seen=False) send_messages.save() expiredAdvert.delete() serialized_ad = [] if len(advert) > 0: serialized_ad = advert shuffled_content = sample(serialized_ad, len(serialized_ad)) else: users_category = Members.objects.filter(user_id=user_id) hamlet_u_re_not_part_of = [] if len(users_category) > 0: pred_category = choice(users_category) recommended_hamlet = generate_recommendation(pred_category.description) string = recommended_hamlet.replace(" ", ")|(") # recommend nothing string if string is empty search = string if string != "": search = r"({})".format(string) hamlet_u_re_not_part_of = Members.objects.filter(~Q(user_id=user_id), description__iregex=r'{}'.format(search)) else: users_category = Members.objects.all() if len(users_category) > 0: pred_category = choice(users_category) recommended_hamlet = generate_recommendation(pred_category.description) string = recommended_hamlet.replace(" ", ")|(") # recommend nothing string if string is empty search = string if string != "": search = r"({})".format(string) hamlet_u_re_not_part_of = Members.objects.filter(~Q(user_id=user_id), description__iregex=r'{}'.format(search)) # # selecting advert through random process random_ads = len(advert) - numba_of_ads if random_ads < 0: random_ads = 0 start = randint(0, random_ads) end = start + numba_of_ads advert = advert[start:end] # #this is not ideal it is to be change later for expired in expiredAdvert: send_messages = Messages(sender_id=1, msg=f"<p class='tweet-this'>Your ads has expired on {expired.ad_expirydatetime.strftime('%d %b %Y %I-%M%p')}</p>", receiver_id=expired.user_id, msg_type="ads expired", receiver_seen=False) send_messages.save() expiredAdvert.delete() serialized_ad = [] if len(advert) > 0: serialized_ad = advert hamlet_u_re_not_part_of_trimmed = hamlet_u_re_not_part_of[0:2] served_promo = [*serialized_ad, *hamlet_u_re_not_part_of_trimmed] shuffled_content = sample(served_promo, len(served_promo)) return serializers.serialize("json", shuffled_content)