Source

ytmanager / mcyoutube / views.py

Full commit
from django import http
from django.core.urlresolvers import reverse
from django.forms.models import model_to_dict
from django.shortcuts import get_object_or_404, redirect

from annoying.decorators import ajax_request

import gdata.service

from mcyoutube import models


def render_to_response(request, template_name, context_dict, **kwargs):
    from django.template import RequestContext
    from django.shortcuts import render_to_response as _render_to_response
    context = RequestContext(request, context_dict)
    return _render_to_response(template_name, context_instance=context, **kwargs)


def is_auth(func):
    def inner(request):
        try:
            request.session['token']
            request.session['username']
        except KeyError:
            return render_to_response(request, 'ytmanager/login.html', {})

        return func(request)
    return inner


def auth(request):
    try:
        token = request.GET['token']
    except KeyError:
        return redirect('ytmanager-login')

    yt_service = models.get_service()
    yt_service.SetAuthSubToken(token)
    try:
        yt_service.UpgradeToSessionToken()
    except gdata.service.TokenUpgradeFailed:
        return http.HttpResponseRedirect(models.auth_sub_url())

    request.session['token'] = yt_service.current_token.get_token_string()

    models.import_playlists()

    return redirect('ytmanager-wait-playlists')


def reset(request):
    try:
        models.import_playlists()
    except gdata.service.RequestError:
        return http.HttpResponseRedirect(models.auth_sub_url())

    return redirect('ytmanager-wait-playlists')


def import_playlist(request):
    try:
        id = request.GET['id']
    except KeyError:
        return http.HttpResponseBadRequest()

    playlist = models.Playlist.objects.get(id=id)

    yt_service = models.get_service()

    for i in range(0, 20):
        start_index = i * 50 + 1
        feed_link_href = playlist.link + '?start-index=%d&max-results=50' % start_index

        video_feed = yt_service.GetYouTubePlaylistVideoFeed(uri=feed_link_href)
        for video_entry in video_feed.entry:
            try:
                playlist_entry = models.PlaylistEntry.from_video_entry(video_entry, playlist)
            except models.CanNotCreateInstanceError:
                continue
            playlist_entry.save()

        if len(video_feed.entry) < 50:
            break

    playlist.is_ready = True
    playlist.save()

    return http.HttpResponse()


@ajax_request
@is_auth
def check_playlists(request):
    obj_list = list(models.Playlist.user_objects.filter(is_ready=False))
    if obj_list:
        return {'result': False}
    else:
        return {'result': True, 'redirect_to': reverse('ytmanager-playlists')}


@is_auth
def playlists(request):
    playlists = models.Playlist.user_objects.all()

    return render_to_response(request, 'ytmanager/playlist.html',
                              {'playlists': playlists})


@ajax_request
@is_auth
def update_playlist_entry(request):
    try:
        id = request.GET['id']
        title = request.GET['title']
        playlist_id = request.GET['playlist_id']
    except KeyError:
        return http.HttpResponseBadRequest()

    entry = models.PlaylistEntry.objects.get(id=id)
    if not entry.is_mine():
        return http.HttpResponseForbidden()

    if entry.playlist_id != playlist_id:
        playlist = models.Playlist.objects.get(id=playlist_id)

        try:
            entry.move_to_playlist(playlist)
        except gdata.service.RequestError, exc:
            if exc.args[0]['body'] == 'Favorite already exists.':
                entry.delete()
                return {'result': False, 'reason': 'Favorite already exists.'}

    entry.title = title
    entry.save()

    return dict(model_to_dict(entry), result=True)


@ajax_request
@is_auth
def delete_playlist_entry(request):
    try:
        id = request.GET['id']
    except KeyError:
        return http.HttpResponseBadRequest()

    entry = models.PlaylistEntry.objects.get(id=id)
    if not entry.is_mine():
        return http.HttpResponseForbidden()

    entry_dict = model_to_dict(entry)

    entry.remove_from_youtube()
    entry.delete()

    return entry_dict


@ajax_request
@is_auth
def create_playlist(request):
    try:
        title = request.GET['title']
    except KeyError:
        return http.HttpResponseBadRequest()

    playlist = models.Playlist(title=title)

    try:
        playlist.create_playlist_entry()
    except gdata.service.RequestError, exc:
        if exc.args[0]['body'] == 'Playlist already exists.':
            playlist = models.Playlist.user_objects.get(title=title);
            return dict(model_to_dict(playlist), result=False, reason='Playlist already exists.')

    playlist.save()

    return dict(model_to_dict(playlist), result=True)


@ajax_request
@is_auth
def update_playlist(request):
    try:
        id = request.GET['id']
        title = request.GET['title']
    except KeyError:
        return http.HttpResponseBadRequest()

    playlist = get_object_or_404(models.Playlist.user_objects, id=id)
    playlist.rename(title)
    playlist.save()

    return model_to_dict(playlist)


@ajax_request
@is_auth
def delete_playlist(request):
    try:
        playlist_id = request.GET['id']
    except:
        return http.HttpResponseBadRequest()

    playlist = models.Playlist.user_objects.get(id=playlist_id)

    playlist_dict = model_to_dict(playlist)

    playlist.remove_from_youtube()
    playlist.delete()

    return playlist_dict


@ajax_request
@is_auth
def delete_playlist_duplicates(request):
    try:
        id = request.GET['id']
    except KeyError:
        return http.HttpResponseBadRequest()

    entries = models.PlaylistEntry.objects.filter(playlist=id)

    video_ids = {}
    deleted_entries = []
    for entry in entries:
        if entry.video_id in video_ids:
            deleted_entries.append(entry.id)

            entry.remove_from_youtube()
            entry.delete()
        else:
            video_ids[entry.video_id] = None

    return {'deleted_entries': deleted_entries}