Advertisement
Guest User

DJango Models and Backend for a Video App

a guest
Apr 4th, 2016
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 42.70 KB | None | 0 0
  1. from django.db import models
  2. from django.utils import timezone
  3. from django.db.models import Q
  4. from boto.sns import SNSConnection
  5. from django.core.mail import EmailMessage
  6. from random import choice
  7. from geoposition.fields import GeopositionField
  8. import json
  9. import datetime
  10. import math
  11. import hashlib
  12. import string
  13. import uuid
  14. import time
  15. import random
  16. import base64
  17. import boto
  18. import cStringIO
  19. import urllib
  20. from PIL import Image
  21. from boto.s3.connection import S3Connection
  22. from boto.s3.key import Key
  23.  
  24. # Create your models here.
  25.  
  26. #USER MODEL
  27. class User(models.Model):
  28. username = models.CharField(max_length=300)
  29. facebook_id = models.CharField(max_length=300)
  30. first_name = models.CharField(max_length=300)
  31. full_name = models.CharField(max_length=300, default='')
  32. last_name = models.CharField(max_length=300)
  33. gender = models.CharField(max_length=300, default='')
  34. profile_pic = models.CharField(max_length=300, default='')
  35. website = models.CharField(max_length=300, default='')
  36. bio = models.CharField(max_length=300, default='')
  37. date_joined = models.DateTimeField('date joined')
  38. last_login = models.DateTimeField('last login')
  39. email = models.EmailField(unique=True)
  40. lat = models.FloatField(default=0)
  41. lng = models.FloatField(default=0)
  42. device_token = models.CharField(max_length=300)
  43. device_type = models.CharField(max_length=300)
  44. password = models.CharField(max_length=300)
  45. push_notifications = models.IntegerField(default=1)
  46. email_notifications = models.IntegerField(default=1)
  47. followers = models.ManyToManyField('self', symmetrical=False)
  48. posts = models.ManyToManyField('Post', symmetrical=False)
  49. reposts = models.ManyToManyField('Post', symmetrical=False, related_name='Reposts')
  50. liked_posts = models.ManyToManyField('Post', symmetrical=False, related_name='LikedPosts')
  51. reaction_videos = models.ManyToManyField('Video', symmetrical=False)
  52. liked_reactions = models.ManyToManyField('Video', symmetrical=False, related_name='LikedReactions')
  53. disliked_reactions = models.ManyToManyField('Video', symmetrical=False, related_name='DisLikedReactions')
  54. is_suggested = models.IntegerField(default=0)
  55. phone = models.CharField(max_length=300, default='')
  56.  
  57. ##CREATE USER OR RETURN EXISTING ONE FACEBOOK LOGIN##
  58. @staticmethod
  59. def loginWithFacebook(fb_id, first_name, last_name, email, device_token, device_type, profile_pic):
  60. #Check if user already exists in our system
  61. user = User.objects.filter(facebook_id=fb_id)
  62.  
  63. user_email = User.objects.filter(email=email)
  64.  
  65. if len(user)!=0:
  66. #Found user record
  67. user = User.objects.get(pk=user[0].id)
  68. user.last_login = timezone.now()
  69. user.device_token = device_token
  70. user.device_type = device_type
  71. user.profile_pic = profile_pic
  72. user.full_name = str(first_name + '' + last_name)
  73. user.save()
  74. response = {'status':'success', 'user_id':user.id}
  75.  
  76. return json.dumps(response)
  77.  
  78. elif len(user_email)!=0:
  79.  
  80. user = User.objects.get(pk=user_email[0].id)
  81. user.last_login = timezone.now()
  82. user.facebook_id = fb_id
  83. user.first_name = first_name
  84. user.last_name = last_name
  85. user.profile_pic = profile_pic
  86. user.device_token = device_token
  87. user.device_type = device_type
  88. user.full_name = str(first_name + ' ' + last_name)
  89. user.username = str(first_name) + str(last_name) + str(random.randrange(0,1000))
  90. user.save()
  91.  
  92. response = {'status':'success', 'user_id':user.id}
  93. return json.dumps(response)
  94.  
  95. else:
  96. #Create User Record
  97. new_user = User(facebook_id=fb_id,
  98. email=email,
  99. device_token=device_token,
  100. device_type=device_type,
  101. date_joined=timezone.now(),
  102. last_login=timezone.now(),
  103. profile_pic=profile_pic,
  104. first_name=first_name,
  105. last_name=last_name,
  106. password=fb_id,
  107. username=str(first_name) + str(last_name) + str(random.randrange(0,1000))
  108. )
  109. new_user.full_name = str(first_name + ' ' + last_name)
  110. new_user.save()
  111.  
  112. #Return Response
  113. response = {'status':'success', 'user_id':new_user.id}
  114. return json.dumps(response)
  115.  
  116. return ""
  117.  
  118. ##UPDATE THE USER LOCATION CALL
  119. @staticmethod
  120. def updateUserLocation(user_id, lat, lng):
  121.  
  122. user = User.objects.get(pk=user_id)
  123. user.lat = lat
  124. user.lng = lng
  125. user.save()
  126.  
  127. response = {'msg':'user location updated'}
  128. return json.dumps(response)
  129.  
  130. ##REGULAR REGISTER##
  131. @staticmethod
  132. def register(username, email, password, full_name, device_token, device_type, profile_pic, facebook_id):
  133.  
  134. check_user = User.objects.filter(username=username)
  135.  
  136. #Hash Password
  137. h = hashlib.md5()
  138. h.update(password)
  139.  
  140. ##CHECK TO SEE IF THERE IS A USER WITH THAT EMAIL ALREADY##
  141. if len(check_user) == 0:
  142.  
  143. check_email = User.objects.filter(email=email)
  144.  
  145. if len(check_email) == 0:
  146.  
  147. new_user = User(
  148. username=username,
  149. email=email,
  150. device_token=device_token,
  151. device_type=device_type,
  152. date_joined=timezone.now(),
  153. last_login=timezone.now(),
  154. password=h.hexdigest(),
  155. facebook_id=facebook_id,
  156. full_name=full_name,
  157. profile_pic=profile_pic
  158. )
  159.  
  160. new_user.save()
  161.  
  162. response = {'status':'success', 'user_id' : new_user.id, 'profile_pic':new_user.profile_pic}
  163.  
  164. else:
  165. response = {'status':'failed', 'msg' : 'That email is registered to another user. Please login to proceed.'}
  166.  
  167. else:
  168. response = {'status':'failed', 'msg' : 'That username is taken. Please try another username.'}
  169.  
  170. return json.dumps(response)
  171.  
  172. ##LOGIN USER##
  173. @staticmethod
  174. def login(username, password, device_token, device_type):
  175.  
  176. h = hashlib.md5()
  177. h.update(password)
  178.  
  179. user = User.objects.filter(username=username, password=h.hexdigest())
  180.  
  181. if(len(user) > 0):
  182. ##WE FOUND THE USER SO LETS JUST RETURN A TRUE
  183. user_found = user[0]
  184. user_found.last_login = timezone.now()
  185. user_found.device_token = device_token
  186. user_found.device_type = device_type
  187. user_found.save()
  188.  
  189. response = {'status':'success', 'user_id':user_found.id, 'profile_pic':user_found.profile_pic}
  190.  
  191. else:
  192. response = {'status':'failed', 'msg':'There was an issue logging you in, please check your username/password combination.'}
  193.  
  194.  
  195. return json.dumps(response)
  196.  
  197. ##FORGOT PASSWORD##
  198. @staticmethod
  199. def forgotPassword(email):
  200.  
  201. the_user = User.objects.filter(email=email)
  202.  
  203. if len(the_user) == 0:
  204. response = {'status':'failed' , 'msg' : 'We do not recognize the email you provided.' }
  205. return json.dumps(response)
  206. else:
  207. #Generate New Password
  208. user = User.objects.get(pk=the_user[0].id)
  209.  
  210. chars = string.letters + string.digits
  211. length = 8
  212. password = ''.join(choice(chars) for _ in xrange(length))
  213. print("new password: ",password)
  214.  
  215. #Generate Password Hash
  216. h = hashlib.md5()
  217. h.update( password )
  218. hash = h.hexdigest()
  219. print("password hashed: ",hash)
  220.  
  221. #Save New Password
  222. user.password = hash;
  223. user.save()
  224. print("user password reset")
  225.  
  226. #Get Email
  227. body = open('templates/emails/forgot_password.html', 'r+')
  228. body = body.read()
  229. body = string.replace(body, "{{password}}", password)
  230. print("rendered template")
  231.  
  232. #Send Email
  233. subject = "Reset Password"
  234. from_email = "noreply@butterfingerz.com"
  235. to_emails = [user.email]
  236. email = EmailMessage(subject, body, from_email, to_emails)
  237. email.content_subtype = "html"
  238. email.send()
  239. print("email sent")
  240.  
  241. print ("password reset success")
  242. #Send Home
  243.  
  244. response = {'status':'success' , 'msg' : 'We have sent a new password to the email you provided.' }
  245. return json.dumps(response)
  246.  
  247. ##UPDATE USER INFO
  248. @staticmethod
  249. def updateUserInfo(user_id, username, bio, website, email, profile_pic, full_name):
  250.  
  251. user = User.objects.get(pk=user_id)
  252.  
  253. user.bio = bio
  254. user.full_name = full_name
  255. user.website = website
  256.  
  257. if profile_pic != '':
  258. user.profile_pic = profile_pic
  259.  
  260. user.save()
  261.  
  262. if username == user.username and email == user.email:
  263.  
  264. response = {'status':'success', 'user_id' : user.id}
  265. return json.dumps(response)
  266.  
  267. else:
  268.  
  269. username_check = User.objects.filter(username=username).exclude(id=user.id)
  270.  
  271. if len(username_check) == 0:
  272.  
  273. email_check = User.objects.filter(email=email).exclude(id=user.id)
  274.  
  275. if len(email_check) == 0:
  276. user.email = email
  277. user.bio = bio
  278. user.full_name = full_name
  279. user.website = website
  280. user.username = username
  281. user.save()
  282. response = {'status':'success', 'user_id' : user.id}
  283. return json.dumps(response)
  284.  
  285. else:
  286. response = {'status':'failed', 'msg' : 'That email you choose is not avaliable.'}
  287. else:
  288. response = {'status':'failed', 'msg' : 'That username you have choosen is not avaliable.'}
  289.  
  290. return json.dumps(response)
  291.  
  292. ##FOLLOW USER
  293. @staticmethod
  294. def followUser(user_id, to_follow_id):
  295.  
  296. main_user = User.objects.get(pk=user_id)
  297. to_follow_user = User.objects.get(pk=to_follow_id)
  298.  
  299. to_follow_user.followers.add(main_user)
  300.  
  301. return json.dumps({'status':'success'})
  302.  
  303. ##UNFOLLOW USER
  304. @staticmethod
  305. def unFollowUser(user_id, to_follow_id):
  306.  
  307. main_user = User.objects.get(pk=user_id)
  308. to_follow_user = User.objects.get(pk=to_follow_id)
  309.  
  310. to_follow_user.followers.remove(main_user)
  311.  
  312. return json.dumps({'status':'success'})
  313.  
  314. ##GET USER INFO
  315. @staticmethod
  316. def userInfo(user_id, info_id):
  317.  
  318. main_user = User.objects.get(pk=user_id)
  319. info_user = User.objects.get(pk=info_id)
  320.  
  321. following = User.objects.filter(followers__id=info_id)
  322.  
  323. is_following = User.objects.filter(id=info_id, followers__id=user_id)
  324.  
  325. posts_count = Post.objects.filter(user_id=info_id).count()
  326.  
  327. total_score = 0
  328.  
  329. for vid in info_user.reaction_videos.all():
  330.  
  331. total_score = total_score + vid.score
  332.  
  333. to_return = {
  334.  
  335. 'profile_pic':info_user.profile_pic,
  336. 'num_following':len(following),
  337. 'num_followers':len(info_user.followers.all()),
  338. 'username':info_user.username,
  339. 'bio':info_user.bio,
  340. 'website':info_user.website,
  341. 'total_reactions':len(info_user.reaction_videos.all()),
  342. 'is_following':len(is_following),
  343. 'full_name':info_user.full_name,
  344. 'email':info_user.email,
  345. 'total_videos':posts_count,
  346. 'total_reposts':info_user.reposts.all().count(),
  347. 'total_score':total_score
  348. }
  349.  
  350. return json.dumps(to_return)
  351.  
  352. @staticmethod
  353. def searchUsers(query,user_id):
  354.  
  355. users = User.objects.filter(username__icontains=query)
  356.  
  357. list_return = []
  358.  
  359. for user in users:
  360.  
  361. main_user = User.objects.get(pk=user_id)
  362. info_user = User.objects.get(pk=user.id)
  363.  
  364. following = User.objects.filter(followers__id=user.id)
  365.  
  366. is_following = User.objects.filter(id=user.id, followers__id=user_id)
  367.  
  368. total_score = 0
  369.  
  370. for vid in user.reaction_videos.all():
  371.  
  372. total_score = total_score + vid.score
  373.  
  374. to_return = {
  375.  
  376. 'profile_pic':info_user.profile_pic,
  377. 'num_following':len(following),
  378. 'num_followers':len(info_user.followers.all()),
  379. 'username':info_user.username,
  380. 'bio':info_user.bio,
  381. 'website':info_user.website,
  382. 'total_reactions':len(info_user.reaction_videos.all()),
  383. 'is_following':len(is_following),
  384. 'user_id':user.id,
  385. 'total_score':total_score
  386. }
  387.  
  388. list_return.append(to_return)
  389.  
  390. return json.dumps(list(list_return))
  391.  
  392. @staticmethod
  393. def suggestedUsers(user_id):
  394.  
  395. users = User.objects.filter(is_suggested=1)
  396.  
  397. list_return = []
  398.  
  399. for user in users:
  400.  
  401. main_user = User.objects.get(pk=user_id)
  402. info_user = User.objects.get(pk=user.id)
  403.  
  404. following = User.objects.filter(followers__id=user.id)
  405.  
  406. is_following = User.objects.filter(id=user.id, followers__id=user_id)
  407.  
  408. total_score = 0
  409.  
  410. for vid in user.reaction_videos.all():
  411.  
  412. total_score = total_score + vid.score
  413.  
  414. to_return = {
  415.  
  416. 'profile_pic':info_user.profile_pic,
  417. 'num_following':len(following),
  418. 'num_followers':len(info_user.followers.all()),
  419. 'username':info_user.username,
  420. 'bio':info_user.bio,
  421. 'website':info_user.website,
  422. 'total_reactions':len(info_user.reaction_videos.all()),
  423. 'is_following':len(is_following),
  424. 'user_id':user.id,
  425. 'total_score':total_score
  426.  
  427. }
  428.  
  429. list_return.append(to_return)
  430.  
  431. return json.dumps(list(list_return))
  432.  
  433. @staticmethod
  434. def facebookContacts(user_id):
  435.  
  436. users = User.objects.filter(is_suggested=1)
  437.  
  438. list_return = []
  439.  
  440. for user in users:
  441.  
  442. main_user = User.objects.get(pk=user_id)
  443. info_user = User.objects.get(pk=user.id)
  444.  
  445. following = User.objects.filter(followers__id=user.id)
  446.  
  447. is_following = User.objects.filter(id=user.id, followers__id=user_id)
  448.  
  449. total_score = 0
  450.  
  451. for vid in user.reaction_videos.all():
  452.  
  453. total_score = total_score + vid.score
  454.  
  455. to_return = {
  456.  
  457. 'profile_pic':info_user.profile_pic,
  458. 'num_following':len(following),
  459. 'num_followers':len(info_user.followers.all()),
  460. 'username':info_user.username,
  461. 'bio':info_user.bio,
  462. 'website':info_user.website,
  463. 'total_reactions':len(info_user.reaction_videos.all()),
  464. 'is_following':len(is_following),
  465. 'user_id':user.id,
  466. 'total_score':total_score
  467.  
  468. }
  469.  
  470. list_return.append(to_return)
  471.  
  472. return json.dumps(list(list_return))
  473.  
  474. @staticmethod
  475. def phoneContacts(user_id):
  476.  
  477. users = User.objects.filter(is_suggested=1)
  478.  
  479. list_return = []
  480.  
  481. for user in users:
  482.  
  483. main_user = User.objects.get(pk=user_id)
  484. info_user = User.objects.get(pk=user.id)
  485.  
  486. following = User.objects.filter(followers__id=user.id)
  487.  
  488. is_following = User.objects.filter(id=user.id, followers__id=user_id)
  489.  
  490. total_score = 0
  491.  
  492. for vid in user.reaction_videos.all():
  493.  
  494. total_score = total_score + vid.score
  495.  
  496. to_return = {
  497.  
  498. 'profile_pic':info_user.profile_pic,
  499. 'num_following':len(following),
  500. 'num_followers':len(info_user.followers.all()),
  501. 'username':info_user.username,
  502. 'bio':info_user.bio,
  503. 'website':info_user.website,
  504. 'total_reactions':len(info_user.reaction_videos.all()),
  505. 'is_following':len(is_following),
  506. 'user_id':user.id,
  507. 'total_score':total_score
  508.  
  509. }
  510.  
  511. list_return.append(to_return)
  512.  
  513. return json.dumps(list(list_return))
  514.  
  515. @staticmethod
  516. def leaderboardUsersAllTime(user_id):
  517.  
  518. users = User.objects.all()
  519.  
  520. list_return = []
  521.  
  522. for user in users:
  523.  
  524. main_user = User.objects.get(pk=user_id)
  525. info_user = User.objects.get(pk=user.id)
  526.  
  527. following = User.objects.filter(followers__id=user.id)
  528.  
  529. is_following = User.objects.filter(id=user.id, followers__id=user_id)
  530.  
  531. total_score = 0
  532.  
  533. for vid in user.reaction_videos.all():
  534.  
  535. total_score = total_score + vid.score
  536.  
  537. to_return = {
  538.  
  539. 'profile_pic':info_user.profile_pic,
  540. 'num_following':len(following),
  541. 'num_followers':len(info_user.followers.all()),
  542. 'username':info_user.username,
  543. 'bio':info_user.bio,
  544. 'website':info_user.website,
  545. 'total_reactions':len(info_user.reaction_videos.all()),
  546. 'is_following':len(is_following),
  547. 'user_id':user.id,
  548. 'total_score':total_score
  549. }
  550.  
  551. list_return.append(to_return)
  552.  
  553. newlist = sorted(list_return, key=lambda k: k['total_score'], reverse=True)[:100]
  554.  
  555. return json.dumps(list(newlist))
  556.  
  557. @staticmethod
  558. def leaderboardUsersToday(user_id):
  559.  
  560. users = User.objects.all()
  561.  
  562. list_return = []
  563.  
  564. for user in users:
  565.  
  566. main_user = User.objects.get(pk=user_id)
  567. info_user = User.objects.get(pk=user.id)
  568.  
  569. following = User.objects.filter(followers__id=user.id)
  570.  
  571. is_following = User.objects.filter(id=user.id, followers__id=user_id)
  572.  
  573. total_score = 0
  574.  
  575. for vid in user.reaction_videos.all():
  576.  
  577. total_score = total_score + vid.score
  578.  
  579. to_return = {
  580.  
  581. 'profile_pic':info_user.profile_pic,
  582. 'num_following':len(following),
  583. 'num_followers':len(info_user.followers.all()),
  584. 'username':info_user.username,
  585. 'bio':info_user.bio,
  586. 'website':info_user.website,
  587. 'total_reactions':len(info_user.reaction_videos.all()),
  588. 'is_following':len(is_following),
  589. 'user_id':user.id,
  590. 'total_score':total_score
  591. }
  592.  
  593. list_return.append(to_return)
  594.  
  595. newlist = sorted(list_return, key=lambda k: k['total_score'], reverse=True)[:100]
  596.  
  597. return json.dumps(list(newlist))
  598.  
  599. @staticmethod
  600. def userReactionVideos(user_id):
  601.  
  602. user = User.objects.get(pk=user_id)
  603. reactions_list = []
  604. all_reactions = user.reaction_videos.all().order_by('-score')
  605.  
  606. for reaction in all_reactions:
  607. to_add = {
  608. 'video_url':reaction.video_url,
  609. 'video_thumb_url':reaction.thumbnail_url,
  610. 'score':reaction.score,
  611. 'username':user.username,
  612. 'user_id':user.id,
  613. 'profile_pic':user.profile_pic
  614. }
  615. reactions_list.append(to_add)
  616.  
  617. to_return = {'reactions':list(reactions_list)}
  618.  
  619. return json.dumps(to_return)
  620.  
  621. @staticmethod
  622. def rePost(post_id, user_id):
  623.  
  624. the_user = User.objects.get(pk=user_id)
  625. the_post = Post.objects.get(pk=post_id)
  626.  
  627. the_user.reposts.add(the_post)
  628.  
  629. return json.dumps({'status':'success'})
  630.  
  631. @staticmethod
  632. def rePostFeed(user_id):
  633.  
  634. main_user = User.objects.get(pk=user_id)
  635. posts = main_user.reposts.all()
  636. list_of_posts = []
  637.  
  638. for post in posts:
  639.  
  640. already_recorded_for_post = 0
  641. video = Video.objects.get(pk=post.video_id)
  642. reactions = video.reactions.all()
  643. reactions_list = []
  644. post_user = User.objects.get(pk=post.user_id)
  645.  
  646. for reaction in reactions:
  647.  
  648. if reaction in main_user.reaction_videos.all():
  649. already_recorded_for_post = 1
  650.  
  651. user = User.objects.get(pk=reaction.user_id)
  652. to_add = {
  653. 'video_url':reaction.video_url,
  654. 'video_thumb_url':reaction.thumbnail_url,
  655. 'score':reaction.score,
  656. 'username':user.username,
  657. 'user_id':user.id,
  658. 'profile_pic':user.profile_pic
  659. }
  660. reactions_list.append(to_add)
  661.  
  662. to_append = {
  663. 'post_id': post.id,
  664. 'video_url':video.video_url,
  665. 'video_thumb_url':video.thumbnail_url,
  666. 'reactions_count':len(reactions_list),
  667. 'likes':post.likes,
  668. 'loops':post.loops,
  669. 'username':post_user.username,
  670. 'user_id':post_user.id,
  671. 'reactions':list(reactions_list),
  672. 'profile_pic':post_user.profile_pic,
  673. 'date_created':str(post.date_created),
  674. 'title':post.title,
  675. 'is_top_pick':post.is_top_pick,
  676. 'already_recorded_reaction':already_recorded_for_post
  677. }
  678.  
  679. list_of_posts.append(to_append)
  680.  
  681. return json.dumps(list(list_of_posts))
  682.  
  683. #POST MODEL
  684. class Post(models.Model):
  685. video_id = models.CharField(max_length=300)
  686. user_id = models.CharField(max_length=300)
  687. likes = models.IntegerField(default=0)
  688. loops = models.IntegerField(default=0)
  689. date_created = models.DateTimeField('created date')
  690. title = models.CharField(max_length=300, default='')
  691. is_top_pick = models.IntegerField(default=0)
  692. tags = models.ManyToManyField('User', symmetrical=False)
  693.  
  694. @staticmethod
  695. def createPost(user_id, video_url, video_thumb_url, title, tags):
  696.  
  697. vid_creator = User.objects.get(pk=user_id)
  698.  
  699. video_thumb_url = Utility.createThumb(video_thumb_url)
  700.  
  701. if vid_creator != None:
  702.  
  703. new_vid = Video(video_url=video_url,
  704. thumbnail_url=video_thumb_url,
  705. user_id=user_id,
  706. is_reaction_video=0
  707. )
  708. new_vid.save()
  709.  
  710. new_post = Post(user_id=user_id,
  711. video_id=new_vid.id,
  712. title=title,
  713. date_created=timezone.now()
  714. )
  715. new_post.save()
  716.  
  717. vid_creator.posts.add(new_post)
  718.  
  719. for id in tags:
  720.  
  721. tagged = User.objects.get(pk=id)
  722. new_post.tags.add(tagged)
  723.  
  724.  
  725. response = {'status':'success', 'post_id' : new_post.id}
  726.  
  727. else:
  728. response = {'status':'failed', 'msg' : 'Failed to create new post, try again!'}
  729.  
  730. return json.dumps(response)
  731.  
  732. @staticmethod
  733. def createReactionVideo(user_id, post_id, video_url, video_thumb_url):
  734.  
  735. vid_creator = User.objects.get(pk=user_id)
  736.  
  737. video_thumb_url = Utility.createThumb(video_thumb_url)
  738.  
  739. post = Post.objects.get(pk=post_id)
  740.  
  741. if vid_creator != None and post != None:
  742.  
  743. main_video = Video.objects.get(pk=post.video_id)
  744.  
  745. if main_video != None:
  746.  
  747. new_reaction_vid = Video(video_url=video_url,
  748. thumbnail_url=video_thumb_url,
  749. user_id=user_id,
  750. is_reaction_video=1
  751. )
  752.  
  753. new_reaction_vid.save()
  754.  
  755. main_video.reactions.add(new_reaction_vid)
  756.  
  757. vid_creator.reaction_videos.add(new_reaction_vid)
  758.  
  759. response = {'status':'success', 'reaction_vid_id' : new_reaction_vid.id, 'video_url' : video_url, 'video_thumb_url':video_thumb_url}
  760.  
  761. else:
  762. response = {'status':'failed', 'msg' : 'Failed to create reaction, try again!'}
  763.  
  764. return json.dumps(response)
  765.  
  766. @staticmethod
  767. def recentVideoFeed(user_id):
  768.  
  769. posts = Post.objects.all().order_by('-date_created')
  770.  
  771. list_of_posts = []
  772.  
  773. main_user = User.objects.get(pk=user_id)
  774.  
  775. for post in posts:
  776.  
  777. already_recorded_for_post = 0
  778. already_liked_post = 0
  779.  
  780. if post in main_user.liked_posts.all():
  781. already_liked_post = 1
  782.  
  783. video = Video.objects.get(pk=post.video_id)
  784. reactions = video.reactions.all().order_by('-score')
  785.  
  786. reactions_list = []
  787. post_user = User.objects.get(pk=post.user_id)
  788.  
  789. for reaction in reactions:
  790.  
  791. if reaction in main_user.reaction_videos.all():
  792. already_recorded_for_post = 1
  793.  
  794. user = User.objects.get(pk=reaction.user_id)
  795. to_add = {
  796. 'video_url':reaction.video_url,
  797. 'video_thumb_url':reaction.thumbnail_url,
  798. 'score':reaction.score,
  799. 'username':user.username,
  800. 'user_id':user.id,
  801. 'profile_pic':user.profile_pic
  802. }
  803. reactions_list.append(to_add)
  804.  
  805. to_append = {
  806. 'post_id': post.id,
  807. 'video_url':video.video_url,
  808. 'video_thumb_url':video.thumbnail_url,
  809. 'reactions_count':len(reactions_list),
  810. 'likes':post.likes,
  811. 'loops':post.loops,
  812. 'username':post_user.username,
  813. 'user_id':post_user.id,
  814. 'reactions':list(reactions_list),
  815. 'profile_pic':post_user.profile_pic,
  816. 'date_created':str(post.date_created),
  817. 'title':post.title,
  818. 'is_top_pick':post.is_top_pick,
  819. 'already_liked_post':already_liked_post,
  820. 'already_recorded_reaction':already_recorded_for_post
  821. }
  822. list_of_posts.append(to_append)
  823.  
  824. return json.dumps(list(list_of_posts))
  825.  
  826. @staticmethod
  827. def topVideoFeed(user_id):
  828.  
  829. posts = Post.objects.filter(is_top_pick=1)
  830.  
  831. list_of_posts = []
  832.  
  833. main_user = User.objects.get(pk=user_id)
  834.  
  835. for post in posts:
  836.  
  837. already_recorded_for_post = 0
  838. already_liked_post = 0
  839. video = Video.objects.get(pk=post.video_id)
  840. reactions = video.reactions.all().order_by('-score')
  841. reactions_list = []
  842. post_user = User.objects.get(pk=post.user_id)
  843.  
  844. if post in main_user.liked_posts.all():
  845. already_liked_post = 1
  846.  
  847. for reaction in reactions:
  848.  
  849. if reaction in main_user.reaction_videos.all():
  850. already_recorded_for_post = 1
  851.  
  852. user = User.objects.get(pk=reaction.user_id)
  853.  
  854. to_add = {
  855. 'video_url':reaction.video_url,
  856. 'video_thumb_url':reaction.thumbnail_url,
  857. 'score':reaction.score,
  858. 'username':user.username,
  859. 'user_id':user.id,
  860. 'profile_pic':user.profile_pic
  861. }
  862. reactions_list.append(to_add)
  863.  
  864. # video.video_url = video.video_url.replace('muvie.s3.amazonaws.com','d2ttl824hypyff.cloudfront.net')
  865. # video.thumbnail_url = video.thumbnail_url.replace('muvie.s3.amazonaws.com','d2ttl824hypyff.cloudfront.net')
  866. # video.save()
  867.  
  868. to_append = {
  869. 'post_id': post.id,
  870. 'video_url':video.video_url,
  871. 'video_thumb_url':video.thumbnail_url,
  872. 'reactions_count':len(reactions_list),
  873. 'likes':post.likes,
  874. 'loops':post.loops,
  875. 'username':post_user.username,
  876. 'user_id':post_user.id,
  877. 'reactions':list(reactions_list),
  878. 'profile_pic':post_user.profile_pic,
  879. 'date_created':str(post.date_created),
  880. 'title':post.title,
  881. 'is_top_pick':post.is_top_pick,
  882. 'already_liked_post':already_liked_post,
  883. 'already_recorded_reaction':already_recorded_for_post
  884. }
  885. list_of_posts.append(to_append)
  886.  
  887. return json.dumps(list(list_of_posts))
  888.  
  889. @staticmethod
  890. def followingVideoFeed(user_id):
  891.  
  892. posts = Post.objects.all().order_by('?')
  893.  
  894. list_of_posts = []
  895.  
  896. main_user = User.objects.get(pk=user_id)
  897.  
  898. # for post in posts:
  899. # post.delete()
  900.  
  901. ##return ''
  902.  
  903. for post in posts:
  904.  
  905. already_recorded_for_post = 0
  906. already_liked_post = 0
  907.  
  908. if post in main_user.liked_posts.all():
  909. already_liked_post = 1
  910.  
  911. video = Video.objects.get(pk=post.video_id)
  912. reactions = video.reactions.all().order_by('-score')
  913.  
  914. reactions_list = []
  915. post_user = User.objects.get(pk=post.user_id)
  916.  
  917. for reaction in reactions:
  918.  
  919. if reaction in main_user.reaction_videos.all():
  920. already_recorded_for_post = 1
  921.  
  922. user = User.objects.get(pk=reaction.user_id)
  923. to_add = {
  924. 'video_url':reaction.video_url,
  925. 'video_thumb_url':reaction.thumbnail_url,
  926. 'score':reaction.score,
  927. 'username':user.username,
  928. 'user_id':user.id,
  929. 'profile_pic':user.profile_pic
  930. }
  931. reactions_list.append(to_add)
  932.  
  933. to_append = {
  934. 'post_id': post.id,
  935. 'video_url':video.video_url,
  936. 'video_thumb_url':video.thumbnail_url,
  937. 'reactions_count':len(reactions_list),
  938. 'likes':post.likes,
  939. 'loops':post.loops,
  940. 'username':post_user.username,
  941. 'user_id':post_user.id,
  942. 'reactions':list(reactions_list),
  943. 'profile_pic':post_user.profile_pic,
  944. 'date_created':str(post.date_created),
  945. 'title':post.title,
  946. 'is_top_pick':post.is_top_pick,
  947. 'already_liked_post':already_liked_post,
  948. 'already_recorded_reaction':already_recorded_for_post
  949. }
  950. list_of_posts.append(to_append)
  951.  
  952. return json.dumps(list(list_of_posts))
  953.  
  954. @staticmethod
  955. def userVideoFeed(user_id, other_user_id):
  956.  
  957. posts = Post.objects.filter(user_id=other_user_id)
  958.  
  959. list_of_posts = []
  960.  
  961. main_user = User.objects.get(pk=user_id)
  962.  
  963. for post in posts:
  964.  
  965. already_recorded_for_post = 0
  966. already_liked_post = 0
  967. video = Video.objects.get(pk=post.video_id)
  968. reactions = video.reactions.all().order_by('-score')
  969. reactions_list = []
  970. post_user = User.objects.get(pk=post.user_id)
  971.  
  972. if post in main_user.liked_posts.all():
  973. already_liked_post = 1
  974.  
  975. for reaction in reactions:
  976.  
  977. if reaction in main_user.reaction_videos.all():
  978. already_recorded_for_post = 1
  979.  
  980. user = User.objects.get(pk=reaction.user_id)
  981. to_add = {
  982. 'video_url':reaction.video_url,
  983. 'video_thumb_url':reaction.thumbnail_url,
  984. 'score':reaction.score,
  985. 'username':user.username,
  986. 'user_id':user.id,
  987. 'profile_pic':user.profile_pic
  988. }
  989. reactions_list.append(to_add)
  990.  
  991. to_append = {
  992. 'post_id': post.id,
  993. 'video_url':video.video_url,
  994. 'video_thumb_url':video.thumbnail_url,
  995. 'reactions_count':len(reactions_list),
  996. 'likes':post.likes,
  997. 'loops':post.loops,
  998. 'username':post_user.username,
  999. 'user_id':post_user.id,
  1000. 'reactions':list(reactions_list),
  1001. 'profile_pic':post_user.profile_pic,
  1002. 'date_created':str(post.date_created),
  1003. 'title':post.title,
  1004. 'already_recorded_reaction':already_recorded_for_post,
  1005. 'already_liked_post':already_liked_post
  1006. }
  1007. list_of_posts.append(to_append)
  1008.  
  1009. return json.dumps(list(list_of_posts))
  1010.  
  1011. @staticmethod
  1012. def videoDetails(user_id, post_id):
  1013.  
  1014. main_user = User.objects.get(pk=user_id)
  1015.  
  1016. post = Post.objects.get(pk=post_id)
  1017.  
  1018. video = Video.objects.get(pk=post.video_id)
  1019. reactions = video.reactions.all().order_by('-score')
  1020. reactions_list = []
  1021. post_user = User.objects.get(pk=post.user_id)
  1022.  
  1023. already_recored = 0
  1024. already_recored_vid_url = ''
  1025. already_recored_vid_thumb_url = ''
  1026.  
  1027. for video in main_user.reaction_videos.all():
  1028. if video in reactions:
  1029. already_recored = 1
  1030. already_recored_vid_url = video.video_url
  1031. already_recored_vid_thumb_url = video.thumbnail_url
  1032.  
  1033. for reaction in reactions:
  1034. user = User.objects.get(pk=reaction.user_id)
  1035.  
  1036. ##check for if we are following the user
  1037. if main_user in user.followers.all():
  1038. is_following = 1
  1039. else:
  1040. is_following = 0
  1041.  
  1042. # 0 none 1 downvote 2 upvote
  1043. reaction_vid_vote = 0
  1044. if reaction in main_user.liked_reactions.all():
  1045. reaction_vid_vote = 2
  1046. elif reaction in main_user.disliked_reactions.all():
  1047. reaction_vid_vote = 1
  1048.  
  1049. to_add = {
  1050. 'video_url':reaction.video_url,
  1051. 'video_thumb_url':reaction.thumbnail_url,
  1052. 'score':reaction.score,
  1053. 'username':user.username,
  1054. 'user_id':user.id,
  1055. 'profile_pic':user.profile_pic,
  1056. 'is_following':is_following,
  1057. 'total_reactions':len(user.reaction_videos.all()),
  1058. 'reaction_vid_vote':reaction_vid_vote
  1059. }
  1060.  
  1061. reactions_list.append(to_add)
  1062.  
  1063. to_append = {
  1064. 'post_id': post.id,
  1065. 'video_url':video.video_url,
  1066. 'video_thumb_url':video.thumbnail_url,
  1067. 'reactions_count':len(reactions_list),
  1068. 'likes':post.likes,
  1069. 'loops':post.loops,
  1070. 'username':post_user.username,
  1071. 'user_id':post_user.id,
  1072. 'reactions':list(reactions_list),
  1073. 'profile_pic':post_user.profile_pic,
  1074. 'date_created':str(post.date_created),
  1075. 'title':post.title,
  1076. 'already_recorded':already_recored,
  1077. 'already_recorded_vid_url': already_recored_vid_url,
  1078. 'already_recorded_vid_thumb_url':already_recored_vid_thumb_url
  1079. }
  1080.  
  1081.  
  1082. return json.dumps({'data':to_append})
  1083.  
  1084. @staticmethod
  1085. def loop(post_id, count):
  1086. the_post = Post.objects.get(pk=post_id)
  1087. the_count = the_post.loops
  1088. the_post.loops = the_count + int(count)
  1089. the_post.save()
  1090. return json.dumps({'status':'success'})
  1091.  
  1092. @staticmethod
  1093. def like(user_id, post_id):
  1094. the_user = User.objects.get(pk=user_id)
  1095. the_post = Post.objects.get(pk=post_id)
  1096. the_user.liked_posts.add(the_post)
  1097. the_count = the_post.likes
  1098. the_post.likes = the_count + 1
  1099. the_post.save()
  1100. return json.dumps({'status':'success'})
  1101.  
  1102. #VIDEO MODEL
  1103. class Video(models.Model):
  1104.  
  1105. video_url = models.CharField(max_length=300)
  1106. thumbnail_url = models.CharField(max_length=300)
  1107. reactions = models.ManyToManyField('self' , symmetrical=False, related_name='reactionVideos')
  1108. user_id = models.CharField(max_length=300)
  1109. score = models.IntegerField(default=0)
  1110. is_reaction_video = models.IntegerField(default=0)
  1111.  
  1112. @staticmethod
  1113. def likeReaction(video_url, user_id):
  1114.  
  1115. the_user = User.objects.get(pk=user_id)
  1116.  
  1117. the_video = Video.objects.filter(video_url=video_url)
  1118. if(len(the_video) != 0):
  1119. true_video = Video.objects.get(pk=the_video[0].id)
  1120. true_video.score = true_video.score + 1
  1121. true_video.save()
  1122.  
  1123. the_user.liked_reactions.add(true_video)
  1124.  
  1125. return json.dumps({'status':'success', 'score': true_video.score})
  1126.  
  1127. else:
  1128. return json.dumps({'status':'fail', 'msg':'No video found.'})
  1129.  
  1130. @staticmethod
  1131. def dislikeReaction(video_url, user_id):
  1132.  
  1133. the_user = User.objects.get(pk=user_id)
  1134.  
  1135. the_video = Video.objects.filter(video_url=video_url)
  1136. if(len(the_video) != 0):
  1137.  
  1138. true_video = Video.objects.get(pk=the_video[0].id)
  1139. true_video.score = true_video.score - 1
  1140. true_video.save()
  1141.  
  1142. the_user.disliked_reactions.add(true_video)
  1143.  
  1144. if(true_video.score < 0):
  1145. true_video.score = 0
  1146. true_video.save()
  1147.  
  1148. return json.dumps({'status':'success', 'score': true_video.score})
  1149. else:
  1150. return json.dumps({'status':'fail', 'msg':'No video found.'})
  1151.  
  1152. #UTILITY MODEL
  1153. class Utility():
  1154.  
  1155. @staticmethod
  1156. def uploadVideo(request):
  1157. #Prepare Contents
  1158. file_key = str(int(round(time.time() * 1000)))+".mp4"
  1159. save_path = "uploads/"+file_key
  1160. content = base64.b64decode( string.replace( request.POST['video'].strip(), " ", "+") )
  1161.  
  1162. #Save File to S3
  1163. api_key = "AKIAIOXJUFMM4NWOYZFQ"
  1164. api_secret = "zfTrCj/6PZHfWkkk17LOowdVzqNMu4TDai5u/Ovm"
  1165. conn = S3Connection(api_key, api_secret)
  1166. bucket = conn.get_bucket('muvie')
  1167. k = Key(bucket)
  1168. k.key = file_key
  1169. k.set_contents_from_string(content)
  1170. k.make_public()
  1171.  
  1172. #Return Link to File
  1173. link = "https://d2ttl824hypyff.cloudfront.net/"+file_key
  1174. response = {'status':'success', 'msg':'video uploaded', 'link':link}
  1175. return json.dumps(response)
  1176.  
  1177. @staticmethod
  1178. def createThumb(link_incoming):
  1179.  
  1180. api_key = "AKIAIOXJUFMM4NWOYZFQ"
  1181. api_secret = "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"
  1182. conn = S3Connection(api_key, api_secret)
  1183. bucket = conn.get_bucket('muvie')
  1184.  
  1185. size = 128, 128
  1186.  
  1187. file_key_base = str(int(round(time.time() * 1000)))
  1188.  
  1189. #Retrieve our source image from a URL
  1190. fp = urllib.urlopen(link_incoming)
  1191.  
  1192. #Load the URL data into an image
  1193. img = cStringIO.StringIO(fp.read())
  1194. im = Image.open(img)
  1195.  
  1196. #Resize the image
  1197. im.thumbnail(size)
  1198.  
  1199. #NOTE, we're saving the image into a cStringIO object to avoid writing to disk
  1200. out_im2 = cStringIO.StringIO()
  1201.  
  1202. #You MUST specify the file type because there is no file name to discern it from
  1203. im.save(out_im2, 'JPEG')
  1204.  
  1205. # im.save(file_key_base + '_thumb.jpg', "JPEG")
  1206.  
  1207. #Connect to bucket and create key
  1208. file_key_2 = file_key_base + '_thumb.jpg'
  1209. k2 = Key(bucket)
  1210. k2.key = file_key_2
  1211. k2.set_contents_from_string(out_im2.getvalue())
  1212. k2.make_public()
  1213.  
  1214. link2 = "https://d2ttl824hypyff.cloudfront.net/"+file_key_2
  1215.  
  1216. return link2
  1217.  
  1218. @staticmethod
  1219. def uploadImage(request):
  1220. #Prepare Contents
  1221.  
  1222. if 'http' in request.POST['image']:
  1223. response = {'status':'success', 'msg':'image uploaded', 'link':request.POST['image'], 'thumb_link':request.POST['image']}
  1224. return json.dumps(response)
  1225.  
  1226. file_key_base = str(int(round(time.time() * 1000)))
  1227.  
  1228. file_key = file_key_base+".jpg"
  1229. save_path = "uploads/"+file_key
  1230. content = base64.b64decode( string.replace( request.POST['image'].strip(), " ", "+") )
  1231.  
  1232. #Save File to S3
  1233. api_key = "AKIAIOXJUFMM4NWOYZFQ"
  1234. api_secret = "zfTrCj/6PZHfWkkk17LOowdVzqNMu4TDai5u/Ovm"
  1235. conn = S3Connection(api_key, api_secret)
  1236. bucket = conn.get_bucket('muvie')
  1237. k = Key(bucket)
  1238. k.key = file_key
  1239. k.set_contents_from_string(content)
  1240. k.make_public()
  1241.  
  1242. size = 128, 128
  1243.  
  1244. #Return Link to File
  1245. link = "https://d2ttl824hypyff.cloudfront.net/"+file_key
  1246.  
  1247. #Retrieve our source image from a URL
  1248. fp = urllib.urlopen(link)
  1249.  
  1250. #Load the URL data into an image
  1251. img = cStringIO.StringIO(fp.read())
  1252. im = Image.open(img)
  1253.  
  1254. #Resize the image
  1255. im.thumbnail(size)
  1256.  
  1257. #NOTE, we're saving the image into a cStringIO object to avoid writing to disk
  1258. out_im2 = cStringIO.StringIO()
  1259.  
  1260. #You MUST specify the file type because there is no file name to discern it from
  1261. im.save(out_im2, 'JPEG')
  1262.  
  1263. # im.save(file_key_base + '_thumb.jpg', "JPEG")
  1264.  
  1265. #Connect to bucket and create key
  1266. file_key_2 = file_key_base + '_thumb.jpg'
  1267. k2 = Key(bucket)
  1268. k2.key = file_key_2
  1269. k2.set_contents_from_string(out_im2.getvalue())
  1270. k2.make_public()
  1271.  
  1272. link2 = "https://d2ttl824hypyff.cloudfront.net/"+file_key_2
  1273.  
  1274. #Note we're setting contents from the in-memory string provided by cStringIO
  1275.  
  1276. response = {'status':'success', 'msg':'image uploaded', 'link':link, 'thumb_link':link2}
  1277. return json.dumps(response)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement