solve the provlem of timeline updating

This commit is contained in:
Tan, Kian-ting 2022-11-14 00:06:07 +08:00
parent 20d7284d9c
commit cde4cb2a50
4 changed files with 165 additions and 21 deletions

View file

@ -24,4 +24,6 @@ urlpatterns = [
path('home/', views.home, name='home'),
path('signup/', views.signup),
path('api/post', views.api_post),
path('api/get_recent_posts_counter', views.api_get_recent_posts_counter),
path('api/get_latest_posts', views.api_get_latest_posts),
]

View file

@ -6,6 +6,36 @@ from django.utils import timezone
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import redirect
from django.contrib.auth.models import AnonymousUser
from datetime import datetime
from django.http import JsonResponse
from django.core import serializers
from django.db.models import Q
def api_get_latest_posts(request):
if request.method == 'POST':
post_body_orig = request.body.decode('utf-8')
post_body_json = json.loads(post_body_orig)
latest_time = post_body_json["latest_time"]
latest_datetime_object = datetime.strptime(latest_time, '%Y-%m-%d %H:%M:%S.%f%z')
newer_posts = Post.objects.filter(post_time__gte=latest_datetime_object)
newer_posts_list = [{"id" : o.pk,
"post_time" : datetime.strftime(o.post_time, "%Y-%m-%d %H:%M:%S.%f%z"),
"poster_username" : o.poster.username,
"poster_shown_name":o.poster.shown_name ,
"text": o.text}
for o in newer_posts]
return JsonResponse({'newer_posts':newer_posts_list})
def api_get_recent_posts_counter(request):
if request.method == 'POST':
post_body_orig = request.body.decode('utf-8')
post_body_json = json.loads(post_body_orig)
latest_time = post_body_json["latest_time"]
latest_datetime_object = datetime.strptime(latest_time, '%Y-%m-%d %H:%M:%S.%f%z')
newer_posts_len = Post.objects.filter(post_time__gte=latest_datetime_object).exclude(Q(poster=request.user) & Q(post_time=latest_datetime_object)).__len__()
return JsonResponse({'newer_posts_num':newer_posts_len})
def api_post(request):
if request.method == 'POST':
@ -58,14 +88,19 @@ def signup(request):
def home(request):
if request.user == AnonymousUser():
return redirect('/account/login') # redirect to main page
public_timeline_list = Post.objects.filter(privilage = 'public').order_by('-id')[:10]
print(public_timeline_list)
latest_received_time = timezone.now()
oldest_received_time = public_timeline_list[9].post_time
template = loader.get_template('index.html')
context = {
'latest_received_time' : latest_received_time,
'oldest_received_time' : oldest_received_time,
'public_timeline_list': public_timeline_list,
}
return HttpResponse(template.render(context, request))

View file

@ -26,20 +26,28 @@
</form>
<div id="public_timeline">
<div id="new_post_notifier" value=""></div>
<div id="latest_time" style="display: block;">{{latest_received_time|date:"Y-m-d H:i:s.u"}}+0000</div>
{% for public_post in public_timeline_list %}
<div id="post-{{public_post.id}}" class="post"><a href="user/{{public_post.poster}}">{{public_post.poster.shown_name}}</a>
at <a href="post/{{public_post.id}}" class="post-time">{{public_post.post_time|date:"Y-m-d H:i:s"}}+0000</a><br/>
{{public_post.text}}</div>
at <a href="post/{{public_post.id}}" class="post-time">{{public_post.post_time|date:"Y-m-d H:i:s.u"}}+0000</a><br/>
{{public_post.text}}<br/>
<span id="reply-{{public_post.id}}" value="{{public_post.id}}" class="reply">↩️</span>
- <span id="repost-{{public_post.id}}" value="{{public_post.id}}" class="repost">🔁</span>
- <span id="fav-{{public_post.id}}" value="{{public_post.id}}" class="fav"></span>
</div>
{% endfor %}
<div id="oldest_time" style="display: block;">{{oldest_received_time|date:"Y-m-d H:i:s.u"}}+0000</div>
</div>
<script>
function timezoneChanging(){
document.querySelectorAll(".post-time").forEach(
(x)=>{var date= new Date(x.innerHTML);
timezoneChangingOne = (x)=>{var date= new Date(x.innerHTML);
var year = date.getFullYear().toString();
var month = (date.getMonth()+1).toString().padStart(2, '0');
var day = date.getDate().toString().padStart(2, '0');
@ -48,31 +56,47 @@
var sec = date.getSeconds().toString().padStart(2, '0');
local_date_string = `${year}-${month}-${day} ${hour}:${min}:${sec}`;
x.innerHTML=local_date_string;}
function timezoneChanging(){
document.querySelectorAll(".post-time").forEach(
x => timezoneChangingOne(x)
);
}
$name = (x) => document.getElementsByName(x);
$ = (x) => document.getElementById(x);
var httpRequest;
$("submit_post").addEventListener('click', make_req);
async function make_req() {
async function make_req() {
post_text = $('post_text').value;
post_privilage = $('privil_choosing').value;
await fetch('/api/post', {
method: 'POST',
headers: {
"X-CSRFToken": "{{ csrf_token }}",
'Content-Type': 'application/json',
},
body: JSON.stringify({
"privilage" : post_privilage,
"text": post_text,
})
if (post_text != ""){
await fetch('/api/post', {
method: 'POST',
headers: {
"X-CSRFToken": "{{ csrf_token }}",
'Content-Type': 'application/json',
},
body: JSON.stringify({
"privilage" : post_privilage,
"text": post_text,
})
}).then(response => {if (response.ok == true)
{$('post_text').value = "";
getLatestPosts(); // wait for a moment then get latest posts
}}
);
}
});
}
@ -89,6 +113,79 @@ function adjust_post_text(){
post_text.style.height = (post_text.scrollHeight)+"px";
}
async function getRecentPostsCounter(){
latest_time_string = $("latest_time").innerHTML;
await fetch('/api/get_recent_posts_counter', {
method: 'POST',
headers: {
"X-CSRFToken": "{{ csrf_token }}",
'Content-Type': 'application/json',
},
body: JSON.stringify({
"latest_time" : latest_time_string,
})
}).then(response => response.json())
.then(the_json => {console.log(the_json);let newer_posts_num = the_json['newer_posts_num'];
if (newer_posts_num == 1)
{ $("new_post_notifier").style.display = "block";
$("new_post_notifier").innerHTML = `1 new post`}
if (newer_posts_num > 1)
{ $("new_post_notifier").style.display = "block";
$("new_post_notifier").innerHTML = `${newer_posts_num} new posts`} });
}
var intervalID = window.setInterval(getRecentPostsCounter, 20000);
async function getLatestPosts(){
latest_time_string = $("latest_time").innerHTML;
await fetch('/api/get_latest_posts', {
method: 'POST',
headers: {
"X-CSRFToken": "{{ csrf_token }}",
'Content-Type': 'application/json',
},
body: JSON.stringify({
"latest_time" : latest_time_string,
}) }).then(response => response.json())
.then(item => item['newer_posts'])
.then(posts => {posts.forEach(post => add_post_to_the_beginning(post));
$('new_post_notifier').style.display = "none";
var nowTime = new Date();
var nowTimeString = nowTime.toISOString();
$("latest_time").innerHTML = nowTimeString.substring(0,10) + " " + nowTimeString.substring(11,23) + "000+0000"; });
}
function add_post_to_the_beginning(post){
console.log(post);
var public_tl = $("public_timeline");
var new_div = document.createElement("div");
new_div.id = `post-${post.id}`;
new_div.className = "post";
new_div.innerHTML = `<a href="user/${post.poster_username}">${post.poster_shown_name}</a>
at <a href="post/${post.id}" class="post-time">${post.post_time}</a><br>
${post.text}<br>
<span id="reply-${post.id}" value="${post.id}" class="reply">↩️</span>
- <span id="repost-${post.id}" value="${post.id}" class="repost">🔁</span>
- <span id="fav-${post.id}" value="${post.id}" class="fav"></span>`;
new_div_timestamp = new_div.getElementsByClassName('post-time')[0];
timezoneChangingOne(new_div_timestamp);
public_tl.insertBefore(new_div, $('latest_time').nextSibling);
}
$("new_post_notifier").addEventListener('click', getLatestPosts);
adjust_post_text();
</script>
{% endblock %}

View file

@ -0,0 +1,10 @@
{% extends "base_generic.html" %}
{% block content %}
You have logged out.
go to <a href="/home">Main Page</a>.
{% endblock %}