Example #1
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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
0
    def get_new_music(self):
        music = Music(name='Test',
                      album=self.album,
                      order=1,
                      file=self._get_mp3())

        music.save()
        return music
Example #8
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 #10
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 #11
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 #12
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 #13
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 #14
0
    def getNextSong(self):
        try:
            song, request = Music.next_song_and_request()
            # file is gone, delete it and move on to the next one
            fileName = song.filename
            if not os.path.exists(fileName):
                song.delete()
                return self.getNextSong()
            if request:
                request.fulfilled = True
                request.save()
            Music.objects.filter(playing=True).update(playing=False)
            song.playing = True
            song.save()
            print("Next song to play: %s" % fileName)
            self.fd = open(fileName, 'rb')
            self.file_size = os.path.getsize(fileName)
            # if there is valid ID3 data, read it out of the file first,
            # so we can skip sending it to the client
            try:
                self.id3 = id3reader.Reader(self.fd)
                if isinstance(self.id3.header.size, int) and self.id3.header.size < self.file_size: # read out the id3 data
                    self.fd.seek(self.id3.header.size + 1, os.SEEK_SET)
            except id3reader.Id3Error:
                self.id3 = None

        except StopIteration:
            fileName = None
            self.fd = None
        except IOError:
            self.fd = None
Example #15
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 #16
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 #17
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 #18
0
    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()
Example #19
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 #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_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 #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_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 #24
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 #25
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 #26
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 #27
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 #28
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 #29
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 #30
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 #31
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 #32
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 #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_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 #35
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 #36
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 #37
0
    def test_get(self):

        # Create a classic music that should be sent by /musics
        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,
        ).save()

        # Create new room and a new music that should not be sent by /musics
        r2 = Room(name='b', password='******')
        r2.save()
        Music(
            music_id="a",
            name="a",
            thumbnail="https://a.com",
            total_duration=114,
            duration=114,
            url="https://www.a.com",
            source="youtube",
            room=r2,
        ).save()

        response = self.client.get('/musics')

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

        response.data.should.have.key('count')
        response.data.should.have.key('next')
        response.data.should.have.key('previous')
        response.data.should.have.key('results')
        response.data['results'].should.be.a(list)
        response.data['results'].should.have.length_of(1)

        self.assertResponseEqualsMusic(
            response.data['results'][0],
            Music.objects.get(music_id='a', room=self.r))
Example #38
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 #39
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 #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 current(request):
    playing = Music.currently_playing()
    data = {}
    if playing:
        data['artist'] = playing.artist
        data['title'] = playing.title
        if playing.associated_request is not None:
            data['requested_by'] = playing.associated_request.requester.username
        else:
            data['requested_by'] = "Random Play"

    return HttpResponse(json.dumps(data), content_type='application/json')
Example #42
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 #43
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 #44
0
def settings_for_view(context):
    return {'SITE_NAME': get_setting('site_name'),
            'SITE_TITLE': get_setting('site_title'),
            'ENABLE_MUSIC': get_setting('enable_music'),
            'ENABLE_BENCHMARKS': get_setting('enable_benchmarks'),
            'ENABLE_GALLERY': get_setting('enable_gallery'),
            'ENABLE_TOURNAMENTS': get_setting('enable_tournaments'),
            'ENABLE_SERVERS': get_setting('enable_servers'),
            'ENABLE_NOMS': get_setting('enable_noms'),
            'THUMB_X': settings.THUMBNAIL_SIZE[0],
            'THUMB_Y': settings.THUMBNAIL_SIZE[1],
            'MUSIC_PLAYING': Music.currently_playing()
    }
Example #45
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 #46
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 #47
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 #48
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 #49
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 #50
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 #51
0
def get_notices(request):
    notices = []
    # upcoming tournament notices
    if get_setting('enable_tournaments') == '1':
        upcoming = Tournament.objects.filter(starts__lte=(datetime.now() + timedelta(hours=1)))
        if upcoming.count() == 1:
            notices.append("The tournament %s is starting within the hour" % upcoming[0].name)
        elif upcoming.count() > 1:
            notices.append("%d tournaments are starting within the hour" % upcoming.count())
    # get admin notices
    if request.user.is_admin:
        # servers needing approval
        servers_unapproved = Server.objects.filter(mod_approved=False)
        if servers_unapproved.count() is not 0:
            notices.append("%d servers require admin approval." % servers_unapproved.count())
        # jukebox is not running
        if get_setting('enable_music') == '1' and Music.currently_playing() is None:
            notices.append("No music is currently playing!")
    # and return the lot of them
    return HttpResponse(json.dumps(notices), content_type='application/json')
        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 #53
0
from music.models import Music
from urllib2 import urlopen
import json
from utils import *

url = 'https://itunes.apple.com/lookup?id=284910350'
response = urlopen(url)
json_obj = json.load(response)

print json_obj

print '##########################'
print 'debugging'

for i in json_obj['results']:
    music = Music()
    if i['screenshotUrls']:
        app_url = []
        for url in i['screenshotUrls']:
            app_url.append(strip_unicode(url))
        music.app_url = app_url
    else:
        pass

    print i['trackName']
    if i['trackName']:
        music.app_name = i['trackName']
    else:
        pass

    if i['genres']:
Example #54
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])
Example #55
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 #56
0
def stream(request):
    if Music.currently_playing() is not None:
        warning(request, "Only one Shoutcast stream may be active at any time")
        return HttpResponseRedirect("/")
    response = HttpResponse(ShoutCastStream(request))
    return response