summaryrefslogtreecommitdiff
path: root/backend/views.py
diff options
context:
space:
mode:
authorMaksim A. Boyko <maksim.a.boyko@gmail.com>2012-08-28 23:05:34 -0400
committerMaksim A. Boyko <maksim.a.boyko@gmail.com>2012-08-28 23:05:34 -0400
commit3a35a5e273ba2a4b67e3219a7cd4cd57ad1f845a (patch)
tree07593ff4eda7f1cbb17b99b9ba24e0705b7ef79a /backend/views.py
parent8b07b7578f4d75da972ac69705a84a298f0b4f85 (diff)
Backend: Add api_video_search view
Diffstat (limited to 'backend/views.py')
-rw-r--r--backend/views.py112
1 files changed, 98 insertions, 14 deletions
diff --git a/backend/views.py b/backend/views.py
index 2feb8c4..383c487 100644
--- a/backend/views.py
+++ b/backend/views.py
@@ -24,6 +24,7 @@ import cStringIO
from backend.models import SJLike
from backend.models import SJRoom
from backend.models import SJContent
+from backend.models import SJSearch
from backend.models import SJUserProfile
from browser import Browser
@@ -62,14 +63,14 @@ def is_image(url):
return ext.lower() in ['.gif', '.jpg', '.jpeg', '.png']
def is_number(s):
- try:
- int(s)
- return True
- except:
- return False
+ try:
+ int(s)
+ return True
+ except:
+ return False
def title_from_url (url):
- return url.split("/")[-1].replace(".mp3", "").replace("%20"," ").replace("_"," ")
+ return url.split("/")[-1].replace(".mp3", "").replace("%20"," ").replace("_"," ")
def headers(response):
""" Setup additional headers for response
@@ -189,7 +190,8 @@ def store_video_youtube(room, user, ytid):
if ytmatch:
title = ytmatch.group(1)
video = SJContent(room=room, content_type='video', user=user, datetime=datetime.now())
- video.settings = {'url': YT_PREFIX+ytid, 'title': title}
+ url = YT_PREFIX+ytid
+ video.settings = {'url': url, 'title': title, 'thumbnail': 'http://img.youtube.com/vi/' + url[-11:] + '/1.jpg'}
video.save()
return video.id
@@ -204,7 +206,7 @@ def store_video_vimeo(room, user, vimeoid):
title = match.group(1)
title = title[0:-9]
video = SJContent(room=room, content_type='video', user=user, datetime=datetime.now())
- video.settings = {'url': VIMEO_PREFIX+vimeoid, 'title': title}
+ video.settings = {'url': VIMEO_PREFIX+vimeoid, 'title': title, 'thumbnail': ''}
video.save()
return video.id
@@ -227,7 +229,7 @@ def store_video_soundcloud(room, user, url):
if match:
title = match.group(1)
video = SJContent(room=room, content_type='video', user=user, datetime=datetime.now())
- video.settings = {'url': url, 'title': title}
+ video.settings = {'url': url, 'title': title, 'thumbnail': ''}
video.save()
return video.id
@@ -294,7 +296,7 @@ def store_media_str(room, user, msg):
if image is not None and music is not None:
title = title_from_url(music)
audio = SJContent(room=room, content_type='video', user=user, datetime=datetime.now())
- audio.settings = {'url': image+music, 'title': title}
+ audio.settings = {'url': image+music, 'title': title, 'thumbnail': ''}
audio.save()
strio.write(videos_response_str([audio]))
return strio.getvalue()
@@ -929,7 +931,7 @@ def api_video_unlike(request):
@require_POST
def api_video_remove(request):
- """ Remove video. Private API
+ """ Remove video view. Private API
"""
user = request.user
if not user.is_authenticated():
@@ -957,17 +959,99 @@ def api_video_remove(request):
@require_POST
def api_video_search(request):
- """ Private API
+ """ Search video view. Private API
"""
user = request.user
if not user.is_authenticated():
return response_error('NO LOGGED IN')
user_profile = user.get_profile()
- form_fields = ['q', 'start', 'limit']
+ form_fields = ['q']
response = check_form_fields(request, form_fields)
if response:
return response
- return HttpResponse('Not implemented yet!\n')
+ start = 0
+ if 'start' in request.POST and is_number(request.POST['start']):
+ start = int(request.POST['start'])
+ limit = 10
+ if 'limit' in request.POST and is_number(request.POST['limit']):
+ limit = int(request.POST['limit'])
+ if limit > 100:
+ limit = 100
+ videos = SJContent.objects.filter(content_type='video')
+ words = {}
+ videos_by_url = {}
+ videos_by_id = {}
+ for video in videos:
+ settings = video.settings
+ url = settings.get('url', '')
+ likes = SJLike.objects.filter(content=video).count()
+ username = video.user.username
+ if url in videos_by_url:
+ videos_by_url[url]['score'] += likes
+ if username not in videos_by_url[url]['users']:
+ videos_by_url[url]['users'].append(username)
+ continue
+ settings['id'] = video.id
+ settings['users'] = [username]
+ settings['score'] = likes
+ if 'thumbnail' not in settings:
+ settings['thumbnail'] = ''
+ videos_by_url[url] = settings
+ videos_by_id[video.id] = settings
+ terms = re.split(r'\W+', settings['title'])
+ terms.extend(settings['users'])
+ for term in terms:
+ term = term.lower()
+ if len(term) >= 2:
+ if term not in words:
+ words[term] = []
+ words[term].append(settings['id'])
+ terms = re.split(r'\W+', request.POST['q'].lower())
+ match = {}
+ for term in terms:
+ if term in words:
+ for videoid in words[term]:
+ if videoid not in match:
+ match[videoid] = 1
+ else:
+ match[videoid] += 1
+ results = []
+ count = 0
+ for videoid in sorted(sorted(match, key=lambda x: videos_by_id[x]['score'], reverse=True), key=lambda x: match[x], reverse=True):
+ count += 1
+ if count > limit:
+ break
+ if count < start:
+ continue
+ settings = videos_by_id[videoid]
+ results.append(settings)
+ response = response_success(message='')
+ for result in results:
+ response.write('%s\n' % (
+ '\t'.join([str(result['id']),
+ str(result['score']),
+ result['users'][0],
+ str(len(result['users'])),
+ result['title'],
+ result['url'],
+ result['thumbnail']])
+ ))
+ count = len(match)
+ if start == 0:
+ search = SJSearch(user=user, datetime=datetime.now())
+ settings = {
+ 'terms': request.POST['q'],
+ 'count': count,
+ }
+ if count:
+ settings['url']= results[0]['url']
+ settings['title'] = results[0]['title']
+ else:
+ settings['url']= ''
+ settings['title'] = ''
+ search.settings = settings
+ search.save()
+ return response
#
# Common views