Example #1
0
def vote(request,song_id):

    # we should get the song in the DB from the index page, so we
    # won't be adding dupe records
    try:
        song = Song.objects.get(pk=song_id)

    # this exception should occur when we vote from the search results
    # page, in which case we'll make a new DB record and give it one vote
    except Song.DoesNotExist:
        song = Song(id_code=song_id,
                 title=request.POST['title'],
                 artist=request.POST['artist'],
                 album=request.POST['album'],
                 votes=0)

    # are we voting up or down? assume up in case of forgotten POST data
    if ('vote_up' in request.POST):
        vote_up = request.POST['vote_up']
    else:
        vote_up = "False"
        
    if (vote_up == "True"):
        song.votes += 1;
#    elif (song.votes > 0): # if voting down, ensure vote # will remain nonnegative
    else: 
       song.votes -= 1;

    # else, do nothing (don't vote down)
    song.save()

    # Always return an HttpResponseRedirect after successfully dealing
    # with POST data. This prevents data from being posted twice if a
    # user hits the Back button. We redirect to the song-level results/info page
    return HttpResponseRedirect(reverse('songs:results', args=(song.id_code,)))
Example #2
0
def bulk_upload_songs(songfile):
    """
    Given a file of songs, will insert them into the database.
    Will not insert songs that are not (title, author) unique
    Returns a list of failed songs that trigger IntegrityError Exception
    """
    errors = []
    # skip headers
    songfile.readline()
    # Extract information from each row and create song objects, validating info.
    for line in songfile:
        fields = line.strip().split(",")
        song = Song()
        song, status = set_song_values(song, fields)
        
        if status is not None:
            errors.append([fields, status])
            continue
        else:
            try:
                song.save()
            except IntegrityError:
                errors.append([fields, "Failed to write to DB. Possible duplicate"])
    
    if len(errors) == 0:
        errors.append("No errors. All songs successfully inserted")
    
    return errors
Example #3
0
    def test_entity_index(self):
        author = testing.create_user()
        jack_white = Entity.create_for_testing()
        seven_nations_army = Song.create_for_testing(author)
        self.add_contribution(seven_nations_army, jack_white, True)
        jolene = Song.create_for_testing(author)
        self.add_contribution(jolene, jack_white, True)

        # Approve only Jolene.
        seven_nations_army.reviewed = False
        seven_nations_army.save()
        jolene.reviewed = True
        jolene.save()

        # General public should see only Jolene.
        response = testing.get_public_client().get(
            jack_white.get_absolute_url())
        self.assertEqual(200, response.status_code)
        self.assertEqual(1, len(response.context['songs']))

        # The author should see both.
        response = testing.get_user_client(author).get(
            jack_white.get_absolute_url())
        self.assertEqual(200, response.status_code)
        self.assertEqual(2, len(response.context['songs']))

        # Any logged-in user should see both, too.
        response = testing.get_user_client().get(jack_white.get_absolute_url())
        self.assertEqual(200, response.status_code)
        self.assertEqual(2, len(response.context['songs']))
Example #4
0
def process_one_line(line, count, debug=False):

    line = line.rstrip("\n\r")
    line = line.rstrip('/')
    folders = line.split('/')
    if len(folders) == 3:
        if (debug): print('folders=', folders)
        service_folder = folders[0]
        # if service_folder.find("Kabbalat Shabbat") >= 0:
        service_name = valid_dir_name.match(service_folder).group(2)
        if (debug): print('ServiceName=', service_name)
        service_key = service_name.replace(" ", "")
        srv = ServiceName.objects.get(pk=service_key)
        if (debug): print('srv.name=', srv.name)
        
        song_folder = folders[1]
        if (debug): print('SongFolder=', song_folder)
        
        song_name = valid_dir_name.match(song_folder).group(2)
        if (debug): print('SongName=', song_name)
        
        page_number = int(valid_dir_name.match(song_folder).group(1))
        if (debug): print('PageNumber=', page_number)
        
        file_folder = folders[2]
        file_name = valid_dir_name.match(file_folder).group(2)
        if (debug): print('FileName=',file_name)
        
        # Figure out the extension
        ext=''
        if file_name.lower().endswith(".mp3") :
            ext = "mp3"
        elif file_name.lower().endswith(".pdf") :
            ext = "pdf"
        elif file_name.lower().endswith(".jpg") :
            ext = "jpg"
        if (debug): print('Extension=',ext)
        
        sg = Song(
            service_name=srv, 
            name=song_name.replace(" ", ""), 
            display=song_name, 
            s3_obj_key=line, 
            extension=ext, 
            page_number=page_number, 
            seq_number=page_number,
            file_name=file_name)
        sg.save()
        
        if (debug): print('sequence number = ', count)
Example #5
0
    def search_and_store_track(cls,track_id):
        """
        Get track from storage, or from API if doesnt exists.
        """
        track_result = Song.get_track(track_id)
        if track_result is None:
            (track_name, artist_name) = cls.search_by_id(track_id)

            track_result = Song.save_track(
                    name = track_name,
                    artist = artist_name,
                    track_id = track_id
                )
        return track_result
 def handle(self, *args, **options):
     # add all songs that do not exist
     newsongs = 0
     for i in songs:
         print('Adding {0}'.format(i[0]))
         try:
             song = Song.objects.get(name=i[0])
             # update the song short name
             song.shortname = i[1]
         except:
             # song does not exist
             song = Song(name=i[0], shortname=i[1])
             newsongs += 1
         song.save()
     print('Added {0} new songs.'.format(newsongs))
	def handle(self, *args, **options):
		# add all songs that do not exist
		newsongs = 0
		for i in songs:
			print('Adding {0}'.format(i[0]))
			try:
				song = Song.objects.get(name=i[0])
				# update the song short name
				song.shortname = i[1]
			except:
				# song does not exist
				song = Song(name=i[0], shortname=i[1])
				newsongs += 1
			song.save()
		print('Added {0} new songs.'.format(newsongs))
Example #8
0
    def get_songs(skip, limit):
        # Set maximum limit size
        limit = min(10, limit)

        return list(
            map(lambda s: Song(s).to_dict(),
                songs_collection.find().skip(skip * limit).limit(limit)))
Example #9
0
def to_review(request):
    to_review = []
    to_review.extend(Article.items_reviewable_by(request.user))
    to_review.extend(ArtistNote.items_reviewable_by(request.user))
    to_review.extend(Post.items_reviewable_by(request.user))
    to_review.extend(Song.items_reviewable_by(request.user))
    to_review.extend(SongNote.items_reviewable_by(request.user))
    return {'to_review': to_review}
Example #10
0
def add(request):
    if request.method == 'POST':
        title = request.POST['title'] if request.POST['title'] else None
        author = request.POST['author'] if request.POST['author'] else None
        link = request.POST['link'] if request.POST['link'] else None

        Song(title=title, author=author, link=link).save()

    return redirect('/')
Example #11
0
 def setUp(self):
     # load all the songs into the DB
     for i in songs:
         foo = Song(name=i[0])
         foo.save()
     # must also add a venue
     foo = Venue(name='test', city='test', state=4, country=0)
     foo.save()
Example #12
0
 def get(self, request, *args, **kwargs):
     index = []
     for song in Song.items_live():
         index.append({
             'name': song.__str__(),
             'value': song.__str__(),
             'tokens': song.__str__().split(),
             'url': song.get_absolute_url()
         })
     return self.render_to_response({'index': index})
Example #13
0
 def get_add_url(self):
     author = testing.create_user()
     artist = Artist.create_for_testing(author)
     artist.reviewed = True
     artist.save()
     song = Song.create_for_testing(author)
     song.reviewed = True
     song.full_clean()
     song.save()
     return song.get_add_note_url()
Example #14
0
 def get(self, request, *args, **kwargs):
     index = []
     for song in Song.items_live():
         index.append({
             "name": song.__str__(),
             "value": song.__str__(),
             "tokens": song.__str__().split(),
             "url": song.get_absolute_url()
         })
     return self.render_to_response({"index": index})
Example #15
0
def to_review(request):
    to_review = []
    to_review.extend(Annotation.items_reviewable_by(request.user))
    to_review.extend(Article.items_reviewable_by(request.user))
    to_review.extend(Event.items_reviewable_by(request.user))
    to_review.extend(Post.items_reviewable_by(request.user))
    to_review.extend(Song.items_reviewable_by(request.user))
    return {
        'to_review': to_review
    }
Example #16
0
    def handle(self, *args, **kwargs):
        print 'Beginning import....'

        attrs = ['title', 'show', 'gender', 'song_style', 'additional_info', 'character_type',
                 'low_note', 'high_note', 'tessitura', 'tempo', 'character_name',
                 'original_artist', 'year', 'pre_post', 'composer', 'media_link',
                 'buy_sheet', 'buy_audio']

        book = xlrd.open_workbook('apps/songs/management/data/beltBookExcel.xlsx')
        sheet = book.sheets()[0] 

        for i in xrange(1, sheet.nrows):
            song = Song()
            for c in xrange(len(sheet.row(i))):
              attribute_str = attrs[c]
              try:
                  setattr(song, attribute_str, sheet.row(i)[c].value)
              except:
                  pass
            song.save()

        print 'Done'
Example #17
0
	def setUp(self):
		# load all the songs into the DB
		for i in songs:
			foo = Song(name=i[0])
			foo.save()
		# must also add a venue
		foo = Venue(name='test', city='test', state=4, country=0)
		foo.save()
Example #18
0
    def test_song_mentions(self):
        article = Article.create_for_testing(self.user)
        self.assertEqual(self.get_song_mentions_count(), 0)

        # Mentions should not be added until the article is public.
        song_a = Song.create_for_testing(self.user)
        link_a = '[song_a](https://example.com/opracowanie/%s)' % song_a.slug
        article.main_text_trevor = put_text_in_trevor(link_a)
        article.full_clean()
        article.save()
        self.assertEqual(self.get_song_mentions_count(), 0)

        article.reviewed = True
        article.full_clean()
        article.save()
        self.assertEqual(self.get_song_mentions_count(), 1)

        article.main_text_trevor = put_text_in_trevor(link_a + ' ' + link_a)
        article.full_clean()
        article.save()
        self.assertEqual(self.get_song_mentions_count(), 1)

        song_b = Song.create_for_testing(self.user)
        link_b = '[song_a](https://example.com/opracowanie/%s)' % song_b.slug
        article.main_text_trevor = put_text_in_trevor(link_a + ' ' + link_b)
        article.save()
        self.assertEqual(self.get_song_mentions_count(), 2)

        song_c = Song.create_for_testing(self.user)
        # This time with a trailing slash.
        link_c = '[song_a](https://example.com/opracowanie/%s/)' % song_c.slug
        article.main_text_trevor = put_text_in_trevor(link_a + ' ' + link_c)
        article.save()
        self.assertEqual(self.get_song_mentions_count(), 2)

        article.main_text_trevor = put_text_in_trevor('nothing')
        article.save()
        self.assertEqual(self.get_song_mentions_count(), 0)
Example #19
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     context['carousel_items'] = CarouselItem.objects.filter(archived=False)
     context['events'] = get_events_for(self.request.user)
     context['posts'] = (Post.items_visible_to(self.request.user)
                         .order_by('-pub_date')[:SiteIndex.POST_COUNT])
     context['songs'] = (Song.items_visible_to(self.request.user)
                         .order_by('-pub_date')[:SiteIndex.SONG_COUNT])
     context['annotation'] = (SongNote.items_visible_to(self.request.user)
                              .order_by('-pub_date').first())
     context['annotations'] = (
         SongNote.items_visible_to(self.request.user)
         .order_by('-pub_date')[:SiteIndex.ANNOTATION_COUNT])
     return context
Example #20
0
def upload_songs():
    path = r"/Users/daniel/emelody/mysite/songs.txt"
    f = open(path, 'r')
    songs = []
    for line in f:
        # Lines are in the following format:
        # Artist - Title.mp3
        line = line.replace('.mp3', '')
        line = line.split('-')
        artist = line[0].strip()
        song = line[1].strip()
        songs.append((artist, song))

    f.close()

    # Populate the Artist table
    for song in songs:
        artist = song[0]
        try: 
            db_artist = Artist.objects.get(name=artist)
        except Artist.DoesNotExist:
            db_artist = Artist(name=artist)
            db_artist.save()

    # Populate the Song table
    for song in songs:
        artist_name = song[0]
        title = song[1]
        try:
            artist = Artist.objects.get(name=artist_name)
            try:
                db_song = Song.objects.get(title=title, artist=artist)
            except Song.DoesNotExist:
                db_song = Song(title=title, artist=artist)
                db_song.save()
        except Artist.DoesNotExist:
            continue
Example #21
0
 def search(message):
     songs = list(
         map(
             lambda s: Song(s).to_dict(),
             songs_collection.find({
                 "$text": {
                     "$search": message
                 }
             }, {
                 "score": {
                     "$meta": "textScore"
                 }
             }).sort([("score", {
                 "$meta": "textScore"
             })])))
     return songs
Example #22
0
    def setUp(self):
        author = testing.create_user()
        song = Song.create_for_testing(author)
        entity = Entity.create_for_testing()
        contribution = EntityContribution()
        contribution.song = song
        contribution.entity = entity
        contribution.texted = True
        contribution.save()

        song.old_slug = "some-old-slug"
        song.reviewed = True
        song.save()

        self.song = song
        self.entity = entity
Example #23
0
    def test_get_songs(self, mock_find):
        song_dict = {
            "_id": 1,
            "artist": "Oliver Koletzki",
            "title": "No Man No Cry",
            "difficulty": 5,
            "level": 4,
            "released": "2014-01-01"
        }
        song = Song(song_dict)

        mock_find.return_value = Mock(skip=lambda x: Mock(limit=Mock(
            return_value=(song_dict, song_dict))))

        songs = SongRepository.get_songs(0, 20)

        self.assertEqual(songs[0], song.__dict__)
Example #24
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     authors = []
     for user in User.objects.filter(is_active=True):
         author = {}
         author['user'] = user
         author['annotations'] = SongNote.items_live().filter(
             author=user).count() + ArtistNote.items_live().filter(
                 author=user).count()
         author['songs'] = Song.items_live().filter(author=user).count()
         author['articles'] = Article.items_live().filter(
             author=user).count()
         author['total'] = (author['annotations'] + author['songs'] +
                            self.ARTICLE_FACTOR * author['articles'])
         if author['total']:
             authors.append(author)
     context['authors'] = sorted(
         authors, key=lambda k: k['total'], reverse=True)
     return context
Example #25
0
def addSong(request):
    if request.method == 'POST':
        form = SongForm(request.POST)
        if form.is_valid():
            # Process form data from form.cleaned_data
            newTrackNum = len(
                Song.objects.filter(
                    playlistID__exact=form.cleaned_data['playlistID']))
            currentSong = Song()
            currentSong.songName = form.cleaned_data['songName']
            currentSong.songUrl = form.cleaned_data['songUrl']
            currentSong.playlistID = form.cleaned_data['playlistID']
            currentSong.playlistPosition = newTrackNum
            currentSong.save()
            pl_id = currentSong.playlistID
            return HttpResponseRedirect("/songs/%d&tracknum=%d" %
                                        (pl_id, newTrackNum))
    else:
        form = SongForm()

    return render(request, 'songs/addSong.html', {'form': form})
Example #26
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     context['article'] = (Article.items_visible_to(self.request.user)
                           .order_by('-pub_date').first())
     context['events'] = get_events_for(self.request.user)
     context['posts'] = (Post.items_visible_to(self.request.user)
                         .order_by('-pub_date')[:SiteIndex.POST_COUNT])
     context['songs'] = (Song.items_visible_to(self.request.user)
                         .order_by('-pub_date')[:SiteIndex.SONG_COUNT])
     context['song_of_the_day'] = self.get_song_of_the_day()
     context['annotation'] = (SongNote.items_visible_to(self.request.user)
                              .order_by('-pub_date').first())
     song_notes = SongNote.items_visible_to(self.request.user).order_by(
         '-pub_date')[:SiteIndex.ANNOTATION_COUNT]
     artist_notes = ArtistNote.items_visible_to(self.request.user).order_by(
         '-pub_date')[:SiteIndex.ANNOTATION_COUNT]
     notes = (list(song_notes) + list(artist_notes))
     notes.sort(key=lambda x: x.pub_date, reverse=True)
     context['annotations'] = notes[:SiteIndex.ANNOTATION_COUNT]
     return context
Example #27
0
    def test_add_song_note(self):
        user = testing.create_user()
        artist = Artist.create_for_testing(user)
        artist.reviewed = True
        artist.full_clean()
        artist.save()

        song = Song.create_for_testing(user)
        song.reviewed = True
        song.full_clean()
        song.save()

        data = {
            'title': 'dalsze losy kotka',
            'text_trevor': put_text_in_trevor('Abc')
        }
        self.assertEqual(len(SongNote.objects.all()), 0)
        response = testing.get_user_client(user=user).post(
            song.get_add_note_url(), data=data)
        self.assertEqual(302, response.status_code)
        self.assertRedirects(response, song.get_absolute_url())
        self.assertEqual(len(SongNote.objects.all()), 1)
Example #28
0
    def test_cannot_add_song_note_if_song_not_reviewed(self):
        user = testing.create_user()
        artist = Artist.create_for_testing(user)
        artist.reviewed = True
        artist.full_clean()
        artist.save()

        song = Song.create_for_testing(user)
        song.reviewed = True
        song.full_clean()
        song.save()

        url = song.get_add_note_url()
        song.reviewed = False
        song.full_clean()
        song.save()

        data = {
            'title': 'dalsze losy kotka',
            'text_trevor': put_text_in_trevor('Abc')
        }
        response = testing.get_user_client(user=user).post(url, data=data)
        self.assertEqual(404, response.status_code)
        self.assertEqual(len(SongNote.objects.all()), 0)
Example #29
0
 def setUp(self):
     s = Song(url = "fake", title = "fake", artist = "fake", artwork = "a")
     s.save()
Example #30
0
def song_add(request, song_name, duration):
    song = Song(name=song_name, duration=duration)
    song.save()
    return HttpResponse("Song was added wiht id {}".format(song.pk))
Example #31
0
	def test_songinfo(self):
		playlist = Playlist(name="cool songs")
		artist = Artist(name="Josh")
		album = Album(name="Pizzaman")
		song = Song(name="King Ass", album=album, artist=artist, playlist=playlist)
		this.assertEquals("King Ass by Josh on Pizzaman", song.song_info())
Example #32
0
    def handle(self, *args, **options):
        # import the scan_tool we will use
        spec = importlib.util.spec_from_file_location(
            'scan_tool',
            Setting.objects.get(key='scan_tool').value)
        scan_tool = importlib.util.module_from_spec(spec)
        sys.modules[spec.name] = scan_tool
        spec.loader.exec_module(scan_tool)

        # new artists, songs and metadata are added by "admin"
        admin_id = User.objects.get(username='******').pk

        for path in options['paths']:
            # scan the uploaded file
            try:
                info = scan_tool.scan(path)
            except Exception as e:
                raise ValueError("Failed to parse uploaded file: %s" % str(e))

            # also calculate the hash
            with open(path, 'rb') as f:
                filehash = hashlib.sha1(f.read()).digest()

            # construct song meta dict for adding new entries
            file_info = {
                'file_type': info['file_type'],
                'sample_rate': info['sample_rate'],
                'channels': info['channels'],
                'bit_rate': info['bit_rate'],
                'duration': timedelta(seconds=info['duration']),
                'hash': filehash
            }

            song_info = {}
            changed_fields = 'name filepath'
            if 'tags' in info:
                if 'title' in info['tags']:
                    song_info['name'] = info['tags']['title']
                else:
                    song_info['name'] = path

                if 'album' in info['tags']:
                    song_info['info'] = info['tags']['album']
                    changed_fields += ' info'
                if 'date' in info['tags']:
                    song_info['date'] = datetime.strptime(
                        info['tags']['date'], '%Y-%m-%d')
                    changed_fields += ' release_date'

                if 'artist' in info['tags']:
                    artist_name = info['tags']['artist']
                    changed_fields += ' artist'
            else:
                song_info['name'] = path
                artist_name = None

            # get the artist from the DB - if it doesn't exist, we need to create it
            if artist_name:
                try:
                    artist = Artist.objects.get(name=artist_name)
                except Artist.DoesNotExist:
                    artist = Artist(name=artist_name)
                    artist.save()
                    artist_meta = ArtistMeta(artist=artist, name=artist_name)
                    artist_meta.save()
            else:
                artist = None

            # Everything is parsed.  We're committed to import now!
            #  create the song and meta, and attach the song to it.
            with open(path, 'rb') as f:
                imported_filename = default_storage.save(
                    upload_to(None, path), f)

            # file has been imported to our local filesystem
            #  now we can create an SongFile object around it
            song_file = SongFile(filepath=imported_filename, **file_info)
            song_file.save()

            # add the Song
            song = Song(**song_info)
            song.song_file = song_file
            song.save()

            song.artist.set([artist])
            song_meta = SongMeta(song=song,
                                 reviewed=True,
                                 accepted=True,
                                 changed_fields=changed_fields,
                                 submitter_id=admin_id,
                                 song_file=song_file,
                                 **song_info)
            song_meta.save()
            song_meta.artist.set([artist])

            self.stdout.write(
                self.style.SUCCESS('Successfully imported file "%s"' % path))
Example #33
0
    def test_user_menu(self):
        response = testing.get_user_client().get(reverse('index'))
        self.assertEqual(200, response.status_code)
        self.assertNotContains(response, reverse('hello'), html=False)
        self.assertContains(response, reverse('goodbye'), html=False)
        self.assertNotContains(response, reverse('add_article'), html=False)
        self.assertNotContains(response, reverse('add_event'), html=False)
        self.assertNotContains(response, reverse('add_post'), html=False)
        self.assertNotContains(response, reverse('add_song'), html=False)

        user = testing.create_user(perms=[Article.permstring()])
        response = testing.get_user_client(user).get(reverse('index'))
        self.assertEqual(200, response.status_code)
        self.assertNotContains(response, reverse('hello'), html=False)
        self.assertContains(response, reverse('goodbye'), html=False)
        self.assertContains(response, reverse('add_article'), html=False)
        self.assertNotContains(response, reverse('add_event'), html=False)
        self.assertNotContains(response, reverse('add_post'), html=False)
        self.assertNotContains(response, reverse('add_song'), html=False)

        user = testing.create_user(perms=[Event.permstring()])
        response = testing.get_user_client(user).get(reverse('index'))
        self.assertEqual(200, response.status_code)
        self.assertNotContains(response, reverse('hello'), html=False)
        self.assertContains(response, reverse('goodbye'), html=False)
        self.assertNotContains(response, reverse('add_article'), html=False)
        self.assertContains(response, reverse('add_event'), html=False)
        self.assertNotContains(response, reverse('add_post'), html=False)
        self.assertNotContains(response, reverse('add_song'), html=False)

        user = testing.create_user(perms=[Post.permstring()])
        response = testing.get_user_client(user).get(reverse('index'))
        self.assertEqual(200, response.status_code)
        self.assertNotContains(response, reverse('hello'), html=False)
        self.assertContains(response, reverse('goodbye'), html=False)
        self.assertNotContains(response, reverse('add_article'), html=False)
        self.assertNotContains(response, reverse('add_event'), html=False)
        self.assertContains(response, reverse('add_post'), html=False)
        self.assertNotContains(response, reverse('add_song'), html=False)

        user = testing.create_user(perms=[Song.permstring()])
        response = testing.get_user_client(user).get(reverse('index'))
        self.assertEqual(200, response.status_code)
        self.assertNotContains(response, reverse('hello'), html=False)
        self.assertContains(response, reverse('goodbye'), html=False)
        self.assertNotContains(response, reverse('add_article'), html=False)
        self.assertNotContains(response, reverse('add_event'), html=False)
        self.assertNotContains(response, reverse('add_post'), html=False)
        self.assertContains(response, reverse('add_song'), html=False)

        user = testing.create_user(perms=[Article.permstring(),
                                          Event.permstring(),
                                          Post.permstring(),
                                          Song.permstring()])
        response = testing.get_user_client(user).get(reverse('index'))
        self.assertEqual(200, response.status_code)
        self.assertNotContains(response, reverse('hello'), html=False)
        self.assertContains(response, reverse('goodbye'), html=False)
        self.assertContains(response, reverse('add_article'), html=False)
        self.assertContains(response, reverse('add_event'), html=False)
        self.assertContains(response, reverse('add_post'), html=False)
        self.assertContains(response, reverse('add_song'), html=False)
Example #34
0
for line in f:
    # Lines are in the following format:
    # Artist - Title.mp3
    line = line.replace('.mp3', '')
    line = line.split(' - ')
    artist = line[0].strip()
    song = line[1].strip()
    songs.append((artist, song))

f.close()

# Populate the Artist table
for song in songs:
    artist = song[0]
    try: 
        db_artist = Artist.objects.get(name=artist)
    except Artist.DoesNotExist:
        db_artist = Artist(name=artist)
        db_artist.save()

# Populate the Song table
for song in songs:
    artist = song[0]
    title = song[1]
    try:
        db_song = Song.objects.get(title=title, artist=artist)
    except Song.DoesNotExist:
        db_song = Song(title=title, artist=artist)
        db_song.save()

Example #35
0
    def save(self, request):
       
        song = Song()
        song.user =  request.user
        
        domain_name = ''
        if self.cleaned_data['audio_url']:
            domain_name = self.cleaned_data['audio_url'].split('/')
            song.audio_url = self.cleaned_data['audio_url']                
            
        if self.cleaned_data['vedio_url']:
            domain_name = self.cleaned_data['vedio_url'].split('/')
            song.vedio_url = self.cleaned_data['vedio_url']
            
        if self.cleaned_data['flash_url']:
            domain_name = self.cleaned_data['flash_url'].split('/')
            song.flash_url = self.cleaned_data['flash_url']
            
        if len(domain_name) >= 2:
            song.source = domain_name[2]
            if song.flash_url:
                s_size = _get_swf_size(song.source)
                song.flash_width = s_size[0]
                song.flash_height = s_size[1]
            
        song.title = self.cleaned_data['title']
        song.singer = self.cleaned_data['singer']
        song.album = self.cleaned_data['album']
        song.genre = SongGenre.objects.get(id=self.cleaned_data['genre'])
        if self.cleaned_data['song_cover_url'].find('images/artist.png') == -1:
            song.song_cover_url = self.cleaned_data['song_cover_url']
        song.intro = self.cleaned_data['intro']
        song.show_media = True
        
        #当链接是百度那个下载链接(但不能在线引用播放)时,转成flash
        if song.audio_url and song.audio_url.find('zhangmenshiting') != -1 and song.audio_url.find('baidu') != -1:
            song.audio_url = None
            m = {'artist' : song.singer, 'name' : song.title, }
            song.flash_url = 'http://box.baidu.com/widget/flash/mbsong.swf?%s' % (urllib.urlencode(m))
            song.flash_width = 400
            song.flash_height = 95
        
        song.save()

        #加入电台播放
        if song.audio_url and request.POST.get('add_to_playlist'):
            _add_to_playlist(song, request.user)

        #发布到新浪微博
        if (request.POST.get('share_swf_to_weibo') and song.flash_url) or (request.POST.get('share_to_weibo') and song.audio_url):

            current_site = get_current_site(request)

            domain = current_site.domain
            public_radio_url = reverse('songs.views.public_radio',args=(song.id,))

            from social.views import _post_weibo
            s_url = 'http://%s%s' % (domain, public_radio_url)
            msg = '[%s-%s]%s' %(song.title, song.singer, song.intro)
            _post_weibo(request, msg, s_url)

        request.user.get_profile()
        request.user.get_profile().songs = request.user.get_profile().songs + 1
        request.user.get_profile().save()
Example #36
0
    def process_postback(self, postback_payload):
        """ 
        Understand payload-type(switch), process something and create response
        """
        if postback_payload == "GET_STARTED_BOT":
            response_data = "Soy un bot de busqueda musical por letras/lyrics"
            self.record_message_and_payload(response_data, postback_payload)
            return (response_data, ResponseType.default)

        if postback_payload == "LYRICS_PAYLOAD":
            response_data = "escribe la letra que quieres buscar :)"
            self.record_message_and_payload(response_data,
                                            postback_payload,
                                            with_follow_up=True)
            return (response_data, ResponseType.text)

        if "FAVORITE_" in postback_payload:
            track_id = postback_payload.split("_")[1]
            (track, was_saved) = self.search_track_by_id(track_id)

            if was_saved:
                response_data = "se guardó la canción {} en tu lista de favoritos".format(
                    track.name)
            else:
                response_data = "la canción {} ya estaba en tu lista de favoritos".format(
                    track.name)
            self.record_message_and_payload(response_data, postback_payload)

            return (response_data, ResponseType.text)

        if "REMOVE_" in postback_payload:
            track_id = postback_payload.split("_")[1]
            #removed = self.remove_track_by_id(track_id)
            removed = True

            if removed:
                response_data = "Se Borró la canción seleccionada"
            else:
                response_data = "La canción no existe en tu lista de canciones"
            self.record_message_and_payload(response_data, postback_payload)

            return (response_data, ResponseType.text)

        if postback_payload == "FAVORITES_PAYLOAD":
            favorite_songs = Song.favorites_by_user(self.sender_id)

            response_message = "tienes {} cancion(es) en tu lista de favoritos, estas son:".format(
                len(favorite_songs))
            self.record_message_and_payload(response_message, postback_payload)
            response_data = {
                "text": response_message,
                "data": favorite_songs,
                "buttons": {
                    "title": "Eliminar",
                    "payload": "REMOVE_{}_PAYLOAD",
                }
            }
            return (response_data, ResponseType.results)

        if postback_payload == "COUNT_USERS":
            users_quantity = User.users_quantity()
            response_data = "Aproximadamente {} usuario(s) utilizan el bot".format(
                users_quantity)
            self.record_message_and_payload(response_data, postback_payload)
            return (response_data, ResponseType.text)

        if postback_payload == "CHAT_DAYS":
            chats_daily_quantity = Conversation.quantity_by_day()
            response_data = "Aproximadamente hay {} chat(s) en el día a día".format(
                chats_daily_quantity)
            self.record_message_and_payload(response_data, postback_payload)
            return (response_data, ResponseType.text)

        if postback_payload == "TOP_FAVORITES":
            top_songs = Song.get_top_songs()

            response_message = "estos son las top 5 canciones:"
            self.record_message_and_payload(response_message, postback_payload)
            response_data = {
                "text": response_message,
                "data": top_songs,
                "buttons": {
                    "title": "Favorita",
                    "payload": "FAVORITE_{}_PAYLOAD",
                }
            }
            return (response_data, ResponseType.results)