Beispiel #1
0
def populate_db():
    a1 = Artist(name="Billy Joel", hometown="Long Island, NY")
    a2 = Artist(name="Tash Sultana", hometown="Melbourne, Australia")
    a3 = Artist(name="Mac Miller", hometown="Pittsburgh, PA")
    a4 = Artist(name="Red Hot Chili Peppers", hometown="Los Angeles, CA")

    db.session.add_all([a1, a2, a3, a4])
    db.session.commit()

    s1 = Song(name="Zanzibar", artist=a1)
    s2 = Song(name="Mystik", artist=a2)
    s3 = Song(name="Woods", artist=a3)
    s4 = Song(name="The Longest Wave", artist=a4)

    db.session.add_all([s1, s2, s3, s4])
    db.session.commit()

    print(s1)

    p1 = Playlist(name="Rock")
    p2 = Playlist(name="Slow Jams")

    stp1 = SongToPlaylist(song=s1, playlist=p1)
    stp2 = SongToPlaylist(song=s2, playlist=p1)
    stp3 = SongToPlaylist(song=s3, playlist=p2)
    stp4 = SongToPlaylist(song=s4, playlist=p2)

    db.session.add_all([p1, p2, stp1, stp2, stp3, stp4])
    db.session.commit()

    print("Artist - Woods", s3.artist.name)
    return "Database has been populated."
Beispiel #2
0
    def add_playlist(m3u: M3UList):

        # Create Playlist obj from M3UList obj, and Insert Playlist into DB if it does not already exist

        pl = Playlist.make_playlist_obj(m3u)
        if not Playlist.db_pl_exists(pl):
            try:
                Playlist.add_playlist(pl)

            except Exception as inst:
                print(str(inst))
        else:
            print('Playlist {} already exists in DB'.format(pl.playlist_name))

        # Insert tracks from m3u into DB if they do not already exist
        addable_tracks = []
        for mt in m3u.tracks:
            dt = Track.make_Track_obj(mt)
            if not Track.db_trk_exists(dt):
                try:
                    Track.add_track(t=dt, com=False)
                    addable_tracks.append(dt)
                except Exception:
                    raise Exception('add {} track fails'.format(
                        dt.artist_title))
            else:
                print('Track {} already exists in DB'.format(dt.artist_title))
                addable_tracks.append(dt)
        db.session.commit()
        #     add tracks to db playlist
        npl = Playlist.query.filter_by(playlist_name=pl.playlist_name).first()
        for dt in addable_tracks:
            npl.add_track(dt, com=False)
        db.session.commit()
Beispiel #3
0
def load_playlist(fname):
    try:
        with open(fname + ".playlist") as f:
            playlist = Playlist()
            data = json.load(f)
            playlist.name = data['name']
            playlist.thumbnail = data['thumbnail']
            db.session.add(playlist)
            db.session.commit()
            for s in data['songs']:
                song_obj = Song.query.filter_by(
                    itunes_resource_id=s['itunes_resource_id']).first()
                if song_obj is None:
                    song_obj = Song()
                    song_obj.name = s['name']
                    song_obj.artist = s['artist']
                    song_obj.album = s['album']
                    song_obj.thumbnail_url = s['thumbnail_url']
                    song_obj.preview_url = s['preview_url']
                    song_obj.external_url = s['external_url']
                    song_obj.itunes_resource_id = s['itunes_resource_id']
                    db.session.add(song_obj)
                    db.session.commit()
                playlist.songs.append(song_obj)
                db.session.commit()
            return True
    except IOError as e:
        return False

    return False
Beispiel #4
0
    def setUp(self):
        self.username = '******'
        self.email = '*****@*****.**'
        self.password = '******'
        self.user = User.objects.create_user(username=self.username,
                                             email=self.email,
                                             password=self.password)
        self.client = Client()
        self.client.login(username=self.username, password=self.password)

        self.anonymous_client = Client()

        self.playlist = Playlist(user=self.user)
        self.playlist.save()

        self.channel = Channel.objects.create(user=self.user,
                                              title='Testing Playlist',
                                              duration='150',
                                              group='The best group',
                                              path='no path')
        self.channel.playlists.add(self.playlist)

        self.sample_m3u8 = '\n'.join([
            '#EXTM3U', '#EXTINF:0,BBC NEWS', '#EXTGRP:News',
            'http://example.com/bbc-news-tv.m3u8', '#EXTINF:0,Fox NEWS',
            '#EXTGRP:News', 'http://example.com/fox-news-tv.m3u8',
            '#EXTINF:Invalid channel',
            'http://example.com/invalid-channel.m3u8'
        ])
Beispiel #5
0
def playlist(playlist_id, spotify):
    user_id = spotify.current_user()['id']
    api_response = spotify.user_playlist(user_id, playlist_id)
    playlist = Playlist(api_response)
    form = SongSearchForm()
    return render_template('playlist.html',
        playlist=playlist,
        items=playlist.items(),
        form=form)
Beispiel #6
0
def create_playlist():
    data = request.json

    try:
        playlist = Playlist(name=data['playlistName'], user_id=data['id'])
        db.session.add(playlist)
        db.session.commit()
        return {'playlist': playlist.to_dict()}
    except AssertionError as message:
        return jsonify({"error": str(message)}), 400
Beispiel #7
0
    def test_get_playlists(self):
        '''
        Test case to check if all playlists are returned by the get_playlists function
        '''

        self.new_playlist.save_playlist()

        test_playlist = Playlist(name="The Production List")

        test_playlist.save_playlist()

        gotten_playlists = Playlist.get_playlists()

        self.assertTrue(len(gotten_playlists) == len(Playlist.query.all()))
Beispiel #8
0
    def get(self):
        global threads
        global threadid
        parser = reqparse.RequestParser()
        parser.add_argument('spotifyid',
                            type=str,
                            required=True,
                            help='spotify playlist URI')
        parser.add_argument('name',
                            type=str,
                            required=True,
                            help='name for playlist')
        parser.add_argument('auth',
                            type=str,
                            required=True,
                            help='auth token defined in ..env')
        args = parser.parse_args()
        args['spotifyid'] = args['spotifyid'].split(':')[-1]
        if args['auth'] != Config.PLAYLIST_API_SECRET:
            return {"message": "unauthorized"}, 401

        # create and populate the metadata of the new playlist
        playlist_object = Playlist()
        playlist_object.name = args['name']
        playlist_object.thumbnail = "/resource/placeholder.png"
        playlist_object.spotifyid = args['spotifyid']
        db.session.add(playlist_object)
        db.session.commit()
        # create the thread to populate it
        threadid += 1
        thread = GetSpotifyPlaylistWithITunesThread(playlist_object.id,
                                                    args['spotifyid'],
                                                    threadid,
                                                    name="Playlist-thread-%i" %
                                                    threadid)
        # add new thread to queue and start it if no threads running
        threads.append(thread)
        if not thread_running:
            threads.pop().start()
            return {
                'threadid': threadid,
                'queue_length': len(threads),
                'started': True
            }
        return {
            'threadid': threadid,
            'queue_length': len(threads),
            'started': False
        }
Beispiel #9
0
def playlist_new():
    form = NewPlaylistForm()
    if form.validate_on_submit():
         playlist = Playlist(title=form.title.data)
         db.session.add(playlist)
         db.session.commit()
         return redirect(url_for('playlist_all'))
    return render_template('playlist_new.html', form=form)
Beispiel #10
0
def rescanLibrary(request):
    if request.method == 'POST':
        response = json.loads(request.body)
        if 'LIBRARY_ID' in response:
            library = strip_tags(response['LIBRARY_ID'])
            if Library.objects.filter(id=library).count() == 1:
                library = Library.objects.get(id=library)

                # Check if the library is not used somewhere else
                if library.playlist.isScanned:
                    # Delete all the old tracks
                    library.playlist.delete()

                    # Recreating playlist
                    playlist = Playlist()
                    playlist.name = library.name
                    playlist.user = request.user
                    playlist.isLibrary = True
                    playlist.save()
                    library.playlist = playlist
                    library.save()

                    # Scan library
                    data = scanLibrary(library, playlist, library.convertID3)
                else:
                    data = errorCheckMessage(False, "rescanError")
            else:
                data = errorCheckMessage(False, "dbError")
        else:
            data = errorCheckMessage(False, "badFormat")
    else:
        data = errorCheckMessage(False, "badRequest")
    return JsonResponse(data)
Beispiel #11
0
def newLibrary(request):
    if request.method == 'POST':
        user = request.user
        if checkPermission(["LIBR"], user):
            response = json.loads(request.body)
            if 'URL' in response and 'NAME' in response:
                dirPath = response['URL']
                if os.path.isdir(dirPath):
                    # Removing / at the end of the dir path if present
                    if dirPath.endswith("/"):
                        dirPath = dirPath[:-1]
                    library = Library()
                    library.path = dirPath
                    playlist = Playlist()
                    playlist.user = user
                    playlist.isLibrary = True
                    playlist.name = strip_tags(response['NAME'])
                    playlist.save()
                    library.playlist = playlist
                    library.save()
                    data = {
                        'LIBRARY_ID': library.id,
                        'LIBRARY_NAME': library.playlist.name,
                    }
                    data = {**data, **errorCheckMessage(True, None)}
                else:
                    data = errorCheckMessage(False, "dirNotFound")
            else:
                data = errorCheckMessage(False, "badFormat")
        else:
            data = errorCheckMessage(False, "permissionError")
    else:
        data = errorCheckMessage(False, "badRequest")
    return JsonResponse(data)
Beispiel #12
0
def add_playlist_to_db(sentence, pl_tracks):
    pls = [str(track.id) for track in pl_tracks]
    ids_str = "-".join(pls)
    pl = Playlist(name=sentence.lower(),
                  url_id=str(uuid4()).replace('-', ''),
                  tracks_str=ids_str)
    db.session.add(pl)
    db.session.commit()
    return pl
Beispiel #13
0
def addToPlaylist():
    data = request.json
    playlist = Playlist(
        name=data['name'], 
        song_id=data['songId'],
        user_id=data['userId'],
        )
    db.session.add(playlist)
    db.session.commit()
    playlists = Playlist.query.filter_by(user_id=data['userId']).all()
    playlistList = []
    for playlist in playlists:
        playlist_id = playlist.id
        playlist_dict = playlist.to_dict()
        # playlist_dict['playlist_id'] = playlist_id
        playlistList.append(playlist_dict)
    
    return jsonify(playlistList)
Beispiel #14
0
def _make_db_playlist(sp_playlist):
    db_playlist = Playlist(
        id=sp_playlist['id'],
        name=sp_playlist['name'],
        description=sp_playlist['description'],
    )
    db.session.add(db_playlist)
    _add_item_tracks(db_playlist, sp_playlist['tracks'])
    return db_playlist
Beispiel #15
0
def Make_playlist():
    data = request.json
    print(data)
    p = Playlist(title=data['title'],
                 desc=data['desc'],
                 account_id=current_user.id)
    db.session.add(p)
    db.session.commit()
    flash('Playlist Created')
    return str(p.id)
Beispiel #16
0
def addPlaylist():
    data = request.json
    # form = PlaylistForm()
    # form['csrf_token'].data = request.cookies['csrf_token']
    playlist = Playlist(
        name=data['name'], 
        user_id=data['userId'],
        song_id=None,
        )
    db.session.add(playlist)
    db.session.commit()
    playlists = Playlist.query.filter_by(user_id=data['userId']).all()
    playlistList = []
    for playlist in playlists:
        playlist_id = playlist.id
        playlist_dict = playlist.to_dict()
        # playlist_dict['playlist_id'] = playlist_id
        playlistList.append(playlist_dict)
    
    return jsonify(playlistList)
    def __init__(self, festival, year, bands):
        self.festival = festival
        self.year = year
        self.bands = bands

        self.playlist_storage = Playlist(name=self.festival, year=int(year), bands=", ".join(self.bands))
        db.session.add(self.playlist_storage)

        for band in self.bands:
            self.process_band(band, year)

        db.session.commit()
Beispiel #18
0
def create_playlist():
    form = PlaylistForm()

    # if form was submitted and contained no errors
    if form.validate_on_submit():
        new_playlist = Playlist(name=form.name.data,
                                songs_in_playlist=form.songs_in_playlist.data)
        db.session.add(new_playlist)
        db.session.commit()

        flash('New playlist was created successfully.')
        return redirect(url_for('main.homepage', playlist_id=new_playlist.id))
    return render_template('create_playlist.html', form=form)
Beispiel #19
0
class PlaylistTest(unittest.TestCase):
    '''
    Test class to test behaviours of the Playlist class

    Args:
        unittest.TestCase : Test case class that helps create test cases
    '''
    def setUp(self):
        '''
        Set up method that will run before every Test
        '''
        self.new_playlist = Playlist(name='The Banana List')

    def test_instance(self):
        '''
        Test case to check if new_playlist is an instance of Playlist
        '''
        self.assertTrue(isinstance(self.new_playlist, Playlist))

    def test_save_playlist(self):
        '''
        Test case to check if a playlist is saved to the databse
        '''

        self.new_playlist.save_playlist()

        self.assertTrue(len(Playlist.query.all()) > 0)

    def test_get_playlists(self):
        '''
        Test case to check if all playlists are returned by the get_playlists function
        '''

        self.new_playlist.save_playlist()

        test_playlist = Playlist(name="The Production List")

        test_playlist.save_playlist()

        gotten_playlists = Playlist.get_playlists()

        self.assertTrue(len(gotten_playlists) == len(Playlist.query.all()))

    def test_delete_playlist(self):
        '''
        Test case to check if test_playlist is deleted from the database
        '''

        self.new_playlist.save_playlist()

        test_playlist = Playlist(name="The Bose List")

        test_playlist.save_playlist()

        test_playlist.delete_playlist(test_playlist.id)

        gotten_playlists = Playlist.get_playlists()

        self.assertTrue(len(gotten_playlists) == len(Playlist.query.all()))
Beispiel #20
0
    def test_delete_playlist(self):
        '''
        Test case to check if test_playlist is deleted from the database
        '''

        self.new_playlist.save_playlist()

        test_playlist = Playlist(name="The Bose List")

        test_playlist.save_playlist()

        test_playlist.delete_playlist(test_playlist.id)

        gotten_playlists = Playlist.get_playlists()

        self.assertTrue(len(gotten_playlists) == len(Playlist.query.all()))
Beispiel #21
0
def player():
    video_id = request.args.get('id', None)
    vid_title = request.args.get('title', None)
    if not video_id:
        return "Peak", 500
    url = request.args.get('url', None)
    results = search_results(vid_title, video_id, url)
    form = MakePlaylistForm()
    if form.validate_on_submit():
        s = Song(title=vid_title, youtube_id=video_id)
        p = Playlist(name=form.playlist_name.data)
        p.songs.append(s)
        current_user.playlists.append(p)
        db.session.add(s)
        db.session.add(p)
        db.session.commit()
        return redirect(url_for('main.index'))
    return render_template("song_player.html", results=results, form=form)
Beispiel #22
0
def new_playlist():
    form = MakePlaylistForm()
    video_id = request.args.get('id', None)
    vid_title = request.args.get('title', None)
    url = request.args.get('url', None)
    print('res', video_id, vid_title, url)
    if form.validate_on_submit():
        s = Song(title=vid_title, youtube_id=video_id)
        p = Playlist(name=form.playlist_name.data)
        p.songs.append(s)
        current_user.playlists.append(p)
        db.session.add(s)
        db.session.add(p)
        db.session.commit()
        return redirect(url_for('main.index'))
    return render_template("new_playlist.html",
                           form=form,
                           video_id=video_id,
                           vid_title=vid_title,
                           url=url)
Beispiel #23
0
def newLibrary(request):
    if request.method == 'POST':
        user = request.user
        if checkPermission(["LIBR"], user):
            response = json.loads(request.body)
            if 'URL' in response and 'NAME' in response:
                dirPath = response['URL']
                if os.path.isdir(dirPath):
                    # Removing / at the end of the dir path if present
                    if dirPath.endswith("/"):
                        dirPath = dirPath[:-1]
                    library = Library()
                    library.path = dirPath
                    playlist = Playlist()
                    playlist.user = user
                    playlist.isLibrary = True
                    playlist.name = strip_tags(response['NAME'])
                    playlist.save()
                    library.playlist = playlist
                    library.save()
                    data = {
                        'INFO': {
                            'ID': library.id,
                            'NAME': library.playlist.name,
                            'DESCRIPTION': library.playlist.description,
                            'IS_PUBLIC': library.playlist.isPublic,
                            'IS_LIBRARY': library.playlist.isLibrary,
                            'TOTAL_TRACK': "TO BE IMPLEMENTED",
                            'TOTAL_DURATION': "TO BE IMPLEMENTED",
                            'AVERAGE_BITRATE': "TO BE IMPLEMENTED",
                            'OWNER': library.playlist.user.username
                        }
                    }
                    data = {**data, **errorCheckMessage(True, None, newLibrary)}
                else:
                    data = errorCheckMessage(False, ErrorEnum.DIR_NOT_FOUND, newLibrary)
            else:
                data = errorCheckMessage(False, ErrorEnum.BAD_FORMAT, newLibrary, user)
        else:
            data = errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR, newLibrary, user)
    else:
        data = errorCheckMessage(False, ErrorEnum.BAD_REQUEST, newLibrary)
    return JsonResponse(data)
Beispiel #24
0
def get_all_playlists():
    auth_header = _auth_header(_get_access_token())
    payload = {'limit': '50', 'offset': 0}
    response = requests.get("https://api.spotify.com/v1/me/playlists",
                            headers=auth_header,
                            params=payload)
    playlists_info = response.json()
    has_next = True
    playlists_in_db = Playlist.query.filter_by(user_id=g.current_user.id).all()

    for playlist in playlists_in_db:
        playlist.deleted = True

    while has_next:
        for item in playlists_info['items']:
            playlist_id = item['id']
            playlist_name = item['name']
            current_playlist = Playlist.query.filter_by(
                user_id=g.current_user.id, playlist_id=playlist_id).first()
            if current_playlist is None:
                new_playlist = Playlist(playlist_id=playlist_id,
                                        name=playlist_name,
                                        user_id=g.current_user.id,
                                        deleted=False)
                db.session.add(new_playlist)
            else:
                current_playlist.name = playlist_name
                current_playlist.deleted = False
        if playlists_info['next'] is not None:
            response = requests.get(playlists_info['next'],
                                    headers=auth_header)
            playlists_info = response.json()
        else:
            has_next = False

    db.session.commit()
    for playlist in playlists_in_db:
        if playlist.deleted is True:
            db.session.delete(playlist)
    db.session.commit()
Beispiel #25
0
def initialScan(request):
    print("Asked for initial scan")
    if request.method == 'POST':
        response = json.loads(request.body)
        if 'LIBRARY_ID' in response:
            library = Library.objects.get(id=response['LIBRARY_ID'])
            if os.path.isdir(library.path):
                playlist = Playlist()
                playlist.name = library.name
                playlist.user = request.user
                playlist.isLibrary = True
                playlist.save()
                data = scanLibrary(library, playlist, library.convertID3)
            else:
                data = errorCheckMessage(False, "dirNotFound")
        else:
            data = errorCheckMessage(False, "badFormat")
    else:
        data = errorCheckMessage(False, "badRequest")
    return JsonResponse(data)
Beispiel #26
0
def newPlaylist(request):
    if request.method == 'POST':
        response = json.loads(request.body)
        if 'NAME' in response:
            playlist = Playlist()
            playlist.name = strip_tags(response['NAME'])
            playlist.user = request.user
            playlist.save()
            data = {
                'PLAYLIST_ID': playlist.id,
                'NAME': playlist.name,
            }
            data = {**data, **errorCheckMessage(True, None)}
        else:
            data = errorCheckMessage(False, "badFormat")
    else:
        data = errorCheckMessage(False, "badRequest")
    return JsonResponse(data)
Beispiel #27
0
def newPlaylist(request):
    if request.method == 'POST':
        response = json.loads(request.body)
        user = request.user
        if checkPermission(["PLST"], user):
            if 'PLAYLIST_NAME' in response:
                playlist = Playlist()
                playlist.name = strip_tags(response['PLAYLIST_NAME'])
                playlist.user = request.user
                playlist.save()
                data = {
                    'PLAYLIST_ID': playlist.id,
                    'PLAYLIST_NAME': playlist.name,
                }
                data = {**data, **errorCheckMessage(True, None, newPlaylist)}
            else:
                data = errorCheckMessage(False, ErrorEnum.BAD_FORMAT, newPlaylist, user)
        else:
            data = errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR, newPlaylist, user)
    else:
        data = errorCheckMessage(False, ErrorEnum.BAD_REQUEST, newPlaylist)
    return JsonResponse(data)
Beispiel #28
0
class AppTestCase(TestCase):
    @classmethod
    def setUpClass(cls):
        super(AppTestCase, cls).setUpClass()

        logging.disable(logging.CRITICAL)

    def setUp(self):
        self.username = '******'
        self.email = '*****@*****.**'
        self.password = '******'
        self.user = User.objects.create_user(username=self.username,
                                             email=self.email,
                                             password=self.password)
        self.client = Client()
        self.client.login(username=self.username, password=self.password)

        self.anonymous_client = Client()

        self.playlist = Playlist(user=self.user)
        self.playlist.save()

        self.channel = Channel.objects.create(user=self.user,
                                              title='Testing Playlist',
                                              duration='150',
                                              group='The best group',
                                              path='no path')
        self.channel.playlists.add(self.playlist)

        self.sample_m3u8 = '\n'.join([
            '#EXTM3U', '#EXTINF:0,BBC NEWS', '#EXTGRP:News',
            'http://example.com/bbc-news-tv.m3u8', '#EXTINF:0,Fox NEWS',
            '#EXTGRP:News', 'http://example.com/fox-news-tv.m3u8',
            '#EXTINF:Invalid channel',
            'http://example.com/invalid-channel.m3u8'
        ])

    def test_urls(self):
        urls = [
            'index', 'create-playlist', 'new-channel', 'channels', 'login',
            'logout'
        ]

        social_auth_redirect_urls = [
            '/login/facebook/',
            '/login/vk-oauth2/',
        ]

        for url in urls:
            response = self.client.get(reverse(url), follow=True)
            self.assertEqual(response.status_code,
                             200,
                             msg='Unable to open: %s' % url)

        for url in social_auth_redirect_urls:
            response = self.client.get(url)
            self.assertEqual(response.status_code,
                             302,
                             msg='Unable to open: %s' % url)

    def test_playlist(self):
        self.assertGreater(self.playlist.count, 0)

    def test_playlist_public_link(self):
        self.assertIsNotNone(self.playlist.public_link)

        response = self.client.get(self.playlist.public_link)
        self.assertEqual(response.status_code, 200)

    def test_channel_link(self):
        self.assertIsNotNone(self.channel.get_absolute_url())

    def test_channel_update(self):
        response = self.client.get(self.channel.get_absolute_url())
        self.assertEqual(response.status_code, 200)

        response = self.anonymous_client.get(self.channel.get_absolute_url())
        self.assertEqual(response.status_code, 302)
        self.assertIn('login',
                      response.url,
                      msg='Not redirected to login view')

    def test_load_from_file(self):
        m3u8_file = SimpleUploadedFile("playlist.m3u8",
                                       str.encode(self.sample_m3u8),
                                       content_type='application/x-mpegURL')
        load_m3u8_from_file(m3u8_file, self.playlist, remove_existed=True)

        self.assertEqual(self.playlist.count, 2)

    @requests_mock.mock()
    def test_load_remote_m3u8(self, m):

        mocked_path = 'http://example.com/playlist.m3u8'
        m.get(mocked_path, text=self.sample_m3u8)

        load_remote_m3u8(mocked_path, self.playlist, remove_existed=True)

        self.assertEqual(self.playlist.count, 2)

    def test_simple_extinf(self):
        channel_string = '#EXTINF:-1,RTV 4 HD'
        chf = M3U8ChannelFactory()
        chf.process_line(channel_string)
        self.assertEqual('-1', chf.duration)
        self.assertEqual('RTV 4 HD', chf.title)

    def test_bytestring_extinf(self):
        channel_string = b'#EXTINF:-1 tvg-id="Omreop Fryslan NL" tvg-name="Omrop Fryslan NL" ' \
                         b'tvg-logo="http://1.1.1.1/picons/omropfryslannl.png" ' \
                         b'group-title="Netherland",Omrop Fryslan NL'
        chf = M3U8ChannelFactory()
        chf.process_line(channel_string)
        self.assertEqual('-1', chf.duration)
        self.assertEqual('Netherland', chf.extra_data.get('group-title'))
        self.assertEqual('Omreop Fryslan NL', chf.extra_data.get('tvg-ID'))
        self.assertEqual('Omrop Fryslan NL', chf.extra_data.get('tvg-name'))
        self.assertEqual('http://1.1.1.1/picons/omropfryslannl.png',
                         chf.extra_data.get('tvg-logo'))

    def test_simple_extinf_without_title(self):
        channel_string = '#EXTINF:25,'
        chf = M3U8ChannelFactory()
        chf.process_line(channel_string)
        self.assertEqual('25', chf.duration)
        self.assertEqual('', chf.title)

    def test_complex_extinf(self):
        channel_string = '#EXTINF:-1 ' \
                         'tvg-id="12" ' \
                         'tvg-name="Cinema Pro ARB" ' \
                         'tvg-logo="http://m3u8.pzbz.ru/logo.png" ' \
                         'group-title="Arab Countries",Cinema Pro ARB'
        chf = M3U8ChannelFactory()
        chf.process_line(channel_string)
        self.assertEqual(
            '-1',
            chf.duration,
        )
        self.assertEqual(
            'Cinema Pro ARB',
            chf.title,
        )
        self.assertEqual('12', chf.extra_data['tvg-ID'])
        self.assertEqual('Cinema Pro ARB', chf.extra_data['tvg-name'])
        self.assertEqual('http://m3u8.pzbz.ru/logo.png',
                         chf.extra_data['tvg-logo'])
        self.assertEqual('Arab Countries', chf.extra_data['group-title'])

    def test_bad_extinf(self):
        channel_string = '#EXTINF:Cool, but no duration'
        chf = M3U8ChannelFactory()
        chf.process_line(channel_string)

        self.assertFalse(chf.is_complete())

    def test_url_replace_tags(self):

        factory = RequestFactory()
        request = factory.get('/list/?q=HD&page=2')
        res_url_query = QueryDict(url_replace(request, 'page', 3))

        self.assertEqual({'q': 'HD', 'page': '3'}, res_url_query.dict())

        request = factory.get('/list')
        res_url = url_replace(request, 'page', 3)

        self.assertEqual('page=3', res_url)
Beispiel #29
0
def get_playlist():
    with app.app_context():
        headers = {
            'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36',
        }

        url = 'https://www.kuwo.cn/api/pc/classify/playlist/getRcmPlayList'
        order = random.choice(['hot', 'new'])
        params = {
            'pn': 1,
            'rn': 10,
            'order': order,  # new/hot 最新/最热
            'httpsStatus': 1,
        }
        res = requests.get(url=url, headers=headers, params=params)

        if res.status_code == 200:
            page_text = res.json()
            playlist_ids = jsonpath(page_text, '$..id')
            for i in playlist_ids:
                pid = i
                detail_url = 'https://www.kuwo.cn/playlist_detail/' + i
                res = requests.get(url=detail_url, headers=headers)
                if res.status_code == 200:
                    detail_page = res.text
                    tree = etree.HTML(detail_page)
                    title = tree.xpath(
                        '//*[@id="__layout"]/div/div[2]/div/div[1]/div[2]/div[1]/p[1]/text()'
                    )[0]
                    info = tree.xpath(
                        '//*[@id="__layout"]/div/div[2]/div/div[1]/div[1]/p[2]/text()'
                    )[0]
                    # print(title, info)
                    slist = tree.xpath(
                        '//*[@id="__layout"]/div/div[2]/div/div[1]/div[2]/div[1]/div[2]/div[1]/ul/li'
                    )

                    # cover = tree.xpath('//*[@id="__layout"]/div/div[2]/div/div[1]/div[1]/div[1]/img/@src')[0] #无效图片

                    script = re.findall('data:(\[.*?\]),fetch:',
                                        detail_page)[0]
                    rids = re.findall(r'rid:(\d+)', script)
                    cover = re.search('img700.*?"(.*?)",', detail_page).group(
                        1).encode('utf-8').decode("unicode_escape")
                    song_num = len(rids)
                    try:
                        playlist = Playlist(
                            name=title,
                            info=info,
                            pid=pid,
                            cover=cover,
                        )
                        # playlist = Playlist.query.filter_by(pid=pid).first()
                        # playlist.cover = cover
                        db.session.add(playlist)
                        db.session.commit()
                        print(title, '歌单添加成功')
                    except Exception as e:
                        # print(e)
                        print(title, '添加失败')
                        db.session.rollback()
                    else:
                        for i in range(song_num):
                            rid = rids[i]
                            name = slist[i].xpath('./div[2]/a/text()')[0]
                            artist = slist[i].xpath('./div[3]//text()')[0]
                            timelength = slist[i].xpath('./div[5]//text()')[0]
                            # print(name, artist, timelength, rid)
                            try:
                                music = Music(
                                    name=name,
                                    artist=artist,
                                    time_length=timelength,
                                    rid=rid,
                                    playlist=Playlist.query.filter_by(
                                        pid=pid).first())
                                db.session.add(music)
                                db.session.commit()
                                print(name, '添加成功')
                            except Exception as e:
                                # print(e)
                                print(name, '添加歌曲失败')
                                db.session.rollback()

                else:
                    print('获取歌单详情页失败')
                time.sleep(3)
        else:
            print('获取歌单列表失败')
Beispiel #30
0
def playlist_play_all():
    playlist = Playlist.all()
    print(playlist)
    return render_template('playlist_play.html', playlist=playlist)