Skip to content

Commit

Permalink
Merge pull request #8 from atharv-naik/dev
Browse files Browse the repository at this point in the history
Add views logic
  • Loading branch information
atharv-naik authored Dec 11, 2023
2 parents daa1f11 + 7ec93a8 commit f1cb62a
Show file tree
Hide file tree
Showing 9 changed files with 81 additions and 16 deletions.
3 changes: 1 addition & 2 deletions play/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@

# Register your models here.

from .models import Channel, Comment, Dislike, Like, Subscription, Video, View, History
from .models import Channel, Comment, Dislike, Like, Subscription, Video, History

admin.site.register(Channel)
admin.site.register(Comment)
admin.site.register(Dislike)
admin.site.register(Like)
admin.site.register(Subscription)
admin.site.register(Video)
admin.site.register(View)
admin.site.register(History)
1 change: 1 addition & 0 deletions play/api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@
path('get-preview-thumbnails/<str:video_id>/<int:number>', views.getPreviewThumbnails, name='get-preview-thumbnails'),
path('update-watch-time/', views.updateWatchTime, name='update-watch-time'),
path('get-watch-history/<str:user>', views.getWatchHistory, name='get-watch-history'),
path('update-views/', views.updateViews, name='update-views'),
path('logo/', views.logo, name='logo'),
]
12 changes: 12 additions & 0 deletions play/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from .serializers import HistorySerializer
from django.contrib.auth.models import User
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from django.db.models import F
import os

# Create your views here.
Expand All @@ -20,12 +21,14 @@ def apiOverview(request):
}
return Response(api_urls)


@api_view(['GET'])
def logo(request):
file = open('play/static/play/images/PlayTube.png', 'rb')
response = FileResponse(file)
return response


@api_view(['GET'])
def getVideoStream(request, video_id, file):
video = Video.objects.get(video_id=video_id)
Expand Down Expand Up @@ -74,3 +77,12 @@ def updateWatchTime(request):
defaults={'timestamp': t})
history.save()
return Response()


@api_view(['POST'])
def updateViews(request):
video_id = request.POST.get('video_id')
video = Video.objects.get(video_id=video_id)
video.views = F('views') + 1
video.save()
return Response()
21 changes: 21 additions & 0 deletions play/migrations/0028_video_views_delete_view.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Generated by Django 4.1.2 on 2023-12-11 11:32

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("play", "0027_alter_video_description"),
]

operations = [
migrations.AddField(
model_name="video",
name="views",
field=models.PositiveBigIntegerField(default=0),
),
migrations.DeleteModel(
name="View",
),
]
13 changes: 3 additions & 10 deletions play/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,15 +76,6 @@ def __str__(self):
return f'{self.user.username} dislikes {self.video.title}'


class View(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
video = models.ForeignKey('Video', on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)

def __str__(self):
return f'{self.user.username} viewed {self.video.title}'


class Video(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(max_length=5000, null=True, blank=True)
Expand Down Expand Up @@ -148,6 +139,8 @@ class Video(models.Model):
('oth', 'Other'),
], default='eng')

views = models.PositiveBigIntegerField(default=0)

class Meta:
ordering = ['-created_at']
# check series name, episode and season not null if series is true
Expand Down Expand Up @@ -198,4 +191,4 @@ class Meta:
verbose_name_plural = 'Histories'

def __str__(self):
return f'{self.user.username} watched {self.video.title}'
return f'{self.channel} watched {self.video.title}'
2 changes: 1 addition & 1 deletion play/templates/play/home.html
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ <h1 class="banner-title">PlayTube</h1>
{% endif %}
</a>
<div class="video-metadata">
<span>12K views</span>
<span>{{ video.views|format_views }} views</span>
<span></span>
<span>{{ video.created_at|timesince|truncatetimesince }} ago</span>
</div>
Expand Down
30 changes: 30 additions & 0 deletions play/templates/play/watch.html
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,36 @@
},
});
}

// update views
function updateViews() {
$.ajax({
type: "POST",
url: `${http_protocol}://${domain_name}/api/update-views/`,
data: {
video_id: video_id,
csrfmiddlewaretoken: "{{ csrf_token }}",
},
});
}

// update views after video engagement of atleast 10 percent of the video duration
// i.e. if the sum of all segments of video.played is greater than 0.1
function handleVideoEngagement() {
let totalPlayed = 0;
for (let i = 0; i < video.played.length; i++) {
totalPlayed += video.played.end(i) - video.played.start(i);
}
if (totalPlayed > 0.1 * video.duration) {
console.log(totalPlayed);
updateViews();
// avoid updating views again
video.removeEventListener("timeupdate", handleVideoEngagement);
}
}
video.addEventListener("timeupdate", handleVideoEngagement);


{% if user.is_authenticated %}
// update watch history after every 5 seconds; send post request to update watch history
let timestamp = 0;
Expand Down
11 changes: 11 additions & 0 deletions play/templatetags/custom_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,14 @@ def get_duration_stamp(duration):
@register.filter
def truncatetimesince(value):
return value.split(',')[0]

@register.filter
def format_views(views):
if views < 1000:
return views
elif views < 1000000:
return f'{views // 1000}K'
elif views < 1000000000:
return f'{views // 1000000}M'

return f'{views // 1000000000}B'
4 changes: 1 addition & 3 deletions play/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,7 @@ def watch(request):
t = history.timestamp if t is 0 else t
history.save()

stream_path = os.path.join(os.path.dirname(
video.video_file.path), 'playlist.m3u8')
return render(request, 'play/watch.html', {'video_id': video_id, 'channel_id': channel_id, 't': t, 'movie': video, 'channel': channel, 'stream_path': stream_path, 'domain_name': settings.DOMAIN_NAME, 'http_protocol': 'https' if settings.USE_HTTPS else 'http'})
return render(request, 'play/watch.html', {'video_id': video_id, 'channel_id': channel_id, 't': t, 'movie': video, 'channel': channel, 'domain_name': settings.DOMAIN_NAME, 'http_protocol': 'https' if settings.USE_HTTPS else 'http'})

except Channel.DoesNotExist:
info = {'info': 'This video isn\'t available anymore'}
Expand Down

0 comments on commit f1cb62a

Please sign in to comment.