예제 #1
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)))
예제 #2
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()
예제 #3
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('/')
예제 #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)
예제 #5
0
 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))
예제 #6
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
예제 #7
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__)
예제 #8
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})
예제 #9
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))
예제 #10
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))