Пример #1
0
def playlist(request):
    if request.method == 'GET':
        queryset = Playlist.objects.filter(user=request.user).order_by('-created_at')
        playlist_serializer = PlaylistSerializer(queryset, context={'request': request}, many=True)
        return Response(playlist_serializer.data, status=status.HTTP_200_OK)
    data = request.data
    user = request.user
    playlist_to_save = Playlist()
    playlist_to_save.title = data.get('title')
    playlist_to_save.message = data.get('message')
    playlist_to_save.locked = True if data.get('locked') == 'true' else False
    playlist_to_save.public = True if data.get('public') == 'true' else False
    playlist_to_save.latitude = data.get('latitude')
    playlist_to_save.longitude = data.get('longitude')
    playlist_to_save.user = user
    playlist_to_save.playlist_image = request.FILES.get('image')
    playlist_to_save.playlist_video = request.FILES.get('video')
    playlist_to_save.save()

    songs = data.get('songs', [])
    if type(songs) == type(""):
        songs = json.loads(songs)

    # Save songs
    for song_json in songs:
        images = song_json['album']['images']
        song, _ = Song.objects.get_or_create(
            title=song_json['name'],
            spotify_id=song_json['id'],
            spotify_uri=song_json['uri'],
            track_preview_url=song_json['preview_url'],
            album_artwork=images[0].get('url') if images else '',
            album_title=song_json['album']['name']
        )
        song.save()
        playlist_to_save.songs.add(song)

        for artist_json in song_json['artists']:
            artist, _ = Artist.objects.get_or_create(
                name=artist_json['name'],
                spotify_id=artist_json['id']
            )
            song.artists.add(artist)
    
    profiles = data.get('profiles', [])
    if type(profiles) == type(""):
        profiles = json.loads(profiles)
    
    for profile in profiles:
        share_with_user = get_object_or_404(user_model, username=profile['user']['username'])
        # user_id = profile_json['user']['id']
        playlist_to_save.shared_with_users.add(share_with_user)
    
    # notify_feed_of_playlist(user.userprofile, playlist_to_save)

    return Response(PlaylistSerializer(playlist_to_save,
                                       context={'request': request}).data,
                    status=status.HTTP_201_CREATED)
Пример #2
0
def create_playlist():
    playlist_json = request.json
    playlist = Playlist(request.json['name'])
    playlist.user_id = session['user_id']
    playlist.save()
    
    g.user.add_playlist(playlist)

    return ""
Пример #3
0
Файл: ajax.py Проект: alx/acabed
def add(request, animation):
    dajax = Dajax()
    dajax.remove_css_class('#movie-inspector label', 'error')

    animation = json.loads(animation)
    animation.update({
        'type': 'm',
        'user': request.user is None and '' or request.user.id,
    })

    if int(animation['max_duration']) > 60:
        animation['max_duration'] = 60

    movie_duration = 0
    for frame in animation['data']:
        frame['duration'] = int(frame['duration'])
        if frame['duration'] > 2000:
            frame['duration'] = 2000
        movie_duration += frame['duration']

    if movie_duration > 60000:
        dajax.script('MessageWidget.msg("Animation darf insgesamt nicht laenger als 60 Sekunden sein! Bitte Frames loeschen oder kuerzer anzeigen lassen!")')
        return dajax.json()
    
    form = AnimationForm(animation)

    if form.is_valid():
        a = form.save()

        p = Playlist(
            title = 'stub \'%s\' playlist' % form.cleaned_data['title'],
            user = User.objects.all()[0]
        )
        p.save()
        
        ai = AnimationInstance(
            playlist = p,
            animation = a
        )
        ai.save()

        # queue playlist
        sj = SpoolJob(
            playlist = p,
            priority = 2,
            added = datetime.now()
        )
        sj.save()

        dajax.script('MessageWidget.msg("Great success! Animootion mit ID %s gespeichert!")' % p.id)
    else:
        for error in form.errors:
            dajax.add_css_class('#movie-inspector label[for="%s"]' % error, 'error')
        dajax.script('MessageWidget.msg("Bitte fehlende Felder ausfuellen.")')

    return dajax.json()
Пример #4
0
def playlist(user_id):
    if request.method == 'GET':
        playlists = Playlist.objects().filter(user_id=user_id)
        return playlists.to_json()
    if request.method == 'POST':
        playlist = Playlist()
        playlist.user_id = user_id
        playlist.name = 'New Playlist'
        playlist.song_ids = []
        playlist.save()
        return playlist.to_json()
Пример #5
0
def add(request, animation):
    dajax = Dajax()
    dajax.remove_css_class('#movie-inspector label', 'error')

    animation = json.loads(animation)
    animation.update({
        'type': 'm',
        'user': request.user is None and '' or request.user.id,
    })

    if int(animation['max_duration']) > 60:
        animation['max_duration'] = 60

    movie_duration = 0
    for frame in animation['data']:
        frame['duration'] = int(frame['duration'])
        if frame['duration'] > 2000:
            frame['duration'] = 2000
        movie_duration += frame['duration']

    if movie_duration > 60000:
        dajax.script(
            'MessageWidget.msg("Animation darf insgesamt nicht laenger als 60 Sekunden sein! Bitte Frames loeschen oder kuerzer anzeigen lassen!")'
        )
        return dajax.json()

    form = AnimationForm(animation)

    if form.is_valid():
        a = form.save()

        p = Playlist(title='stub \'%s\' playlist' % form.cleaned_data['title'],
                     user=User.objects.all()[0])
        p.save()

        ai = AnimationInstance(playlist=p, animation=a)
        ai.save()

        # queue playlist
        sj = SpoolJob(playlist=p, priority=2, added=datetime.now())
        sj.save()

        dajax.script(
            'MessageWidget.msg("Great success! Animootion mit ID %s gespeichert!")'
            % p.id)
    else:
        for error in form.errors:
            dajax.add_css_class('#movie-inspector label[for="%s"]' % error,
                                'error')
        dajax.script('MessageWidget.msg("Bitte fehlende Felder ausfuellen.")')

    return dajax.json()
Пример #6
0
def generate_playlist(request):
    print(request.POST.keys())
    artists = request.POST.get("artists").replace('/', '\n').split('\n')
    if artists:
        client = soundcloud.Client(access_token=request.COOKIES['access_token'])
        print(artists)
        all_tracks = []
        for artist in artists:
            artist = artist.strip()
            print artist
            tracks = client.get('/tracks', q=artist, limit=20)
            short_tracks = []
            count = 0
            for track in tracks:
                max_tracks = int(request.POST.get("max_tracks"))
                if count > max_tracks:
                    break
                max_length = int(request.POST.get("max_length"))
                if max_length == 0 or track.duration < (max_length * 60 * 1000):
                    #Skip ones longer than max_length mins
                    count += 1
                    short_tracks.append(track)
            all_tracks.extend(track.id for track in short_tracks)
            print len(all_tracks)

        if request.POST.get("randomize"):
            print("Randomize = true")
            random.shuffle(all_tracks)

        # create an array of track ids
        all_tracks_ids = map(lambda id: dict(id=id), all_tracks)

        # create the playlist
        # FIXME: timeout more than ~400 sounds in total
        print("Creating Playlist...")
        ret = client.post('/playlists', playlist={
            'title': request.POST.get("title"),
            'sharing': "public", #TODO: cutomize this viw a tickbox
            'tracks': all_tracks_ids
        })
        try:
            user = client.get('/me')
            plst = Playlist(name=ret.title, author=user.username, author_id=user.uri, url=ret.permalink_url)
            plst.save()
        except Exception as exc:
            print("++ ERROR while trying to save the playlist: %s" % exc)
        print("Created %s available at: %s!" % (ret.title, ret.permalink_url))
        return HttpResponse(simplejson.dumps({"link": ret.permalink_url, "title": ret.title}), content_type="application/json")
    else:
        print("no artists found!")
        return HttpResponseServerError()
Пример #7
0
def get_playlist(user, name):
    """
    Checks to see if the user has a playlist named name
    If not, create the playlist
    :param user: User object
    :param name: String of name of playlist
    :return: Playlist owned by user, named name
    """
    search = Playlist.objects.filter(name=name, owner=user)
    if search.exists():
        return search[0]
    else:
        playlist = Playlist(owner=user, name=name)
        playlist.save()
        return playlist
Пример #8
0
def createPlaylist(request, track_id, playlist_name, owner_id):
	created_by = User.objects.get(id=owner_id)
	new_list = Playlist(
		name = playlist_name,
		owner = created_by,
		pub_date = timezone.now(),
	)
	new_list.save()
	track = Track.objects.get(id=track_id)
	new_list.tracks.add(track)
	context = {
		'track' : track,
		'playlist' : new_list,
		'msg' : "has been added into the new playlist! "
	}
	return HttpResponseRedirect('/playlist/')
Пример #9
0
def add_playlist(request):
    postdata = request.POST.copy()
    track_slug = postdata.get('track_slug', '')
    p = get_object_or_404(Track, link=track_slug)
    playlist_list = get_playlist(request)
    track_in_playlist = False

    for list in playlist_list:
        if list.track.id == p.id:

            track_in_playlist = True
        if not track_in_playlist:
            ci = Playlist()
            ci.track = p
            ci.playlist_id = _playlist_id(request)
            ci.save()
Пример #10
0
def add_playlist(request):
    postdata = request.POST.copy()
    track_slug = postdata.get('track_slug', '')
    p = get_object_or_404(Track, link = track_slug)
    playlist_list = get_playlist(request)
    track_in_playlist = False

    for list in playlist_list:
        if list.track.id == p.id :

            track_in_playlist = True
        if not track_in_playlist:
            ci = Playlist()
            ci.track = p
            ci.playlist_id = _playlist_id(request)
            ci.save()
Пример #11
0
def fork(request, username, slug):
    """ creates new for of playlist, with parent set as current playlist 
    
        Does not copy editors, followers or votes
    
    """
    parent_owner = shortcuts.get_object_or_404(User, username=username)
    parent_playlist = shortcuts.get_object_or_404(Playlist, slug=slug, user=parent_owner)

    # create new fork
    new_playlist = Playlist(use=request.user, 
                            title = parent_playlist.title,
                            slug = parent_playlist.slug,
                            parent_fork=parent_playlist)
    new_playlist.save()    
    
    Playlist.objects.save_bookmarks(new_playlist, parent_playlist.bookmarks.values_list('id'))
                 
    messages.info(request, 'Playlist forked - You are now viewing your fork')
    
    return http.HttpResponseRedirect(reverse('bookmarks.playlist_views.view', args=[new_playlist.user.username,new_playlist.slug,]))
Пример #12
0
def create(request):
	if request.method == 'POST':
		url = request.POST.get('playlist_location', '')
		#
		#regexp here!!!!!!!!!
		#
		result = urlfetch.fetch(url + "code/xspf.php")

		if result.status_code == 200:
#			xml = minidom.parseString(unicode(result.content, "utf-8" ))
			try:
				xml = minidom.parseString(result.content.replace("&", "&amp;"))
			except:
				return render_to_response('create.html', {'flash' : "Ops. Something went wrong!!!..."})
			
			tracks = xml.getElementsByTagName('track')
			playlist = Playlist(title="lorem ipsum dolor", location=url)
			playlist.save()

			for song in tracks:
				loc = song.getElementsByTagName('location')[0]
				me = song.getElementsByTagName('meta')[0]
				ti = song.getElementsByTagName('title')[0]
				fo = song.getElementsByTagName('info')[0]

				s = SongForm({
					'location': getText(loc.childNodes),
					'meta': getText(me.childNodes),
					'title': getText(ti.childNodes),
					'info': getText(fo.childNodes),
				})
				if s.is_valid():
					s.playlist = playlist
					s.save()

			return render_to_response('create.html', {'flash' : "Playlist added! <a href=\"/\">Go back to home page.</a>"})

	return render_to_response('create.html')
Пример #13
0
def update_playlist(data):
    url = 'http://wrfl.fm/playlist/'
    r = urllib.urlopen(url).read()
    soup = BeautifulSoup(r, "html5lib")
    t = soup.find('tbody')
    data = ([[c.contents[0].contents for c in row.findAll('td')] for row in t.findAll('tr')])
    for track in data[0:30]:
        try:
            playlist = Playlist.objects.get(playtime = cleanDateTime(track[0]))
        except:
            dj, created = DJ.objects.get_or_create(name=(track[4][0]).encode('utf-8'))
            dj_id = dj.id
            playlist = Playlist(
                                dj          = DJ(id=dj_id),
                                artist      = track[1][0],
                                album       = track[3][0],
                                song        = track[2][0],
                                playtime    = cleanDateTime(track[0]),
                                url         = getTinysongURL(track[1][0], track[2][0]),
                                )
            playlist.save()
    playlist_list = Playlist.objects.all()
    return render_to_response('update_playlist.html', {'playlist_list': playlist_list })
Пример #14
0
def add(request, animation):
    dajax = Dajax()
    dajax.remove_css_class('#movie-inspector label', 'error')

    animation = json.loads(animation)
    animation.update({
        'type': 'm',
        'user': request.user is None and '' or request.user.id,
    })

    if int(animation['max_duration']) > 60:
        animation['max_duration'] = 60

    movie_duration = 0
    for frame in animation['data']:
        frame['duration'] = int(frame['duration'])
        if frame['duration'] > 2000:
            frame['duration'] = 2000
        movie_duration += frame['duration']

    if movie_duration > 60000:
        dajax.script('MessageWidget.msg("The maximal duration of 60 seconds has been reached! Either delete frames or shoten the movie duration!")')
        return dajax.json()
    

    initial = {'title': datetime.now().strftime("%Y-%m-%d %H:%M"),
                                               'description':"created at terminal",
                                               'author': "random hacker",
                                               'email': "*****@*****.**"}

    form = AnimationForm(animation, initial = initial )
    if request.user.is_authenticated():
        for key in initial:
            if not form.data[key]:
                form.data[key]=initial[key]
            
    if form.is_valid():
        a = form.save()

        p = Playlist(
            title = 'stub \'%s\' playlist' % form.cleaned_data['title'],
            user = User.objects.all()[0]
        )
        p.save()
        
        ai = AnimationInstance(
            playlist = p,
            animation = a
        )
        ai.save()

        # queue playlist
        sj = SpoolJob(
            playlist = p,
            priority = 2,
            added = datetime.now()
        )
        sj.save()

        dajax.script('MessageWidget.msg("Great success! Animootion ID %s saved!")' % p.id)
    else:
        for error in form.errors:
            dajax.add_css_class('#movie-inspector label[for="%s"]' % error, 'error')
        dajax.script('MessageWidget.msg("Please fill out marked fields.")')

    return dajax.json()
Пример #15
0
tag = Tag(songId=awakening_song, songTag='Rock')
tag.save()
tag = Tag(songId=awakening_song, songTag='Dynamic')
tag.save()

rap_tag = Tag(songId=waves, songTag='Dynamic')
rap_tag.save()

sad_tag = Tag(songId=waves, songTag='Sad')
sad_tag.save()

# Comments
users_avatars = [
    'https://react.semantic-ui.com/images/avatar/small/matt.jpg',
    'https://react.semantic-ui.com/images/avatar/small/elliot.jpg',
    'https://react.semantic-ui.com/images/avatar/small/jenny.jpg',
    'https://react.semantic-ui.com/images/avatar/small/joe.jpg'
]


for song in songs:
    for i in range(0, random.randint(2, 5)):
        random_comment = Comment(songId=song, commentContent=lorem.paragraph(), commentAuthorName=fake.name())
        random_comment.save()


for song in songs:
    generic_playlist_entry = Playlist(playlistName="My simple playlist", songId=song)
    generic_playlist_entry.save()