Esempio n. 1
0
def ajax_vote(request, entry_id):
    data = {'success': False}

    try:
        entry_id = int(entry_id)
    except ValueError:
        entry_id = 0
    entry = get_object_or_404(Entry, id=entry_id)

    # can't vote for yourself
    if entry.owner == request.user:
        data['reason'] = design.cannot_vote_for_yourself
        return json_response(data)

    # how many thumbs up should they have
    max_votes = max_vote_count(entry.competition.entry_set.count())
    used_votes = ThumbsUp.objects.filter(owner=request.user, entry__competition=entry.competition).count()

    if used_votes < max_votes:
        # OK! spend a vote on this entry
        vote = ThumbsUp()
        vote.owner = request.user
        vote.entry = entry
        vote.save()

        data['success'] = True
    else:
        data['reason'] = design.no_votes_left

    return json_response(data)
Esempio n. 2
0
def ajax_vote(request, entry_id):
    data = {'success': False}

    try:
        entry_id = int(entry_id)
    except ValueError:
        entry_id = 0
    entry = get_object_or_404(Entry, id=entry_id)

    # can't vote for yourself
    if entry.owner == request.user:
        data['reason'] = design.cannot_vote_for_yourself
        return json_response(data)

    # how many thumbs up should they have
    max_votes = max_vote_count(entry.competition.entry_set.count())
    used_votes = ThumbsUp.objects.filter(
        owner=request.user, entry__competition=entry.competition).count()

    if used_votes < max_votes:
        # OK! spend a vote on this entry
        vote = ThumbsUp()
        vote.owner = request.user
        vote.entry = entry
        vote.save()

        data['success'] = True
    else:
        data['reason'] = design.no_votes_left

    return json_response(data)
Esempio n. 3
0
def ajax_bookmark(request, id):
    comp = get_object_or_404(Competition, id=int(id))
    prof = request.user.get_profile()
    prof.competitions_bookmarked.add(comp)
    prof.save()
    data = {'success': True}
    return json_response(data)
Esempio n. 4
0
def ajax_bookmark(request, id):
    comp = get_object_or_404(Competition, id=int(id))
    prof = request.user.get_profile()
    prof.competitions_bookmarked.add(comp)
    prof.save()
    data = {'success': True}
    return json_response(data)
Esempio n. 5
0
def ajax_project(request):
    """
    return the project history. if a last_version is supplied, only
    return newer ones. Also return the current state - who has it
    checked out, etc.
    """
    last_version_id = get_val(request.GET, 'last_version', 0)
    project = get_obj_from_request(request.GET, 'project', Project)

    if project is None:
        return json_failure(design.bad_project_id)

    # make sure the user has permission
    data = {
        'user': {
            'is_authenticated': request.user.is_authenticated(),
            'has_permission':
            project.band.permission_to_critique(request.user),
        },
        'success': False,
    }

    if not data['user']['has_permission']:
        data['reason'] = design.you_dont_have_permission_to_critique_this_band
        return json_response(data)

    data['project'] = project.to_dict(SerializableModel.OWNER,
                                      chains=['checked_out_to'])
    data['project']['band'] = project.band.to_dict(SerializableModel.OWNER)

    if last_version_id == 0:
        # get entire version list
        data['versions'] = [
            version_to_dict(x, request.user)
            for x in ProjectVersion.objects.filter(project=project)
        ]
    else:
        data['versions'] = [
            version_to_dict(x, request.user)
            for x in ProjectVersion.objects.filter(project=project,
                                                   id__gt=last_version_id)
        ]

    data['user'].update(request.user.get_profile().to_dict())

    data['success'] = True
    return json_response(data)
Esempio n. 6
0
def ajax_logout(request):
    logout(request)

    data = {
        'success': True,
    }

    return json_response(data)
Esempio n. 7
0
def ajax_logout(request):
    logout(request)

    data = {
        'success': True,
    }

    return json_response(data)
Esempio n. 8
0
def ajax_project(request):
    """
    return the project history. if a last_version is supplied, only
    return newer ones. Also return the current state - who has it
    checked out, etc.
    """
    last_version_id = get_val(request.GET, 'last_version', 0)
    project = get_obj_from_request(request.GET, 'project', Project)

    if project is None:
        return json_failure(design.bad_project_id)

    # make sure the user has permission
    data = {
        'user': {
            'is_authenticated': request.user.is_authenticated(),
            'has_permission': project.band.permission_to_critique(request.user),
        },
        'success': False,
    }

    if not data['user']['has_permission']:
        data['reason'] = design.you_dont_have_permission_to_critique_this_band
        return json_response(data)

    data['project'] = project.to_dict(SerializableModel.OWNER, chains=['checked_out_to'])
    data['project']['band'] = project.band.to_dict(SerializableModel.OWNER)

    if last_version_id == 0:
        # get entire version list
        data['versions'] = [version_to_dict(x, request.user) for x in ProjectVersion.objects.filter(project=project)]
    else:
        data['versions'] = [version_to_dict(x, request.user) for x in ProjectVersion.objects.filter(project=project, id__gt=last_version_id)]

    data['user'].update(request.user.get_profile().to_dict())

    data['success'] = True
    return json_response(data)
Esempio n. 9
0
def ajax_login_state(request):
    user = request.user

    # build the object
    data = {
        'user': {
            'is_authenticated': user.is_authenticated(),
        },
    }

    if user.is_authenticated():
        data['user'].update(user.get_profile().to_dict())

    return json_response(data)
Esempio n. 10
0
def ajax_login_state(request):
    user = request.user

    # build the object
    data = {
        'user': {
            'is_authenticated': user.is_authenticated(),
        },
    }

    if user.is_authenticated():
        data['user'].update(user.get_profile().to_dict())

    return json_response(data)
Esempio n. 11
0
def ajax_unvote(request, entry_id):
    data = {'success': False}

    try:
        entry_id = int(entry_id)
    except ValueError:
        entry_id = 0
    entry = get_object_or_404(Entry, id=entry_id)

    votes = ThumbsUp.objects.filter(owner=request.user, entry=entry)
    if votes.count() > 0:
        votes[0].delete()

    data['success'] = True
    return json_response(data)
Esempio n. 12
0
def ajax_unvote(request, entry_id):
    data = {'success': False}

    try:
        entry_id = int(entry_id)
    except ValueError:
        entry_id = 0
    entry = get_object_or_404(Entry, id=entry_id)

    votes = ThumbsUp.objects.filter(owner=request.user, entry=entry)
    if votes.count() > 0:
        votes[0].delete()

    data['success'] = True
    return json_response(data)
Esempio n. 13
0
def compoRequest(request, compos):
    page_number = get_val(request.GET, 'page', 1)
    paginator = Paginator(compos, settings.ITEMS_PER_PAGE)

    # build the json object
    data = {
        'compos': [compo_to_dict(x, request.user) for x in paginator.page(page_number).object_list],
        'page_count': paginator.num_pages,
        'page_number': page_number,
        'user': {
            'is_authenticated': request.user.is_authenticated(),
        },
    }

    return json_response(data)
Esempio n. 14
0
def ajax_compo(request, compo_id):
    compo_id = int(compo_id)
    try:
        compo = get_object_or_404(Competition, pk=compo_id)
    except Competition.DoesNotExist:
        return json_failure(design.competition_not_found)

    data = {
        'user': {
            'is_authenticated': request.user.is_authenticated(),
        },
        'compo': compo_to_dict(compo, request.user),
        'party': {
            'buffer_time': settings.LISTENING_PARTY_BUFFER_TIME,
        }
    }

    if request.user.is_authenticated():
        max_votes = max_vote_count(compo.entry_set.count())
        used_votes = ThumbsUp.objects.filter(owner=request.user,
                                             entry__competition=compo)

        data['user'].update(request.user.get_profile().to_dict())
        data['votes'] = {
            'max': max_votes,
            'used': [x.to_dict() for x in used_votes],
            'left': max_votes - used_votes.count(),
        }
        user_entries = Entry.objects.filter(competition=compo,
                                            owner=request.user)
        data['submitted'] = (user_entries.count() > 0)

    def entry_to_dict(entry):
        data = entry.to_dict(chains=['owner.solo_band'])
        data['song'] = song_to_dict(entry.song, request.user)
        if request.user.is_authenticated() and entry.owner == request.user:
            version = ProjectVersion.objects.get(song=entry.song)
            data['project_id'] = version.project.pk
            data['version_number'] = version.version
        return data

    # entries. if competition is closed, sort by vote count.
    data['entries'] = [entry_to_dict(x) for x in compo.entry_set.all()]

    return json_response(data)
Esempio n. 15
0
def ajax_compo(request, compo_id):
    compo_id = int(compo_id)
    try:
        compo = get_object_or_404(Competition, pk=compo_id)
    except Competition.DoesNotExist:
        return json_failure(design.competition_not_found)

    data = {
        'user': {
            'is_authenticated': request.user.is_authenticated(),
        },
        'compo': compo_to_dict(compo, request.user),
        'party': {
            'buffer_time': settings.LISTENING_PARTY_BUFFER_TIME,
        }
    }

    if request.user.is_authenticated():
        max_votes = max_vote_count(compo.entry_set.count())
        used_votes = ThumbsUp.objects.filter(owner=request.user, entry__competition=compo)

        data['user'].update(request.user.get_profile().to_dict());
        data['votes'] = {
            'max': max_votes,
            'used': [x.to_dict() for x in used_votes],
            'left': max_votes - used_votes.count(),
        }
        user_entries = Entry.objects.filter(competition=compo, owner=request.user)
        data['submitted'] = (user_entries.count() > 0)

    def entry_to_dict(entry):
        data = entry.to_dict(chains=['owner.solo_band'])
        data['song'] = song_to_dict(entry.song, request.user)
        if request.user.is_authenticated() and entry.owner == request.user:
            version = ProjectVersion.objects.get(song=entry.song)
            data['project_id'] = version.project.pk
            data['version_number'] = version.version
        return data

    # entries. if competition is closed, sort by vote count.
    data['entries'] = [entry_to_dict(x) for x in compo.entry_set.all()]

    return json_response(data)
Esempio n. 16
0
def ajax_say(request):
    room = get_obj_from_request(request.POST, 'room', ChatRoom)
    if room is None:
        return json_failure(design.bad_room_id)

    data = {
        'user': {
            'is_authenticated': request.user.is_authenticated(),
            'permission_read': room.permission_to_hear(request.user),
            'permission_write': room.permission_to_chat(request.user),
        },
        'success': False,
    }

    if not room.is_active():
        return json_failure(design.room_is_not_active)

    message = request.POST.get('message', '')

    if message == "":
        return json_failure(design.cannot_say_blank_message)

    if len(message) > ChatMessage._meta.get_field('message').max_length: #@UndefinedVariable
        return json_failure(design.message_too_long)

    if not data['user']['permission_write']:
        return json_failure(design.you_lack_write_permission)

    msgType = get_val(request.POST, 'type', ChatMessage.MESSAGE)
    if msgType not in [ChatMessage.MESSAGE, ChatMessage.ACTION]:
        msgType = ChatMessage.MESSAGE

    # we're clear. add the message
    m = ChatMessage()
    m.room = room
    m.type = msgType
    m.author = request.user
    m.message = message
    m.save()

    data['success'] = True
    return json_response(data)
Esempio n. 17
0
def compoRequest(request, compos):
    page_number = get_val(request.GET, 'page', 1)
    paginator = Paginator(compos, settings.ITEMS_PER_PAGE)

    # build the json object
    data = {
        'compos': [
            compo_to_dict(x, request.user)
            for x in paginator.page(page_number).object_list
        ],
        'page_count':
        paginator.num_pages,
        'page_number':
        page_number,
        'user': {
            'is_authenticated': request.user.is_authenticated(),
        },
    }

    return json_response(data)
Esempio n. 18
0
def ajax_login(request):
    err_msg = ''
    success = False
    if request.method == 'POST':
        user = authenticate(username=request.POST.get('username', ''), password=request.POST.get('password', ''))
        if user is not None:
            if user.is_active and user.get_profile().activated:
                login(request, user)
                success = True
            else:
                err_msg = design.your_account_not_activated
        else:
            err_msg = design.invalid_login
    else:
        err_msg = design.no_login_data_supplied

    data = {
        'success': success,
        'err_msg': err_msg,
    }

    return json_response(data)
Esempio n. 19
0
def ajax_home(request):
    data = {
        'user': {
            'is_authenticated': request.user.is_authenticated(),
        },
        'success': True,
    }

    if data['user']['is_authenticated']:
        data['user'].update(request.user.get_profile().to_dict())

        # bands the user is a part of
        members = BandMember.objects.filter(user=request.user)
        data['members'] = [x.to_dict(chains=['band']) for x in members]

        # invitations
        invites = BandInvitation.objects.filter(invitee=request.user)
        data['invites'] = [x.to_dict(chains=['band']) for x in invites]

        # log entries
        data['activity'] = activity_list(request)

    return json_response(data)
Esempio n. 20
0
def ajax_login(request):
    err_msg = ''
    success = False
    if request.method == 'POST':
        user = authenticate(username=request.POST.get('username', ''),
                            password=request.POST.get('password', ''))
        if user is not None:
            if user.is_active and user.get_profile().activated:
                login(request, user)
                success = True
            else:
                err_msg = design.your_account_not_activated
        else:
            err_msg = design.invalid_login
    else:
        err_msg = design.no_login_data_supplied

    data = {
        'success': success,
        'err_msg': err_msg,
    }

    return json_response(data)
Esempio n. 21
0
def ajax_home(request):
    data = {
        'user': {
            'is_authenticated': request.user.is_authenticated(),
        },
        'success': True,
    }


    if data['user']['is_authenticated']:
        data['user'].update(request.user.get_profile().to_dict())

        # bands the user is a part of
        members = BandMember.objects.filter(user=request.user)
        data['members'] = [x.to_dict(chains=['band']) for x in members]

        # invitations
        invites = BandInvitation.objects.filter(invitee=request.user)
        data['invites'] = [x.to_dict(chains=['band']) for x in invites]

        # log entries
        data['activity'] = activity_list(request)

    return json_response(data)
Esempio n. 22
0
def ajax_submit_entry(request):
    compo = get_obj_from_request(request.POST, 'compo', Competition)
    if compo is None:
        return json_failure(design.competition_not_found)

    # make sure it's still submission time
    now = datetime.now()
    if now >= compo.submit_deadline:
        return json_failure(design.past_submission_deadline)

    if now <= compo.start_date:
        return json_failure(design.competition_not_started)

    title = request.POST.get('entry-title','')
    comments = request.POST.get('entry-comments', '')
    mp3_file = request.FILES.get('entry-file-mp3')
    source_file = request.FILES.get('entry-file-source')
    is_open_source = request.POST.get('entry-open-source', False)

    entries = Entry.objects.filter(owner=request.user, competition=compo)
    resubmitting = entries.count() > 0

    # make sure files are small enough
    if not resubmitting and mp3_file is None:
        return json_failure(design.mp3_required)

    if mp3_file is not None and mp3_file.size > settings.FILE_UPLOAD_SIZE_CAP:
        return json_failure(design.mp3_too_big)

    if source_file is not None:
        if source_file.size > settings.FILE_UPLOAD_SIZE_CAP:
            return json_failure(design.source_file_too_big)

    if title == '':
        return json_failure(design.entry_title_required)

    if mp3_file is not None:
        band = request.user.get_profile().solo_band

        if resubmitting:
            entry = entries[0]
            project = Project.objects.get(latest_version__song=entry.song)
            new_version_number = project.latest_version.version + 1
            filename_appendix = "_" + str(new_version_number)
        else:
            filename_appendix = ""

        result = upload_song(request.user,
            file_mp3_handle=mp3_file,
            file_source_handle=source_file, 
            max_song_len=settings.COMPO_ENTRY_MAX_LEN,
            band=band,
            song_title=title,
            song_album=compo.title,
            song_comments=comments,
            filename_appendix=filename_appendix)

        if not result['success']:
            return json_failure(result['reason'])

        song = result['song']
        song.is_open_source = is_open_source
        song.is_open_for_comments = True
        song.save()

        # make a new version and attach that to the entry
        if resubmitting:

            # create new version
            version = ProjectVersion()
            version.project = project
            version.song = song
            version.version = new_version_number
            version.saveNewVersion()

            old_length = entry.song.length
            buffer_time = 0
        else:
            # create the project
            project = Project()
            project.band = band
            project.save()

            # create the first version
            version = ProjectVersion()
            version.project = project
            version.song = song
            version.version = 1
            version.saveNewVersion()

            # subscribe the creator
            project.subscribers.add(request.user)
            project.save()

            # create new entry
            entry = Entry()
            entry.competition = compo
            entry.owner = request.user

            old_length = 0
            buffer_time = settings.LISTENING_PARTY_BUFFER_TIME

        entry.song = song
        entry.save()

        # update competition dates based on this newfound length 
        vote_period_delta = timedelta(seconds=compo.vote_period_length)
        if compo.have_listening_party:
            compo.listening_party_end_date += timedelta(seconds=(song.length-old_length+buffer_time))
            compo.vote_deadline = compo.listening_party_end_date + vote_period_delta
        else:
            compo.vote_deadline = compo.submit_deadline + vote_period_delta
        compo.save()

        chatroom = compo.chat_room
        chatroom.end_date = compo.listening_party_end_date + timedelta(hours=1)
        chatroom.save()
    else:
        # only providing source and possibly renaming.
        entry = entries[0]
        song = entry.song

        if source_file is not None:
            handle_project_upload(source_file, request.user, song)

        song.title = title
        song.is_open_source = is_open_source
        song.comments = comments
        song.save()

    return json_response({'success': True})
Esempio n. 23
0
def ajax_hear(request):
    """
    get new or all messages
    """
    last_message_str = request.GET.get('last_message', 'null')

    room = get_obj_from_request(request.GET, 'room', ChatRoom)
    if room is None:
        return json_failure(design.bad_room_id)

    # make sure user has permission to be in this room
    data = {
        'user': {
            'is_authenticated': request.user.is_authenticated(),
            'permission_read': room.permission_to_hear(request.user),
            'permission_write': room.permission_to_chat(request.user),
        },
        'room': room.to_dict(),
        'messages': [],
        'success': True
    }

    if request.user.is_authenticated():
        data['user'].update({
            'username': request.user.username,
        })

    if data['user']['permission_read']:
        def add_to_message(msg):
            return {
                'id': msg.id,
                'type': msg.type,
                'author': {
                    'username': msg.author.username,
                    'id': msg.author.id,
                },
                'message': msg.message,
                'timestamp': msg.timestamp,
            }

        if last_message_str == 'null':
            # get entire log for this chat.
            data['messages'] = [add_to_message(x) for x in ChatMessage.objects.filter(room=room)]
        else:
            try:
                last_message_id = int(last_message_str)
            except ValueError:
                last_message_id = 0

            data['messages'] = [add_to_message(x) for x in ChatMessage.objects.filter(room=room, id__gt=last_message_id)]

    if data['user']['permission_write']:
        # mark an appearance in the ChatRoom
        if request.user.is_authenticated() and room.is_active():
            appearances = Appearance.objects.filter(person=request.user, room=room)
            if appearances.count() > 0:
                appearances[0].save() # update the timestamp
            else:
                new_appearance = Appearance()
                new_appearance.room = room
                new_appearance.person = request.user
                new_appearance.save()

                # join message
                m = ChatMessage()
                m.room=room
                m.type=ChatMessage.JOIN
                m.author=request.user
                m.save()

    return json_response(data)
Esempio n. 24
0
def ajax_submit_entry(request):
    compo = get_obj_from_request(request.POST, 'compo', Competition)
    if compo is None:
        return json_failure(design.competition_not_found)

    # make sure it's still submission time
    now = datetime.now()
    if now >= compo.submit_deadline:
        return json_failure(design.past_submission_deadline)

    if now <= compo.start_date:
        return json_failure(design.competition_not_started)

    title = request.POST.get('entry-title', '')
    comments = request.POST.get('entry-comments', '')
    mp3_file = request.FILES.get('entry-file-mp3')
    source_file = request.FILES.get('entry-file-source')
    is_open_source = request.POST.get('entry-open-source', False)

    entries = Entry.objects.filter(owner=request.user, competition=compo)
    resubmitting = entries.count() > 0

    # make sure files are small enough
    if not resubmitting and mp3_file is None:
        return json_failure(design.mp3_required)

    if mp3_file is not None and mp3_file.size > settings.FILE_UPLOAD_SIZE_CAP:
        return json_failure(design.mp3_too_big)

    if source_file is not None:
        if source_file.size > settings.FILE_UPLOAD_SIZE_CAP:
            return json_failure(design.source_file_too_big)

    if title == '':
        return json_failure(design.entry_title_required)

    if mp3_file is not None:
        band = request.user.get_profile().solo_band

        if resubmitting:
            entry = entries[0]
            project = Project.objects.get(latest_version__song=entry.song)
            new_version_number = project.latest_version.version + 1
            filename_appendix = "_" + str(new_version_number)
        else:
            filename_appendix = ""

        result = upload_song(request.user,
                             file_mp3_handle=mp3_file,
                             file_source_handle=source_file,
                             max_song_len=settings.COMPO_ENTRY_MAX_LEN,
                             band=band,
                             song_title=title,
                             song_album=compo.title,
                             song_comments=comments,
                             filename_appendix=filename_appendix)

        if not result['success']:
            return json_failure(result['reason'])

        song = result['song']
        song.is_open_source = is_open_source
        song.is_open_for_comments = True
        song.save()

        # make a new version and attach that to the entry
        if resubmitting:

            # create new version
            version = ProjectVersion()
            version.project = project
            version.song = song
            version.version = new_version_number
            version.saveNewVersion()

            old_length = entry.song.length
            buffer_time = 0
        else:
            # create the project
            project = Project()
            project.band = band
            project.save()

            # create the first version
            version = ProjectVersion()
            version.project = project
            version.song = song
            version.version = 1
            version.saveNewVersion()

            # subscribe the creator
            project.subscribers.add(request.user)
            project.save()

            # create new entry
            entry = Entry()
            entry.competition = compo
            entry.owner = request.user

            old_length = 0
            buffer_time = settings.LISTENING_PARTY_BUFFER_TIME

        entry.song = song
        entry.save()

        # update competition dates based on this newfound length
        vote_period_delta = timedelta(seconds=compo.vote_period_length)
        if compo.have_listening_party:
            compo.listening_party_end_date += timedelta(
                seconds=(song.length - old_length + buffer_time))
            compo.vote_deadline = compo.listening_party_end_date + vote_period_delta
        else:
            compo.vote_deadline = compo.submit_deadline + vote_period_delta
        compo.save()

        chatroom = compo.chat_room
        chatroom.end_date = compo.listening_party_end_date + timedelta(hours=1)
        chatroom.save()
    else:
        # only providing source and possibly renaming.
        entry = entries[0]
        song = entry.song

        if source_file is not None:
            handle_project_upload(source_file, request.user, song)

        song.title = title
        song.is_open_source = is_open_source
        song.comments = comments
        song.save()

    return json_response({'success': True})