Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from django.db import models
- from django.utils import timezone
- from django.db.models import Q
- from boto.sns import SNSConnection
- from django.core.mail import EmailMessage
- from random import choice
- from geoposition.fields import GeopositionField
- import json
- import datetime
- import math
- import hashlib
- import string
- import uuid
- import time
- import random
- import base64
- import boto
- import cStringIO
- import urllib
- from PIL import Image
- from boto.s3.connection import S3Connection
- from boto.s3.key import Key
- # Create your models here.
- #USER MODEL
- class User(models.Model):
- username = models.CharField(max_length=300)
- facebook_id = models.CharField(max_length=300)
- first_name = models.CharField(max_length=300)
- full_name = models.CharField(max_length=300, default='')
- last_name = models.CharField(max_length=300)
- gender = models.CharField(max_length=300, default='')
- profile_pic = models.CharField(max_length=300, default='')
- website = models.CharField(max_length=300, default='')
- bio = models.CharField(max_length=300, default='')
- date_joined = models.DateTimeField('date joined')
- last_login = models.DateTimeField('last login')
- email = models.EmailField(unique=True)
- lat = models.FloatField(default=0)
- lng = models.FloatField(default=0)
- device_token = models.CharField(max_length=300)
- device_type = models.CharField(max_length=300)
- password = models.CharField(max_length=300)
- push_notifications = models.IntegerField(default=1)
- email_notifications = models.IntegerField(default=1)
- followers = models.ManyToManyField('self', symmetrical=False)
- posts = models.ManyToManyField('Post', symmetrical=False)
- reposts = models.ManyToManyField('Post', symmetrical=False, related_name='Reposts')
- liked_posts = models.ManyToManyField('Post', symmetrical=False, related_name='LikedPosts')
- reaction_videos = models.ManyToManyField('Video', symmetrical=False)
- liked_reactions = models.ManyToManyField('Video', symmetrical=False, related_name='LikedReactions')
- disliked_reactions = models.ManyToManyField('Video', symmetrical=False, related_name='DisLikedReactions')
- is_suggested = models.IntegerField(default=0)
- phone = models.CharField(max_length=300, default='')
- ##CREATE USER OR RETURN EXISTING ONE FACEBOOK LOGIN##
- @staticmethod
- def loginWithFacebook(fb_id, first_name, last_name, email, device_token, device_type, profile_pic):
- #Check if user already exists in our system
- user = User.objects.filter(facebook_id=fb_id)
- user_email = User.objects.filter(email=email)
- if len(user)!=0:
- #Found user record
- user = User.objects.get(pk=user[0].id)
- user.last_login = timezone.now()
- user.device_token = device_token
- user.device_type = device_type
- user.profile_pic = profile_pic
- user.full_name = str(first_name + '' + last_name)
- user.save()
- response = {'status':'success', 'user_id':user.id}
- return json.dumps(response)
- elif len(user_email)!=0:
- user = User.objects.get(pk=user_email[0].id)
- user.last_login = timezone.now()
- user.facebook_id = fb_id
- user.first_name = first_name
- user.last_name = last_name
- user.profile_pic = profile_pic
- user.device_token = device_token
- user.device_type = device_type
- user.full_name = str(first_name + ' ' + last_name)
- user.username = str(first_name) + str(last_name) + str(random.randrange(0,1000))
- user.save()
- response = {'status':'success', 'user_id':user.id}
- return json.dumps(response)
- else:
- #Create User Record
- new_user = User(facebook_id=fb_id,
- email=email,
- device_token=device_token,
- device_type=device_type,
- date_joined=timezone.now(),
- last_login=timezone.now(),
- profile_pic=profile_pic,
- first_name=first_name,
- last_name=last_name,
- password=fb_id,
- username=str(first_name) + str(last_name) + str(random.randrange(0,1000))
- )
- new_user.full_name = str(first_name + ' ' + last_name)
- new_user.save()
- #Return Response
- response = {'status':'success', 'user_id':new_user.id}
- return json.dumps(response)
- return ""
- ##UPDATE THE USER LOCATION CALL
- @staticmethod
- def updateUserLocation(user_id, lat, lng):
- user = User.objects.get(pk=user_id)
- user.lat = lat
- user.lng = lng
- user.save()
- response = {'msg':'user location updated'}
- return json.dumps(response)
- ##REGULAR REGISTER##
- @staticmethod
- def register(username, email, password, full_name, device_token, device_type, profile_pic, facebook_id):
- check_user = User.objects.filter(username=username)
- #Hash Password
- h = hashlib.md5()
- h.update(password)
- ##CHECK TO SEE IF THERE IS A USER WITH THAT EMAIL ALREADY##
- if len(check_user) == 0:
- check_email = User.objects.filter(email=email)
- if len(check_email) == 0:
- new_user = User(
- username=username,
- email=email,
- device_token=device_token,
- device_type=device_type,
- date_joined=timezone.now(),
- last_login=timezone.now(),
- password=h.hexdigest(),
- facebook_id=facebook_id,
- full_name=full_name,
- profile_pic=profile_pic
- )
- new_user.save()
- response = {'status':'success', 'user_id' : new_user.id, 'profile_pic':new_user.profile_pic}
- else:
- response = {'status':'failed', 'msg' : 'That email is registered to another user. Please login to proceed.'}
- else:
- response = {'status':'failed', 'msg' : 'That username is taken. Please try another username.'}
- return json.dumps(response)
- ##LOGIN USER##
- @staticmethod
- def login(username, password, device_token, device_type):
- h = hashlib.md5()
- h.update(password)
- user = User.objects.filter(username=username, password=h.hexdigest())
- if(len(user) > 0):
- ##WE FOUND THE USER SO LETS JUST RETURN A TRUE
- user_found = user[0]
- user_found.last_login = timezone.now()
- user_found.device_token = device_token
- user_found.device_type = device_type
- user_found.save()
- response = {'status':'success', 'user_id':user_found.id, 'profile_pic':user_found.profile_pic}
- else:
- response = {'status':'failed', 'msg':'There was an issue logging you in, please check your username/password combination.'}
- return json.dumps(response)
- ##FORGOT PASSWORD##
- @staticmethod
- def forgotPassword(email):
- the_user = User.objects.filter(email=email)
- if len(the_user) == 0:
- response = {'status':'failed' , 'msg' : 'We do not recognize the email you provided.' }
- return json.dumps(response)
- else:
- #Generate New Password
- user = User.objects.get(pk=the_user[0].id)
- chars = string.letters + string.digits
- length = 8
- password = ''.join(choice(chars) for _ in xrange(length))
- print("new password: ",password)
- #Generate Password Hash
- h = hashlib.md5()
- h.update( password )
- hash = h.hexdigest()
- print("password hashed: ",hash)
- #Save New Password
- user.password = hash;
- user.save()
- print("user password reset")
- #Get Email
- body = open('templates/emails/forgot_password.html', 'r+')
- body = body.read()
- body = string.replace(body, "{{password}}", password)
- print("rendered template")
- #Send Email
- subject = "Reset Password"
- from_email = "noreply@butterfingerz.com"
- to_emails = [user.email]
- email = EmailMessage(subject, body, from_email, to_emails)
- email.content_subtype = "html"
- email.send()
- print("email sent")
- print ("password reset success")
- #Send Home
- response = {'status':'success' , 'msg' : 'We have sent a new password to the email you provided.' }
- return json.dumps(response)
- ##UPDATE USER INFO
- @staticmethod
- def updateUserInfo(user_id, username, bio, website, email, profile_pic, full_name):
- user = User.objects.get(pk=user_id)
- user.bio = bio
- user.full_name = full_name
- user.website = website
- if profile_pic != '':
- user.profile_pic = profile_pic
- user.save()
- if username == user.username and email == user.email:
- response = {'status':'success', 'user_id' : user.id}
- return json.dumps(response)
- else:
- username_check = User.objects.filter(username=username).exclude(id=user.id)
- if len(username_check) == 0:
- email_check = User.objects.filter(email=email).exclude(id=user.id)
- if len(email_check) == 0:
- user.email = email
- user.bio = bio
- user.full_name = full_name
- user.website = website
- user.username = username
- user.save()
- response = {'status':'success', 'user_id' : user.id}
- return json.dumps(response)
- else:
- response = {'status':'failed', 'msg' : 'That email you choose is not avaliable.'}
- else:
- response = {'status':'failed', 'msg' : 'That username you have choosen is not avaliable.'}
- return json.dumps(response)
- ##FOLLOW USER
- @staticmethod
- def followUser(user_id, to_follow_id):
- main_user = User.objects.get(pk=user_id)
- to_follow_user = User.objects.get(pk=to_follow_id)
- to_follow_user.followers.add(main_user)
- return json.dumps({'status':'success'})
- ##UNFOLLOW USER
- @staticmethod
- def unFollowUser(user_id, to_follow_id):
- main_user = User.objects.get(pk=user_id)
- to_follow_user = User.objects.get(pk=to_follow_id)
- to_follow_user.followers.remove(main_user)
- return json.dumps({'status':'success'})
- ##GET USER INFO
- @staticmethod
- def userInfo(user_id, info_id):
- main_user = User.objects.get(pk=user_id)
- info_user = User.objects.get(pk=info_id)
- following = User.objects.filter(followers__id=info_id)
- is_following = User.objects.filter(id=info_id, followers__id=user_id)
- posts_count = Post.objects.filter(user_id=info_id).count()
- total_score = 0
- for vid in info_user.reaction_videos.all():
- total_score = total_score + vid.score
- to_return = {
- 'profile_pic':info_user.profile_pic,
- 'num_following':len(following),
- 'num_followers':len(info_user.followers.all()),
- 'username':info_user.username,
- 'bio':info_user.bio,
- 'website':info_user.website,
- 'total_reactions':len(info_user.reaction_videos.all()),
- 'is_following':len(is_following),
- 'full_name':info_user.full_name,
- 'email':info_user.email,
- 'total_videos':posts_count,
- 'total_reposts':info_user.reposts.all().count(),
- 'total_score':total_score
- }
- return json.dumps(to_return)
- @staticmethod
- def searchUsers(query,user_id):
- users = User.objects.filter(username__icontains=query)
- list_return = []
- for user in users:
- main_user = User.objects.get(pk=user_id)
- info_user = User.objects.get(pk=user.id)
- following = User.objects.filter(followers__id=user.id)
- is_following = User.objects.filter(id=user.id, followers__id=user_id)
- total_score = 0
- for vid in user.reaction_videos.all():
- total_score = total_score + vid.score
- to_return = {
- 'profile_pic':info_user.profile_pic,
- 'num_following':len(following),
- 'num_followers':len(info_user.followers.all()),
- 'username':info_user.username,
- 'bio':info_user.bio,
- 'website':info_user.website,
- 'total_reactions':len(info_user.reaction_videos.all()),
- 'is_following':len(is_following),
- 'user_id':user.id,
- 'total_score':total_score
- }
- list_return.append(to_return)
- return json.dumps(list(list_return))
- @staticmethod
- def suggestedUsers(user_id):
- users = User.objects.filter(is_suggested=1)
- list_return = []
- for user in users:
- main_user = User.objects.get(pk=user_id)
- info_user = User.objects.get(pk=user.id)
- following = User.objects.filter(followers__id=user.id)
- is_following = User.objects.filter(id=user.id, followers__id=user_id)
- total_score = 0
- for vid in user.reaction_videos.all():
- total_score = total_score + vid.score
- to_return = {
- 'profile_pic':info_user.profile_pic,
- 'num_following':len(following),
- 'num_followers':len(info_user.followers.all()),
- 'username':info_user.username,
- 'bio':info_user.bio,
- 'website':info_user.website,
- 'total_reactions':len(info_user.reaction_videos.all()),
- 'is_following':len(is_following),
- 'user_id':user.id,
- 'total_score':total_score
- }
- list_return.append(to_return)
- return json.dumps(list(list_return))
- @staticmethod
- def facebookContacts(user_id):
- users = User.objects.filter(is_suggested=1)
- list_return = []
- for user in users:
- main_user = User.objects.get(pk=user_id)
- info_user = User.objects.get(pk=user.id)
- following = User.objects.filter(followers__id=user.id)
- is_following = User.objects.filter(id=user.id, followers__id=user_id)
- total_score = 0
- for vid in user.reaction_videos.all():
- total_score = total_score + vid.score
- to_return = {
- 'profile_pic':info_user.profile_pic,
- 'num_following':len(following),
- 'num_followers':len(info_user.followers.all()),
- 'username':info_user.username,
- 'bio':info_user.bio,
- 'website':info_user.website,
- 'total_reactions':len(info_user.reaction_videos.all()),
- 'is_following':len(is_following),
- 'user_id':user.id,
- 'total_score':total_score
- }
- list_return.append(to_return)
- return json.dumps(list(list_return))
- @staticmethod
- def phoneContacts(user_id):
- users = User.objects.filter(is_suggested=1)
- list_return = []
- for user in users:
- main_user = User.objects.get(pk=user_id)
- info_user = User.objects.get(pk=user.id)
- following = User.objects.filter(followers__id=user.id)
- is_following = User.objects.filter(id=user.id, followers__id=user_id)
- total_score = 0
- for vid in user.reaction_videos.all():
- total_score = total_score + vid.score
- to_return = {
- 'profile_pic':info_user.profile_pic,
- 'num_following':len(following),
- 'num_followers':len(info_user.followers.all()),
- 'username':info_user.username,
- 'bio':info_user.bio,
- 'website':info_user.website,
- 'total_reactions':len(info_user.reaction_videos.all()),
- 'is_following':len(is_following),
- 'user_id':user.id,
- 'total_score':total_score
- }
- list_return.append(to_return)
- return json.dumps(list(list_return))
- @staticmethod
- def leaderboardUsersAllTime(user_id):
- users = User.objects.all()
- list_return = []
- for user in users:
- main_user = User.objects.get(pk=user_id)
- info_user = User.objects.get(pk=user.id)
- following = User.objects.filter(followers__id=user.id)
- is_following = User.objects.filter(id=user.id, followers__id=user_id)
- total_score = 0
- for vid in user.reaction_videos.all():
- total_score = total_score + vid.score
- to_return = {
- 'profile_pic':info_user.profile_pic,
- 'num_following':len(following),
- 'num_followers':len(info_user.followers.all()),
- 'username':info_user.username,
- 'bio':info_user.bio,
- 'website':info_user.website,
- 'total_reactions':len(info_user.reaction_videos.all()),
- 'is_following':len(is_following),
- 'user_id':user.id,
- 'total_score':total_score
- }
- list_return.append(to_return)
- newlist = sorted(list_return, key=lambda k: k['total_score'], reverse=True)[:100]
- return json.dumps(list(newlist))
- @staticmethod
- def leaderboardUsersToday(user_id):
- users = User.objects.all()
- list_return = []
- for user in users:
- main_user = User.objects.get(pk=user_id)
- info_user = User.objects.get(pk=user.id)
- following = User.objects.filter(followers__id=user.id)
- is_following = User.objects.filter(id=user.id, followers__id=user_id)
- total_score = 0
- for vid in user.reaction_videos.all():
- total_score = total_score + vid.score
- to_return = {
- 'profile_pic':info_user.profile_pic,
- 'num_following':len(following),
- 'num_followers':len(info_user.followers.all()),
- 'username':info_user.username,
- 'bio':info_user.bio,
- 'website':info_user.website,
- 'total_reactions':len(info_user.reaction_videos.all()),
- 'is_following':len(is_following),
- 'user_id':user.id,
- 'total_score':total_score
- }
- list_return.append(to_return)
- newlist = sorted(list_return, key=lambda k: k['total_score'], reverse=True)[:100]
- return json.dumps(list(newlist))
- @staticmethod
- def userReactionVideos(user_id):
- user = User.objects.get(pk=user_id)
- reactions_list = []
- all_reactions = user.reaction_videos.all().order_by('-score')
- for reaction in all_reactions:
- to_add = {
- 'video_url':reaction.video_url,
- 'video_thumb_url':reaction.thumbnail_url,
- 'score':reaction.score,
- 'username':user.username,
- 'user_id':user.id,
- 'profile_pic':user.profile_pic
- }
- reactions_list.append(to_add)
- to_return = {'reactions':list(reactions_list)}
- return json.dumps(to_return)
- @staticmethod
- def rePost(post_id, user_id):
- the_user = User.objects.get(pk=user_id)
- the_post = Post.objects.get(pk=post_id)
- the_user.reposts.add(the_post)
- return json.dumps({'status':'success'})
- @staticmethod
- def rePostFeed(user_id):
- main_user = User.objects.get(pk=user_id)
- posts = main_user.reposts.all()
- list_of_posts = []
- for post in posts:
- already_recorded_for_post = 0
- video = Video.objects.get(pk=post.video_id)
- reactions = video.reactions.all()
- reactions_list = []
- post_user = User.objects.get(pk=post.user_id)
- for reaction in reactions:
- if reaction in main_user.reaction_videos.all():
- already_recorded_for_post = 1
- user = User.objects.get(pk=reaction.user_id)
- to_add = {
- 'video_url':reaction.video_url,
- 'video_thumb_url':reaction.thumbnail_url,
- 'score':reaction.score,
- 'username':user.username,
- 'user_id':user.id,
- 'profile_pic':user.profile_pic
- }
- reactions_list.append(to_add)
- to_append = {
- 'post_id': post.id,
- 'video_url':video.video_url,
- 'video_thumb_url':video.thumbnail_url,
- 'reactions_count':len(reactions_list),
- 'likes':post.likes,
- 'loops':post.loops,
- 'username':post_user.username,
- 'user_id':post_user.id,
- 'reactions':list(reactions_list),
- 'profile_pic':post_user.profile_pic,
- 'date_created':str(post.date_created),
- 'title':post.title,
- 'is_top_pick':post.is_top_pick,
- 'already_recorded_reaction':already_recorded_for_post
- }
- list_of_posts.append(to_append)
- return json.dumps(list(list_of_posts))
- #POST MODEL
- class Post(models.Model):
- video_id = models.CharField(max_length=300)
- user_id = models.CharField(max_length=300)
- likes = models.IntegerField(default=0)
- loops = models.IntegerField(default=0)
- date_created = models.DateTimeField('created date')
- title = models.CharField(max_length=300, default='')
- is_top_pick = models.IntegerField(default=0)
- tags = models.ManyToManyField('User', symmetrical=False)
- @staticmethod
- def createPost(user_id, video_url, video_thumb_url, title, tags):
- vid_creator = User.objects.get(pk=user_id)
- video_thumb_url = Utility.createThumb(video_thumb_url)
- if vid_creator != None:
- new_vid = Video(video_url=video_url,
- thumbnail_url=video_thumb_url,
- user_id=user_id,
- is_reaction_video=0
- )
- new_vid.save()
- new_post = Post(user_id=user_id,
- video_id=new_vid.id,
- title=title,
- date_created=timezone.now()
- )
- new_post.save()
- vid_creator.posts.add(new_post)
- for id in tags:
- tagged = User.objects.get(pk=id)
- new_post.tags.add(tagged)
- response = {'status':'success', 'post_id' : new_post.id}
- else:
- response = {'status':'failed', 'msg' : 'Failed to create new post, try again!'}
- return json.dumps(response)
- @staticmethod
- def createReactionVideo(user_id, post_id, video_url, video_thumb_url):
- vid_creator = User.objects.get(pk=user_id)
- video_thumb_url = Utility.createThumb(video_thumb_url)
- post = Post.objects.get(pk=post_id)
- if vid_creator != None and post != None:
- main_video = Video.objects.get(pk=post.video_id)
- if main_video != None:
- new_reaction_vid = Video(video_url=video_url,
- thumbnail_url=video_thumb_url,
- user_id=user_id,
- is_reaction_video=1
- )
- new_reaction_vid.save()
- main_video.reactions.add(new_reaction_vid)
- vid_creator.reaction_videos.add(new_reaction_vid)
- response = {'status':'success', 'reaction_vid_id' : new_reaction_vid.id, 'video_url' : video_url, 'video_thumb_url':video_thumb_url}
- else:
- response = {'status':'failed', 'msg' : 'Failed to create reaction, try again!'}
- return json.dumps(response)
- @staticmethod
- def recentVideoFeed(user_id):
- posts = Post.objects.all().order_by('-date_created')
- list_of_posts = []
- main_user = User.objects.get(pk=user_id)
- for post in posts:
- already_recorded_for_post = 0
- already_liked_post = 0
- if post in main_user.liked_posts.all():
- already_liked_post = 1
- video = Video.objects.get(pk=post.video_id)
- reactions = video.reactions.all().order_by('-score')
- reactions_list = []
- post_user = User.objects.get(pk=post.user_id)
- for reaction in reactions:
- if reaction in main_user.reaction_videos.all():
- already_recorded_for_post = 1
- user = User.objects.get(pk=reaction.user_id)
- to_add = {
- 'video_url':reaction.video_url,
- 'video_thumb_url':reaction.thumbnail_url,
- 'score':reaction.score,
- 'username':user.username,
- 'user_id':user.id,
- 'profile_pic':user.profile_pic
- }
- reactions_list.append(to_add)
- to_append = {
- 'post_id': post.id,
- 'video_url':video.video_url,
- 'video_thumb_url':video.thumbnail_url,
- 'reactions_count':len(reactions_list),
- 'likes':post.likes,
- 'loops':post.loops,
- 'username':post_user.username,
- 'user_id':post_user.id,
- 'reactions':list(reactions_list),
- 'profile_pic':post_user.profile_pic,
- 'date_created':str(post.date_created),
- 'title':post.title,
- 'is_top_pick':post.is_top_pick,
- 'already_liked_post':already_liked_post,
- 'already_recorded_reaction':already_recorded_for_post
- }
- list_of_posts.append(to_append)
- return json.dumps(list(list_of_posts))
- @staticmethod
- def topVideoFeed(user_id):
- posts = Post.objects.filter(is_top_pick=1)
- list_of_posts = []
- main_user = User.objects.get(pk=user_id)
- for post in posts:
- already_recorded_for_post = 0
- already_liked_post = 0
- video = Video.objects.get(pk=post.video_id)
- reactions = video.reactions.all().order_by('-score')
- reactions_list = []
- post_user = User.objects.get(pk=post.user_id)
- if post in main_user.liked_posts.all():
- already_liked_post = 1
- for reaction in reactions:
- if reaction in main_user.reaction_videos.all():
- already_recorded_for_post = 1
- user = User.objects.get(pk=reaction.user_id)
- to_add = {
- 'video_url':reaction.video_url,
- 'video_thumb_url':reaction.thumbnail_url,
- 'score':reaction.score,
- 'username':user.username,
- 'user_id':user.id,
- 'profile_pic':user.profile_pic
- }
- reactions_list.append(to_add)
- # video.video_url = video.video_url.replace('muvie.s3.amazonaws.com','d2ttl824hypyff.cloudfront.net')
- # video.thumbnail_url = video.thumbnail_url.replace('muvie.s3.amazonaws.com','d2ttl824hypyff.cloudfront.net')
- # video.save()
- to_append = {
- 'post_id': post.id,
- 'video_url':video.video_url,
- 'video_thumb_url':video.thumbnail_url,
- 'reactions_count':len(reactions_list),
- 'likes':post.likes,
- 'loops':post.loops,
- 'username':post_user.username,
- 'user_id':post_user.id,
- 'reactions':list(reactions_list),
- 'profile_pic':post_user.profile_pic,
- 'date_created':str(post.date_created),
- 'title':post.title,
- 'is_top_pick':post.is_top_pick,
- 'already_liked_post':already_liked_post,
- 'already_recorded_reaction':already_recorded_for_post
- }
- list_of_posts.append(to_append)
- return json.dumps(list(list_of_posts))
- @staticmethod
- def followingVideoFeed(user_id):
- posts = Post.objects.all().order_by('?')
- list_of_posts = []
- main_user = User.objects.get(pk=user_id)
- # for post in posts:
- # post.delete()
- ##return ''
- for post in posts:
- already_recorded_for_post = 0
- already_liked_post = 0
- if post in main_user.liked_posts.all():
- already_liked_post = 1
- video = Video.objects.get(pk=post.video_id)
- reactions = video.reactions.all().order_by('-score')
- reactions_list = []
- post_user = User.objects.get(pk=post.user_id)
- for reaction in reactions:
- if reaction in main_user.reaction_videos.all():
- already_recorded_for_post = 1
- user = User.objects.get(pk=reaction.user_id)
- to_add = {
- 'video_url':reaction.video_url,
- 'video_thumb_url':reaction.thumbnail_url,
- 'score':reaction.score,
- 'username':user.username,
- 'user_id':user.id,
- 'profile_pic':user.profile_pic
- }
- reactions_list.append(to_add)
- to_append = {
- 'post_id': post.id,
- 'video_url':video.video_url,
- 'video_thumb_url':video.thumbnail_url,
- 'reactions_count':len(reactions_list),
- 'likes':post.likes,
- 'loops':post.loops,
- 'username':post_user.username,
- 'user_id':post_user.id,
- 'reactions':list(reactions_list),
- 'profile_pic':post_user.profile_pic,
- 'date_created':str(post.date_created),
- 'title':post.title,
- 'is_top_pick':post.is_top_pick,
- 'already_liked_post':already_liked_post,
- 'already_recorded_reaction':already_recorded_for_post
- }
- list_of_posts.append(to_append)
- return json.dumps(list(list_of_posts))
- @staticmethod
- def userVideoFeed(user_id, other_user_id):
- posts = Post.objects.filter(user_id=other_user_id)
- list_of_posts = []
- main_user = User.objects.get(pk=user_id)
- for post in posts:
- already_recorded_for_post = 0
- already_liked_post = 0
- video = Video.objects.get(pk=post.video_id)
- reactions = video.reactions.all().order_by('-score')
- reactions_list = []
- post_user = User.objects.get(pk=post.user_id)
- if post in main_user.liked_posts.all():
- already_liked_post = 1
- for reaction in reactions:
- if reaction in main_user.reaction_videos.all():
- already_recorded_for_post = 1
- user = User.objects.get(pk=reaction.user_id)
- to_add = {
- 'video_url':reaction.video_url,
- 'video_thumb_url':reaction.thumbnail_url,
- 'score':reaction.score,
- 'username':user.username,
- 'user_id':user.id,
- 'profile_pic':user.profile_pic
- }
- reactions_list.append(to_add)
- to_append = {
- 'post_id': post.id,
- 'video_url':video.video_url,
- 'video_thumb_url':video.thumbnail_url,
- 'reactions_count':len(reactions_list),
- 'likes':post.likes,
- 'loops':post.loops,
- 'username':post_user.username,
- 'user_id':post_user.id,
- 'reactions':list(reactions_list),
- 'profile_pic':post_user.profile_pic,
- 'date_created':str(post.date_created),
- 'title':post.title,
- 'already_recorded_reaction':already_recorded_for_post,
- 'already_liked_post':already_liked_post
- }
- list_of_posts.append(to_append)
- return json.dumps(list(list_of_posts))
- @staticmethod
- def videoDetails(user_id, post_id):
- main_user = User.objects.get(pk=user_id)
- post = Post.objects.get(pk=post_id)
- video = Video.objects.get(pk=post.video_id)
- reactions = video.reactions.all().order_by('-score')
- reactions_list = []
- post_user = User.objects.get(pk=post.user_id)
- already_recored = 0
- already_recored_vid_url = ''
- already_recored_vid_thumb_url = ''
- for video in main_user.reaction_videos.all():
- if video in reactions:
- already_recored = 1
- already_recored_vid_url = video.video_url
- already_recored_vid_thumb_url = video.thumbnail_url
- for reaction in reactions:
- user = User.objects.get(pk=reaction.user_id)
- ##check for if we are following the user
- if main_user in user.followers.all():
- is_following = 1
- else:
- is_following = 0
- # 0 none 1 downvote 2 upvote
- reaction_vid_vote = 0
- if reaction in main_user.liked_reactions.all():
- reaction_vid_vote = 2
- elif reaction in main_user.disliked_reactions.all():
- reaction_vid_vote = 1
- to_add = {
- 'video_url':reaction.video_url,
- 'video_thumb_url':reaction.thumbnail_url,
- 'score':reaction.score,
- 'username':user.username,
- 'user_id':user.id,
- 'profile_pic':user.profile_pic,
- 'is_following':is_following,
- 'total_reactions':len(user.reaction_videos.all()),
- 'reaction_vid_vote':reaction_vid_vote
- }
- reactions_list.append(to_add)
- to_append = {
- 'post_id': post.id,
- 'video_url':video.video_url,
- 'video_thumb_url':video.thumbnail_url,
- 'reactions_count':len(reactions_list),
- 'likes':post.likes,
- 'loops':post.loops,
- 'username':post_user.username,
- 'user_id':post_user.id,
- 'reactions':list(reactions_list),
- 'profile_pic':post_user.profile_pic,
- 'date_created':str(post.date_created),
- 'title':post.title,
- 'already_recorded':already_recored,
- 'already_recorded_vid_url': already_recored_vid_url,
- 'already_recorded_vid_thumb_url':already_recored_vid_thumb_url
- }
- return json.dumps({'data':to_append})
- @staticmethod
- def loop(post_id, count):
- the_post = Post.objects.get(pk=post_id)
- the_count = the_post.loops
- the_post.loops = the_count + int(count)
- the_post.save()
- return json.dumps({'status':'success'})
- @staticmethod
- def like(user_id, post_id):
- the_user = User.objects.get(pk=user_id)
- the_post = Post.objects.get(pk=post_id)
- the_user.liked_posts.add(the_post)
- the_count = the_post.likes
- the_post.likes = the_count + 1
- the_post.save()
- return json.dumps({'status':'success'})
- #VIDEO MODEL
- class Video(models.Model):
- video_url = models.CharField(max_length=300)
- thumbnail_url = models.CharField(max_length=300)
- reactions = models.ManyToManyField('self' , symmetrical=False, related_name='reactionVideos')
- user_id = models.CharField(max_length=300)
- score = models.IntegerField(default=0)
- is_reaction_video = models.IntegerField(default=0)
- @staticmethod
- def likeReaction(video_url, user_id):
- the_user = User.objects.get(pk=user_id)
- the_video = Video.objects.filter(video_url=video_url)
- if(len(the_video) != 0):
- true_video = Video.objects.get(pk=the_video[0].id)
- true_video.score = true_video.score + 1
- true_video.save()
- the_user.liked_reactions.add(true_video)
- return json.dumps({'status':'success', 'score': true_video.score})
- else:
- return json.dumps({'status':'fail', 'msg':'No video found.'})
- @staticmethod
- def dislikeReaction(video_url, user_id):
- the_user = User.objects.get(pk=user_id)
- the_video = Video.objects.filter(video_url=video_url)
- if(len(the_video) != 0):
- true_video = Video.objects.get(pk=the_video[0].id)
- true_video.score = true_video.score - 1
- true_video.save()
- the_user.disliked_reactions.add(true_video)
- if(true_video.score < 0):
- true_video.score = 0
- true_video.save()
- return json.dumps({'status':'success', 'score': true_video.score})
- else:
- return json.dumps({'status':'fail', 'msg':'No video found.'})
- #UTILITY MODEL
- class Utility():
- @staticmethod
- def uploadVideo(request):
- #Prepare Contents
- file_key = str(int(round(time.time() * 1000)))+".mp4"
- save_path = "uploads/"+file_key
- content = base64.b64decode( string.replace( request.POST['video'].strip(), " ", "+") )
- #Save File to S3
- api_key = "AKIAIOXJUFMM4NWOYZFQ"
- api_secret = "zfTrCj/6PZHfWkkk17LOowdVzqNMu4TDai5u/Ovm"
- conn = S3Connection(api_key, api_secret)
- bucket = conn.get_bucket('muvie')
- k = Key(bucket)
- k.key = file_key
- k.set_contents_from_string(content)
- k.make_public()
- #Return Link to File
- link = "https://d2ttl824hypyff.cloudfront.net/"+file_key
- response = {'status':'success', 'msg':'video uploaded', 'link':link}
- return json.dumps(response)
- @staticmethod
- def createThumb(link_incoming):
- api_key = "AKIAIOXJUFMM4NWOYZFQ"
- api_secret = "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"
- conn = S3Connection(api_key, api_secret)
- bucket = conn.get_bucket('muvie')
- size = 128, 128
- file_key_base = str(int(round(time.time() * 1000)))
- #Retrieve our source image from a URL
- fp = urllib.urlopen(link_incoming)
- #Load the URL data into an image
- img = cStringIO.StringIO(fp.read())
- im = Image.open(img)
- #Resize the image
- im.thumbnail(size)
- #NOTE, we're saving the image into a cStringIO object to avoid writing to disk
- out_im2 = cStringIO.StringIO()
- #You MUST specify the file type because there is no file name to discern it from
- im.save(out_im2, 'JPEG')
- # im.save(file_key_base + '_thumb.jpg', "JPEG")
- #Connect to bucket and create key
- file_key_2 = file_key_base + '_thumb.jpg'
- k2 = Key(bucket)
- k2.key = file_key_2
- k2.set_contents_from_string(out_im2.getvalue())
- k2.make_public()
- link2 = "https://d2ttl824hypyff.cloudfront.net/"+file_key_2
- return link2
- @staticmethod
- def uploadImage(request):
- #Prepare Contents
- if 'http' in request.POST['image']:
- response = {'status':'success', 'msg':'image uploaded', 'link':request.POST['image'], 'thumb_link':request.POST['image']}
- return json.dumps(response)
- file_key_base = str(int(round(time.time() * 1000)))
- file_key = file_key_base+".jpg"
- save_path = "uploads/"+file_key
- content = base64.b64decode( string.replace( request.POST['image'].strip(), " ", "+") )
- #Save File to S3
- api_key = "AKIAIOXJUFMM4NWOYZFQ"
- api_secret = "zfTrCj/6PZHfWkkk17LOowdVzqNMu4TDai5u/Ovm"
- conn = S3Connection(api_key, api_secret)
- bucket = conn.get_bucket('muvie')
- k = Key(bucket)
- k.key = file_key
- k.set_contents_from_string(content)
- k.make_public()
- size = 128, 128
- #Return Link to File
- link = "https://d2ttl824hypyff.cloudfront.net/"+file_key
- #Retrieve our source image from a URL
- fp = urllib.urlopen(link)
- #Load the URL data into an image
- img = cStringIO.StringIO(fp.read())
- im = Image.open(img)
- #Resize the image
- im.thumbnail(size)
- #NOTE, we're saving the image into a cStringIO object to avoid writing to disk
- out_im2 = cStringIO.StringIO()
- #You MUST specify the file type because there is no file name to discern it from
- im.save(out_im2, 'JPEG')
- # im.save(file_key_base + '_thumb.jpg', "JPEG")
- #Connect to bucket and create key
- file_key_2 = file_key_base + '_thumb.jpg'
- k2 = Key(bucket)
- k2.key = file_key_2
- k2.set_contents_from_string(out_im2.getvalue())
- k2.make_public()
- link2 = "https://d2ttl824hypyff.cloudfront.net/"+file_key_2
- #Note we're setting contents from the in-memory string provided by cStringIO
- response = {'status':'success', 'msg':'image uploaded', 'link':link, 'thumb_link':link2}
- return json.dumps(response)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement