Example #1
0
def process_file(f, source_id):
    extension = splitext(f)[1].lower()
    if extension == '.mp3':
        # found a MP3!
        id3 = id3reader.Reader(f)
        album = id3.getValue('album')
        artist = id3.getValue('performer') or album
        title = id3.getValue('title')
        try:
            m = Music.objects.get(filename=f)
        except Music.DoesNotExist:
            # new one
            m = Music()
        if title is not None and artist is not None:
            m.album = album or "Unknown Album"
            m.artist = artist
            m.title = title
        else:
            info = MUSIC_MATCH_REGEX.search(f)
            if info is None:
                return 0
            m.album = "Unknown Album"
            m.artist = "%s - %s" % (info.groupdict()['folder'], info.groupdict()['subfolder'])
            m.title = info.groupdict()['title']
        m.filename = f
        m.source_id = source_id
        try:
            m.save()
            return 1
        except IntegrityError:
            # probably missing information, skip it
            pass
    return 0
Example #2
0
File: views.py Project: Wextree/ASR
def create_label(request):
    # get the address of the wav audio
    if request.method == 'POST':
        # wav_path = request.POST.get('path')
        file = request.FILES['file']
    # print(wav_path)

    wavName = "./music/wav/" + file.name
    print(wavName)
    with open(wavName, 'wb') as wav:
        for c in file.chunks():
            wav.write(c)


    music = Music()
    music.wav_path = wavName

    # load the web of ASR
    gen = load_model('music\MusicClass\music_cla_model.h5')

    # check the length of the audio and cut into a proper length
    x, sr = librosa.load(wavName)
    if len(x) < 88200:
        x = np.pad(x, (0, 88200 - x.shape[0]), 'constant')
    else:
        x = x[0:88200:1]

    # add some feature and reshape it
    mfcc = librosa.feature.mfcc(y=x, sr=sr, n_mfcc=40)
    norm_mfcc = sklearn.preprocessing.scale(mfcc, axis=1)
    mfcc = norm_mfcc.reshape(1, mfcc.shape[0], mfcc.shape[1], 1)

    # predict the result and get the best one and its label
    result = gen.predict(mfcc)
    probability = []
    result = result.reshape(10, 1)
    for num in result:
        probability.append(float(num))
    print(probability, sum(probability), max(probability))
    music.probability = max(probability)
    music.label = probability.index(max(probability))
    print("label:" + str(music.label))
    music.save()


    return HttpResponse("succeed!!!")

# def create_label(request):
#     # get the address of the wav audio
#     if request.method == 'POST':
#         # wav_path = request.POST.get('path')
#         file = request.FILES['file']
#     print(type(file))
#     print(file.name)
#     wavName = "./music/wav/" + file.name
#     print(wavName)
#     with open(wavName, 'wb') as wav:
#         for c in file.chunks():
#             wav.write(c)
#     return HttpResponse("succeed!!!")
Example #3
0
    def test_initialization(self):
        settings.TESTING = False

        # Create fake app to test ready method
        init = Init.create('music')
        init.models = {
            'playlisttrack': PlaylistTrack
        }

        music = Music(
            room=self.r,
            music_id="a",
            name="a",
            total_duration=211,
            duration=211,
            thumbnail="https://a.com/a.jpg",
        )
        music.save()

        PlaylistTrack(track=music, room=self.r).save()

        init.ready()

        self.r.tracks.count().should.eql(0)

        settings.TESTING = True
Example #4
0
    def test_next(self):
        m = Music(
            music_id="a",
            name="a",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m.save()

        self.r.current_music = m
        self.r.save()

        m2 = Music(
            music_id="b",
            name="b",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m2.save()
        PlaylistTrack.objects.create(room=self.r, track=m2)

        response = self.client.post('/room/next', {'music_pk': m.pk})

        response.status_code.should.eql(status.HTTP_200_OK)
        self.assertResponseEqualsMusic(response.data['current_music'],
                                       self.reload(m2))
Example #5
0
    def test_play_next_with_shuffle(self):
        music = Music(
            room=self.r,
            music_id='a',
            name='a',
            total_duration=200,
            duration=200,
            thumbnail='https://a.com/a.jpg',
        )
        music.save()

        music2 = Music(
            room=self.r,
            music_id='b',
            name='b',
            total_duration=200,
            duration=200,
            thumbnail='https://a.com/a.jpg',
        )
        music2.save()

        self.r.shuffle = True
        self.r.save()
        PlaylistTrack(track=music, room=self.r).save()

        self.r.play_next()
        self.r.current_music.should.eql(music)

        self.r.play_next()
        # No music in the playlist, but should select an other.
        self.r.current_music.should_not.be.none
Example #6
0
    def test_post_below_or_above_action(self):
        m2 = Music(
            music_id="b",
            name="b",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m2.save()

        pt2 = PlaylistTrack(track=m2, room=self.r)
        pt2.save()

        response = self.client.post('/playlist/%s/below/%s' %
                                    (self.pt.pk, pt2.pk))

        response.status_code.should.eql(status.HTTP_200_OK)
        list(self.r.playlist.all()).should.eql([pt2, self.pt])

        response = self.client.post('/playlist/%s/above/%s' %
                                    (pt2.pk, self.pt.pk))

        response.status_code.should.eql(status.HTTP_200_OK)
        list(self.r.playlist.all()).should.eql([pt2, self.pt])
Example #7
0
    def test_play_next_with_shuffle(self):
        music = Music(
            room=self.r,
            music_id='a',
            name='a',
            total_duration=200,
            duration=200,
            thumbnail='https://a.com/a.jpg',
        )
        music.save()

        music2 = Music(
            room=self.r,
            music_id='b',
            name='b',
            total_duration=200,
            duration=200,
            thumbnail='https://a.com/a.jpg',
        )
        music2.save()

        self.r.shuffle = True
        self.r.save()
        PlaylistTrack(track=music, room=self.r).save()

        self.r.play_next()
        self.r.current_music.should.eql(music)

        self.r.play_next()
        # No music in the playlist, but should select an other.
        self.r.current_music.should_not.be.none
Example #8
0
    def test_next(self):
        m = Music(
            music_id="a",
            name="a",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m.save()

        self.r.current_music = m
        self.r.save()

        m2 = Music(
            music_id="b",
            name="b",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m2.save()
        PlaylistTrack.objects.create(room=self.r, track=m2)

        response = self.client.post('/room/next', {'pk': m.pk})

        response.status_code.should.eql(status.HTTP_200_OK)
        self.assertResponseEqualsMusic(response.data['current_music'], self.reload(m2))
Example #9
0
    def test_patch(self):
        m = Music(
            music_id="a",
            name="a",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m.save()

        response = self.client.patch('/music/%s' % m.pk, {
            'timer_start': 8,
            'duration': 106
        })

        response.status_code.should.eql(status.HTTP_200_OK)
        response.data.should.have.key('timer_start').which.should.equal(8)
        response.data.should.have.key('duration').which.should.equal(106)

        m = self.reload(m)

        m.timer_start.should.eql(8)
        m.duration.should.eql(106)
Example #10
0
    def test_music_serializer(self):
        m = Music(
            music_id='a',
            name='a',
            thumbnail='https://a.com',
            total_duration=114,
            duration=114,
            url='https://www.a.com',
            source='youtube',
            room=self.r,
        )
        m.save()

        expected_serialization = {
            'pk': m.pk,
            'music_id': 'a',
            'name': 'a',
            'thumbnail': 'https://a.com',
            'total_duration': 114,
            'duration': 114,
            'url': 'https://www.a.com',
            'source': 'youtube',
            'timer_start': 0,
            'count': 0,
            'last_play': None,
            'one_shot': False
        }

        dict(MusicSerializer(m).data).should.eql(expected_serialization)
Example #11
0
    def test_post_existing_music(self):
        m = Music(
            music_id="a",
            name="a",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m.save()

        music_to_post = {
            "music_id": "a",
            "name": "a",
            "thumbnail": "https://a.com",
            "total_duration": 114,
            "duration": 100,
            "url": "https://www.a.com",
            "source": "youtube",
        }

        response = self.client.post('/music', music_to_post)

        response.status_code.should.eql(status.HTTP_201_CREATED)
        response.data.should.have.key('duration').which.should.eql(100)

        Music.objects.filter(music_id='a', room=self.r).first().duration.should.be.eql(100)
Example #12
0
    def test_post_existing_music(self):
        m = Music(
            music_id="a",
            name="a",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m.save()

        music_to_post = {
            "music_id": "a",
            "name": "a",
            "thumbnail": "https://a.com",
            "total_duration": 114,
            "duration": 100,
            "url": "https://www.a.com",
            "source": "youtube",
        }

        response = self.client.post('/music', music_to_post)

        response.status_code.should.eql(status.HTTP_201_CREATED)
        response.data.should.have.key('duration').which.should.eql(100)

        Music.objects.filter(music_id='a',
                             room=self.r).first().duration.should.be.eql(100)
Example #13
0
    def get_new_music(self):
        music = Music(name='Test',
                      album=self.album,
                      order=1,
                      file=self._get_mp3())

        music.save()
        return music
Example #14
0
    def handle(self, *args, **options):
        try:
            vkey = re.findall('"key": "(\w+)"', requests.get(QQ_MUSIC_MP3_KEY).content)[0]

            music_top100_list = requests.get(QQ_MUSIC_TOP100).json()
            data = []
            for m in music_top100_list['songlist']:
                album_id = m['data']['albummid']
                song_id = m['data']['songmid']
                song_name = m['data']['songname']
                song_lyric = base64.b64decode(
                    re.findall('"lyric":"(.*)"',
                               requests.get(QQ_MUSIC_LYRIC.format(song_id), headers=headers).content)[0])
                data.append({
                    'song_id': song_id,
                    'song_name': song_name,
                    'song_mp3_url': QQ_MUSIC_MP3_FILE.format(song_id, vkey),
                    'song_mp3': u'/{}/{}.mp3'.format(_base_mp3, song_name),
                    'song_lyric': song_lyric,
                    'album_name': m['data']['albumname'],
                    'album_image_url': QQ_MUSIC_ALBUM.format(album_id[-2], album_id[-1], album_id),
                    'album_image': u'/{}/{}.jpg'.format(_base_image, song_name),
                    'singer': '/'.join([s['name'] for s in m['data']['singer']]),
                })

            from django.conf import settings

            if not os.path.exists(os.path.join(settings.BASE_DIR, _base_mp3)):
                os.mkdir(os.path.join(settings.BASE_DIR, _base_mp3))
            if not os.path.exists(os.path.join(settings.BASE_DIR, _base_image)):
                os.mkdir(os.path.join(settings.BASE_DIR, _base_image))
            for m in data:
                try:
                    Music.objects.get(song_id=m['song_id'])
                except Music.DoesNotExist:
                    print u'`{}` start download ....'.format(m['song_name'])
                    try:
                        urllib.urlretrieve(m.pop('song_mp3_url'),
                                           os.path.join(settings.BASE_DIR, _base_mp3, '{}.mp3'.format(m['song_name'])))
                        urllib.urlretrieve(m.pop('album_image_url'),
                                           os.path.join(settings.BASE_DIR, _base_image, '{}.jpg'.format(m['song_name'])))
                    except Exception as e:
                        self.stdout.write(self.style.ERROR(u'download `{}`Have an error: `{}`'.format(m['song_name'], e)))
                        continue

                    music = Music(**m)
                    music.save()
                else:
                    continue
        except Exception as e:
            self.stdout.write(self.style.ERROR('Have an error: `{}`'.format(e)))
        else:
            self.stdout.write('Successfully crawl qq music.')
    def post(self, request):
        file = request.FILES.get("file", None)
        if not file:
            return JsonResponse({"code": 400, "error": "file can not empty"})

        file_name = "{time}_{origin_name}".format(
            origin_name=file.name,
            time=datetime.now().strftime("%Y-%m-%d_%H:%M%S"))
        destination = open(os.path.join("static/uploads/", file_name),
                           'wb+')  # 打开特定的文件进行二进制的写操作
        for chunk in file.chunks():  # 分块写入文件
            destination.write(chunk)
        destination.close()

        print(request.data)
        print(request.data['music_name'], request.data['music_auth'])
        music_info = {
            **request.data,
            **{
                'user': request.user.id,
                'path': "static/uploads/{name}".format(name=file_name)
            }
        }
        music_info['music_name'] = music_info['music_name'][0]
        music_info['music_auth'] = music_info['music_auth'][0]
        # music_info['file'] = music_info['file'][0]
        serilizer = UploadMusicSerializer(data=music_info)
        if serilizer.is_valid():
            serilizer.save()
            # return JsonResponse({"code": 200, "data": serilizer.data, 'error': ""})
        else:
            return JsonResponse({
                "code": 200,
                "data": "",
                'error': serilizer.errors
            })
        music = Music(music_name=request.data['music_name'],
                      music_auth=request.data['music_auth'],
                      music_url=serilizer.data.get('path'))
        print(serilizer.data.get('path'))
        music.save()

        _data = {
            "music_name": music.music_name,
            "music_auth": music.music_auth,
            "music_url": music.music_url,
            "id": music.id
        }
        print(_data)

        return JsonResponse({"code": 200, "data": _data, 'error': ""})
Example #16
0
    def test_get_musics_remaining(self):
        music = Music(
            room=self.r,
            music_id='a',
            name='a',
            total_duration=200,
            duration=200,
            thumbnail='https://a.com/a.jpg',
        )
        music.save()

        PlaylistTrack(track=music, room=self.r).save()

        list(self.r.get_musics_remaining()).should.eql([music])
Example #17
0
    def test_get_musics_remaining(self):
        music = Music(
            room=self.r,
            music_id='a',
            name='a',
            total_duration=200,
            duration=200,
            thumbnail='https://a.com/a.jpg',
        )
        music.save()

        PlaylistTrack(track=music, room=self.r).save()

        list(self.r.get_musics_remaining()).should.eql([music])
Example #18
0
    def test_patch_bad_arguments(self):
        m = Music(
            music_id="a",
            name="a",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m.save()

        response = self.client.patch('/music', {'pk': m.pk, 'total_duration': 'wtf'})

        response.status_code.should.eql(status.HTTP_400_BAD_REQUEST)
Example #19
0
    def test_get_remaining_time(self):
        # Still no music
        self.r.get_remaining_time().should.eql(0)

        music = Music(room=self.r,
                      music_id='a',
                      name='a',
                      total_duration=200,
                      duration=200,
                      thumbnail='https://a.com/a.jpg',
                      last_play=datetime.now())
        music.save()

        PlaylistTrack(track=music, room=self.r).save()

        self.r.get_remaining_time().should.eql(200)
Example #20
0
    def test_stop(self):
        music = Music(
            room=self.r,
            music_id='a',
            name='a',
            total_duration=200,
            duration=200,
            thumbnail='https://a.com/a.jpg',
        )
        music.save()

        self.r.current_music = music
        self.r.save()

        self.r.stop()

        self.r.current_music.should.be.none
Example #21
0
    def test_next_no_current_music(self):
        m = Music(
            music_id="a",
            name="a",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m.save()

        response = self.client.post('/room/next', {'pk': m.pk})

        response.status_code.should.eql(status.HTTP_400_BAD_REQUEST)
        response.data.should.eql("Can't next while no music is currently played")
Example #22
0
    def test_patch_bad_arguments(self):
        m = Music(
            music_id="a",
            name="a",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m.save()

        response = self.client.patch('/music/%s' % m.pk,
                                     {'total_duration': 'wtf'})

        response.status_code.should.eql(status.HTTP_400_BAD_REQUEST)
Example #23
0
    def test_add_music(self):
        music = Music(room=self.r,
                      music_id='b',
                      name='b',
                      total_duration=200,
                      duration=200,
                      thumbnail='https://a.com/a.jpg',
                      source='youtube')
        music.save()

        self.r.add_music(music)
        self.r.music_set.count().should.eql(1)
        self.r.current_music.music_id.should.eql('b')

        self.r.add_music(music)

        self.r.tracks.count().should.eql(1)
Example #24
0
    def test_stop(self):
        music = Music(
            room=self.r,
            music_id='a',
            name='a',
            total_duration=200,
            duration=200,
            thumbnail='https://a.com/a.jpg',
        )
        music.save()

        self.r.current_music = music
        self.r.save()

        self.r.stop()

        self.r.current_music.should.be.none
Example #25
0
    def test_update(self):
        music = Music(room=self.r,
                      music_id='a',
                      name='a',
                      total_duration=200,
                      duration=200,
                      thumbnail='https://a.com/a.jpg',
                      source='youtube')
        music.save()

        self.r.update({'shuffle': True})

        self.r.shuffle.should.be.true

        self.r.update({'can_adjust_volume': True})

        self.r.can_adjust_volume.should.be.true
Example #26
0
    def test_next_no_current_music(self):
        m = Music(
            music_id="a",
            name="a",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m.save()

        response = self.client.post('/room/next', {'music_pk': m.pk})

        response.status_code.should.eql(status.HTTP_400_BAD_REQUEST)
        response.data.should.eql(
            "Can't next while no music is currently played")
Example #27
0
    def create(self, validated_data):
        """
            Override the default Serializer.save() method
            =============================================

            create(..) is called if we don't pass an existing music to the Serializer
            update(..) method NEED to be implemented too !

            :param self: Instance param
            :param validated_data: A dict of validated data from the Serializer
            :type self: MusicSerializer
            :type validated_data: dict
            :return: The Music object CREATED with the valid data from the Serializer
            :rtype: Music
        """
        music = Music(**validated_data)
        music.save()
        return music
Example #28
0
    def test_delete(self):
        m = Music(
            music_id="a",
            name="a",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m.save()

        response = self.client.delete('/music', {'pk': m.pk})

        response.status_code.should.eql(status.HTTP_204_NO_CONTENT)

        Music.objects.filter(music_id="a", room=self.r).exists().should.be.false
Example #29
0
    def create(self, validated_data):
        """
            Override the default Serializer.save() method
            =============================================

            create(..) is called if we don't pass an existing music to the Serializer
            update(..) method NEED to be implemented too !

            :param self: Instance param
            :param validated_data: A dict of validated data from the Serializer
            :type self: MusicSerializer
            :type validated_data: dict
            :return: The Music object CREATED with the valid data from the Serializer
            :rtype: Music
        """
        music = Music(**validated_data)
        music.save()
        return music
Example #30
0
    def test_get_remaining_time(self):
        # Still no music
        self.r.get_remaining_time().should.eql(0)

        music = Music(
            room=self.r,
            music_id='a',
            name='a',
            total_duration=200,
            duration=200,
            thumbnail='https://a.com/a.jpg',
            last_play=datetime.now()
        )
        music.save()

        PlaylistTrack(track=music, room=self.r).save()

        self.r.get_remaining_time().should.eql(200)
Example #31
0
    def test_get_current_time_past_percent(self):
        self.r.get_current_time_past_percent().should.eql(0)

        music = Music(
            room=self.r,
            music_id='a',
            name='a',
            total_duration=240,
            duration=240,
            thumbnail='https://a.com/a.jpg',
            last_play=datetime.now() - timedelta(minutes=2)  # Music started 2 minutes ago
        )
        music.save()

        self.r.current_music = music
        self.r.save()

        self.r.get_current_time_past_percent().should.eql(float(50))
Example #32
0
    def test_add_music(self):
        music = Music(
            room=self.r,
            music_id='b',
            name='b',
            total_duration=200,
            duration=200,
            thumbnail='https://a.com/a.jpg',
            source='youtube'
        )
        music.save()

        self.r.add_music(music)
        self.r.music_set.count().should.eql(1)
        self.r.current_music.music_id.should.eql('b')

        self.r.add_music(music)

        self.r.tracks.count().should.eql(1)
Example #33
0
    def test_get_current_time_past_percent(self):
        self.r.get_current_time_past_percent().should.eql(0)

        music = Music(
            room=self.r,
            music_id='a',
            name='a',
            total_duration=240,
            duration=240,
            thumbnail='https://a.com/a.jpg',
            last_play=datetime.now() -
            timedelta(minutes=2)  # Music started 2 minutes ago
        )
        music.save()

        self.r.current_music = music
        self.r.save()

        self.r.get_current_time_past_percent().should.eql(float(50))
Example #34
0
    def test_update(self):
        music = Music(
            room=self.r,
            music_id='a',
            name='a',
            total_duration=200,
            duration=200,
            thumbnail='https://a.com/a.jpg',
            source='youtube'
        )
        music.save()

        self.r.update({'shuffle': True})

        self.r.shuffle.should.be.true

        self.r.update({'can_adjust_volume': True})

        self.r.can_adjust_volume.should.be.true
Example #35
0
    def test_delete(self):
        m = Music(
            music_id="a",
            name="a",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m.save()

        response = self.client.delete('/music/%s' % m.pk)

        response.status_code.should.eql(status.HTTP_204_NO_CONTENT)

        Music.objects.filter(music_id="a",
                             room=self.r).exists().should.be.false
Example #36
0
    def test_play(self):
        music = Music(
            room=self.r,
            music_id='a',
            name='a',
            total_duration=200,
            duration=200,
            thumbnail='https://a.com/a.jpg',
        )
        music.save()

        self.r.play(music)

        self.r.current_music.should.eql(music)

        music.count.should.eql(1)
        music.last_play.should_not.be.none

        Events.get(self.r).should_not.be.none
Example #37
0
    def test_play(self):
        music = Music(
            room=self.r,
            music_id='a',
            name='a',
            total_duration=200,
            duration=200,
            thumbnail='https://a.com/a.jpg',
        )
        music.save()

        self.r.play(music)

        self.r.current_music.should.eql(music)

        music.count.should.eql(1)
        music.last_play.should_not.be.none

        Events.get(self.r).should_not.be.none
Example #38
0
    def test_play_next_without_shuffle(self):
        music = Music(
            room=self.r,
            music_id='a',
            name='a',
            total_duration=200,
            duration=200,
            thumbnail='https://a.com/a.jpg',
        )
        music.save()

        PlaylistTrack(track=music, room=self.r).save()

        self.r.play_next()

        self.r.current_music.should.eql(music)

        self.r.play_next()
        # No more music in the playlist.
        self.r.current_music.should.be.none
Example #39
0
    def test_set_shuffle(self):
        self.r.set_shuffle.when.called_with(True).should.throw(Room.UnableToUpdate, "Can't activate shuffle when there is no musics.")

        music = Music(
            room=self.r,
            music_id='a',
            name='a',
            total_duration=200,
            duration=200,
            thumbnail='https://a.com/a.jpg',
        )
        music.save()

        self.r.set_shuffle(True)

        self.r.shuffle.should.be.true
        self.r.current_music.should.eql(music)

        self.r.set_shuffle(False)
        self.r.shuffle.should.be.false
Example #40
0
    def test_play_next_without_shuffle(self):
        music = Music(
            room=self.r,
            music_id='a',
            name='a',
            total_duration=200,
            duration=200,
            thumbnail='https://a.com/a.jpg',
        )
        music.save()

        PlaylistTrack(track=music, room=self.r).save()

        self.r.play_next()

        self.r.current_music.should.eql(music)

        self.r.play_next()
        # No more music in the playlist.
        self.r.current_music.should.be.none
Example #41
0
    def test_other_action(self):
        m2 = Music(
            music_id="b",
            name="b",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m2.save()

        pt2 = PlaylistTrack(track=m2, room=self.r)
        pt2.save()

        # test only one action to test the endpoint. Actions themselves are already tested in OrderedModel lib

        response = self.client.post('/playlist/%s/top' % pt2.pk)

        response.status_code.should.eql(status.HTTP_200_OK)
        list(self.r.playlist.all()).should.eql([pt2, self.pt])
Example #42
0
    def test_initialization(self):
        settings.TESTING = False

        # Create fake app to test "ready" method
        init = Init.create('player')
        init.models = {
            'room': Room
        }

        # Clean events
        Events.events = {}
        Events.get_all().should_not.have.key('a')  # Sanity check of events have been cleared

        room = Room(password='******', name='b')
        room.save()

        music = Music(
            room=room,
            music_id="a",
            name="a",
            total_duration=211,
            duration=211,
            thumbnail="https://a.com/a.jpg",
        )
        music.save()

        room.current_music = music
        room.shuffle = True
        room.save()

        init.ready()

        room = self.reload(room)
        room.current_music.should.be.none
        room.shuffle.should.be.false
        Events.get_all().should.have.key('b')
        Events.get_all().should.have.key('a')

        settings.TESTING = True
Example #43
0
    def test_set_shuffle(self):
        self.r.set_shuffle.when.called_with(True).should.throw(
            Room.UnableToUpdate,
            "Can't activate shuffle when there is no musics.")

        music = Music(
            room=self.r,
            music_id='a',
            name='a',
            total_duration=200,
            duration=200,
            thumbnail='https://a.com/a.jpg',
        )
        music.save()

        self.r.set_shuffle(True)

        self.r.shuffle.should.be.true
        self.r.current_music.should.eql(music)

        self.r.set_shuffle(False)
        self.r.shuffle.should.be.false
Example #44
0
    def test_patch(self):
        m = Music(
            music_id="a",
            name="a",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m.save()

        response = self.client.patch('/music', {'pk': m.pk, 'timer_start': 8, 'duration': 106})

        response.status_code.should.eql(status.HTTP_200_OK)
        response.data.should.have.key('timer_start').which.should.equal(8)
        response.data.should.have.key('duration').which.should.equal(106)

        m = self.reload(m)

        m.timer_start.should.eql(8)
        m.duration.should.eql(106)
Example #45
0
    def test_patch_shuffle(self):
        m = Music(
            music_id="a",
            name="a",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m.save()

        response = self.client.patch('/room', {'shuffle': True})

        response.status_code.should.eql(status.HTTP_200_OK)
        response.data['shuffle'].should.be.true
        response.data['current_music']['music_id'].should.eql('a')

        response = self.client.patch('/room', {'shuffle': False})

        response.status_code.should.eql(status.HTTP_200_OK)
        response.data['shuffle'].should.be.false
Example #46
0
    def test_patch_shuffle(self):
        m = Music(
            music_id="a",
            name="a",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m.save()

        response = self.client.patch('/room', {'shuffle': True})

        response.status_code.should.eql(status.HTTP_200_OK)
        response.data['shuffle'].should.be.true
        response.data['current_music']['music_id'].should.eql('a')

        response = self.client.patch('/room', {'shuffle': False})

        response.status_code.should.eql(status.HTTP_200_OK)
        response.data['shuffle'].should.be.false
Example #47
0
def add(request):
    if request.method == 'GET':
        singers = Singer.objects.all()
        types = Type.objects.all()
        singers_li = []
        for singer in singers:
            singers_li.append({'id': singer.id, 'name': singer.name})
        types_li = []
        for type in types:
            types_li.append({'id': type.id, 'name': type.name})

        data = {'singers': singers_li, 'types': types_li}
        return JsonResponse(data)
    else:
        name = request.POST['name']
        singers_id = request.POST.getlist('singers_id')
        # print(singers_id, '-----------')
        music = Music.objects.filter(name=name).first()

        is_exit = True
        if music is not None:
            # print(music.singers.all())
            if len(singers_id) == len(music.singers.all()):
                for singer in music.singers.all():
                    if str(singer.id) not in singers_id:
                        is_exit = False
                        break
            else:
                is_exit = False
        else:
            is_exit = False

        if is_exit is True:
            data = {'status': 'no', 'info': '添加歌曲失败,歌曲已存在'}
            return JsonResponse(data)
        else:
            type_id = request.POST['type_id']
            img = request.FILES.get('img')
            file = request.FILES.get('file')

            if img is not None:
                # print(img.name, '==============')
                img_path = MUSIC_IMG_DIR
                if not os.path.exists(img_path):
                    os.makedirs(img_path)


                with open(img_path + img.name, 'wb') as f:

                    for chunk in img.chunks():
                        f.write(chunk)

                imgPath = MUSIC_IMG_URL + img.name
            else:
                imgPath = ''
            if file is not None:

                file_path = MUSIC_FILE_DIR
                if not os.path.exists(file_path):
                    os.makedirs(file_path)
                # file_name=change_filename(file.name)
                with open(file_path + file.name, 'wb') as f:
                    for chunk in file.chunks():
                        f.write(chunk)
                filePath = MUSIC_FILE_URL + file.name
            else:
                filePath = ''
            # print(type_id)
            typeObj = get_object_or_404(Type, id=type_id)
            music = Music(name=name, img=imgPath, file=filePath, type=typeObj)
            music.save()

            for id in singers_id:
                music.singers.add(int(id))
            music.save()

            data = {'status': 'ok', 'info': '添加歌曲成功'}
            return JsonResponse(data)
Example #48
0
class TestPlaylist(EndpointTestCase):
    def setUp(self):
        super().setUp()
        self.m = Music(
            music_id="a",
            name="a",
            thumbnail="https://a.com",
            total_duration=114,
            duration=104,
            url="https://www.a.com",
            source="youtube",
            timer_start=10,
            room=self.r,
        )
        self.m.save()

        self.pt = PlaylistTrack(track=self.m, room=self.r)
        self.pt.save()

    def test_get(self):
        response = self.client.get('/playlist')

        response.status_code.should.eql(status.HTTP_200_OK)

        expected_result = [{
            'pk': self.pt.pk,
            'order': 0,
            'music': {
                'pk': self.m.pk,
                'music_id': 'a',
                'name': 'a',
                'thumbnail': 'https://a.com',
                'total_duration': 114,
                'duration': 104,
                'url': 'https://www.a.com',
                'source': 'youtube',
                'timer_start': 10,
                'count': 0,
                'last_play': None,
                'one_shot': False
            }
        }]

        list(response.data).should.eql(expected_result)

    def test_delete(self):
        response = self.client.delete('/playlist/%s' % self.pt.pk)
        response.status_code.should.eql(status.HTTP_204_NO_CONTENT)

    def test_delete_unexisting(self):
        response = self.client.delete('/playlist/1337')
        response.status_code.should.eql(status.HTTP_404_NOT_FOUND)

    def test_post_bad_pk(self):
        response = self.client.post('/playlist/1894/top')

        response.status_code.should.eql(status.HTTP_404_NOT_FOUND)
        response.data.should.eql("Can't find this playlistTrack.")

    def test_post_bad_action(self):
        response = self.client.post('/playlist/%s/badaction' % self.pt.pk)

        response.status_code.should.eql(status.HTTP_400_BAD_REQUEST)
        response.data.should.eql('Action can only be: "%s"' %
                                 '" or "'.join(PlaylistTrack.ACTIONS))

    def test_post_above_and_below_action_without_target(self):
        response = self.client.post('/playlist/%s/above' % self.pt.pk)

        response.status_code.should.eql(status.HTTP_400_BAD_REQUEST)
        response.data.should.eql('"above" action needs a target parameter')

        response = self.client.post('/playlist/%s/below' % self.pt.pk)

        response.status_code.should.eql(status.HTTP_400_BAD_REQUEST)
        response.data.should.eql('"below" action needs a target parameter')

    def test_post_above_and_below_action_with_bad_target(self):
        response = self.client.post('/playlist/%s/above/1337' % self.pt.pk)

        response.status_code.should.eql(status.HTTP_404_NOT_FOUND)
        response.data.should.eql("Can't find this playlistTrack as target.")

        response = self.client.post('/playlist/%s/below/1337' % self.pt.pk)

        response.status_code.should.eql(status.HTTP_404_NOT_FOUND)
        response.data.should.eql("Can't find this playlistTrack as target.")

    def test_post_below_or_above_action(self):
        m2 = Music(
            music_id="b",
            name="b",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m2.save()

        pt2 = PlaylistTrack(track=m2, room=self.r)
        pt2.save()

        response = self.client.post('/playlist/%s/below/%s' %
                                    (self.pt.pk, pt2.pk))

        response.status_code.should.eql(status.HTTP_200_OK)
        list(self.r.playlist.all()).should.eql([pt2, self.pt])

        response = self.client.post('/playlist/%s/above/%s' %
                                    (pt2.pk, self.pt.pk))

        response.status_code.should.eql(status.HTTP_200_OK)
        list(self.r.playlist.all()).should.eql([pt2, self.pt])

    def test_other_action(self):
        m2 = Music(
            music_id="b",
            name="b",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=self.r,
        )
        m2.save()

        pt2 = PlaylistTrack(track=m2, room=self.r)
        pt2.save()

        # test only one action to test the endpoint. Actions themselves are already tested in OrderedModel lib

        response = self.client.post('/playlist/%s/top' % pt2.pk)

        response.status_code.should.eql(status.HTTP_200_OK)
        list(self.r.playlist.all()).should.eql([pt2, self.pt])
        if name and year:
            album = Album()
            album.name = name
            album.album_date = year + '-01-01'
            album.create_date = datetime.now()
            album.slug = slugify(name)
            album.band = band
            album.user = user
            album.save()
            sys.stdout.write(name + " - " + year + "\n")
            sys.stdout.flush()
            i = 1

            for music in d['songs']:
                m_name = music
                music = Music()
                music.name = m_name
                music.slug = slugify(m_name)
                music.number = str(i)
                music.user = user
                music.date = datetime.now()
                music.album = Album.objects.latest('id')
                music.save()
                sys.stdout.write(str(i) + " - " + m_name + "\n")
                sys.stdout.flush()
                i = i + 1

            band.robot = 1
            band.save()
Example #50
0
from datetime import datetime
from django.utils import timezone
from django.utils.six import BytesIO
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from music.models import Music
from music.serializers import MusicSerializer

musicdatetime = timezone.make_aware(datetime.now(),
                                    timezone.get_current_timezone())
# music = Music(name='dh', release_date=musicdatetime, music_category='hip-hop', played=False)
# music.save()
#
# musicV2 = Music(name='tiger', release_date=musicdatetime, music_category='k-pop', played=False)
# musicV2.save()

musicV3 = Music(name='max',
                release_date=musicdatetime,
                music_category='ballad',
                played=False)
musicV3.save()

music3Serializer = MusicSerializer(musicV3)
print(music3Serializer.data)

renderer = JSONRenderer()
rendered_data1 = renderer.render(music3Serializer)
Example #51
0
    if i['genres']:
        genres = []
        for genre in i['genres']:
            genres.append(strip_unicode(genre))
        music.genre = genres
    else:
        pass

    if i['languageCodesISO2A']:
        languages = []
        for language_code in i['languageCodesISO2A']:
            languages.append(strip_unicode(language_code))
        music.languages = languages
    else:
        pass

    if i['description']:
        music.description = i['description']
    else:
        pass

    if i['advisories']:
        advisories = []
        for item in i['advisories']:
            advisories.append(strip_unicode(item))
        music.advisories = advisories
    else:
        pass

    music.save()