def test_getPlaylistNameAsByteArray(self): playlist = Playlist("bla") (header, data) = playlist.asByteArray(16) self.assertEqual(len(data), 1, "Should contain one byte array") row = data[0] self.assertEqual(len(row), 16, "complete row should be written")
def __init__(self, appSettings): self.baseUrl = "https://api.spotify.com/v1/" self.appSettings = appSettings existingTracks = self.getExisitingTracks() self.playlist = Playlist(existingTracks)
def get_tracks(playlist_id, offset): tracks = [] for i in range(offset): track_id = get_song_set(playlist_id, i * 100) playlist = Playlist(playlist_id, track_id) tracks += playlist.set_tracks(i * 100) return tracks
class AmarokEventHandler: def __init__(self, state): self.__running = True; self.__playlist = Playlist() self.__state = state dcop = Dcop.init() dcop.player.enableRandomMode("false") def start(self): while self.__running: delay = 1 fd = sys.stdin.fileno() (r,w,e) = select.select( [fd], [], [], delay) for File in r: if File == fd: line = os.read(fd, 1024) self.__dispatch(line) def stop(self): self.__running = False def __dispatch(self, s): Debug.log("Event received: " + s) if s.find("engineStateChange: empty" ) >= 0: Debug.log("Playlist is empty!") if self.__state.isRunning(): Debug.log("Queuing random song") self.__playlist.playRandom() else: Debug.log("Not running") elif s.find("trackChange" ) >= 0: if not self.__playlist.isPlaying(): Debug.log("Queuing random song") self.__playlist.playRandom()
def get_playlist_information(self, playlist_id, ordered_by, ascending): cursor = self.con.cursor() query = '''SELECT playlistName, playlistDescription FROM Playlist WHERE playlistID = ?''' cursor.execute(query, (playlist_id, )) self.con.commit() playlist_info = cursor.fetchall() playlist = Playlist(*playlist_info[0]) query = '''SELECT PlaylistContainsSong.songURL, albumTitle, Song.bandName, featured_artist, songName, songRelease, songLyrics, songLength, songGenre FROM PlaylistContainsSong INNER JOIN Song ON Song.songURL = PlaylistContainsSong.songURL INNER JOIN Album ON Album.albumID = Song.albumID INNER JOIN SongGenres ON SongGenres.songURL = Song.songURL WHERE playlistID = ? ORDER BY ''' + ordered_by + ''' ''' + ascending cursor.execute(query, (playlist_id, )) old_songs_list = cursor.fetchall() for item in old_songs_list: song = Song(*item) playlist.add_song(song) return playlist
def setUp(self): self.code_songs = Playlist(name="Code", repeat=True, shuffle=True) self.song = Song(title="Odin", artist="Manowar", album="The Sons of Odin", length="3:44") self.code_songs.add_song(self.song)
def run(): ''' Starts the app ''' global CONF, PL if len(argv) > 1: if argv[1] == '-h' or argv[1] == '--help': showHelp() elif argv[1] == '-v' or argv[1] == '--version': printexit(VERSION) else: showHelp() if os.path.isfile('config.json'): readConfig() if os.path.isfile('playlist.json'): PL = Playlist('playlist.json') else: PL = Playlist(CONF['url']) else: url = getin('You are creating a new project. Give URL of the playlist') PL = Playlist(url) CONF = { 'output_format': '', 'start': 1, 'end': len(PL.res), 'download': { 'resolution': 720, 'video_format': '', 'bitrate': 0, 'audio_format': '', 'more_options': '-o "%(title)s.%(ext)s"' }, 'url': url } saveConfig() print() confirm = input('Config saved as config.json. Edit it if you please. Then press ENTER ') readConfig() # CONFIG read/create done. Now downloading while CONF['start'] <= CONF['end']: retcode = PL.download( CONF['start'], **{ 'res': CONF['download']['resolution'], 'bitrate': CONF['download']['bitrate'], 'vext': CONF['download']['video_format'], 'aext': CONF['download']['audio_format'], 'oext': CONF['output_format'], 'more': CONF['download']['more_options'] } ) if retcode != 0: # if failed, try again continue CONF['start']+=1 saveConfig()
def setUp(self): self.playlist = Playlist("random") song1 = Song( "We Are!", "Hiroshi Kitadani", "One Piece OST", 5, 240, 512) song2 = Song( "We Are!", "Hiroshi Kitadani", "One Piece OST", 5, 240, 512) self.playlist.add_song(song1) self.playlist.add_song(song2)
def add(self, ref, extra=None, isBatch=False): data = extra if extra is None or extra.get(eMediaDatabase.FIELD_FILE_ID, 0) <= 0: data = self.getDetailsByRef(ref) or data if data is None: path, filename = os_path.split(ref.getPath()) data = { "file_uri" : ref.getPath(), "title" : filename, } Playlist.add(self, ref, data, isBatch)
def open(path): tree = ET.parse(path) root = tree.getroot() playlist = Playlist([]) for child in root: if os.path.exists(child.text): playlist.add_track(child.text) return playlist
def generate_playlist(self): returnPl = Playlist() for file in os.listdir(self._dirpath): if file.endswith(".mp3"): song = MP3(file, ID3=EasyID3) #print(song["title"][0].decode("utf-8")) returnPl.add_song(Song(song["title"][0], song["artist"][0], song["album"][0], str(datetime.timedelta(seconds=int(song.info.length))))) return returnPl
def generate_playlist(self, name): output_playlist = Playlist(name) files = self._get_mp3_files(self.__crawlDir) for filename in files: filename = self.__crawlDir + filename audio_obj = MP3(filename) song = self._create_song(audio_obj) output_playlist.add_song(song) return output_playlist
def newPlaylist(self, name: str = None, songs: list = None): newPlaylist = Playlist(name) if (songs != None): for s in songs: newPlaylist.addAudio(s) self._playlists.append(newPlaylist) print("DEBUG: playlist created:" + newPlaylist.name)
def __dispatch(self, s): if s.find("engineStateChange: empty" ) >= 0: if self.__state.isRunning(): sys.stderr.write("Unknown notification: " + s + " -> ignoring\n") self.__player.playRandom() elif s.find("trackChange" ) >= 0: pl = Playlist() if not pl.isPlaying(): self.__player.playRandom() else: sys.stderr.write("Unknown notification: " + s + " -> ignoring\n")
def __init__(self): self.Playlist = Playlist() self.name = '' self.playlistPosition = 0 self.showTimeOffset = 0 self.lastAccessTime = 0 self.totalTimePlayed = 0 self.fileName = '' self.isPaused = False self.isValid = False self.mode = 0
def test_dataArry_to_playlist(self): data = [] data.append([ 67, 97, 114, 100, 105, 111, 32, 40, 98, 121, 32, 115, 112, 111, 116, 105 ]) data.append([102, 121, 41, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) playlist = Playlist("") playlist.setData([], data) self.assertEqual("Cardio (by spotify)", playlist.name, "Plaulist should be the original one")
def main(): stdin = os.popen("kdialog --getsaveurl %s"%(user.home)) dest = stdin.readline().strip()[5:] plist = Playlist() print dest try: f = open(dest, "w") f.write(plist.toHtml()) f.close() os.system("kdialog --msgbox 'Amarok-playlist saved to %s'"%(dest)) except IOError: os.system('kdialog --error "Sorry, could not save the playlist to %s"'%(dest))
def __init__(self, id, name=_("Default"), type=MediaCore.TYPE_AUDIO, enableWrapAround=True, entryHelper=DatabasePlaylistEntry): Playlist.__init__(self, name, type, enableWrapAround=enableWrapAround, entryHelper=entryHelper) self._id = id
def main(): stdin = os.popen("kdialog --getsaveurl %s"%(user.home)) dest = stdin.readline().strip()[5:] plist = Playlist() print dest try: f = open(dest, "w") f.write(plist.toHtml()) f.close() os.system("kdialog --msgbox 'Pana-playlist saved to %s'"%(dest)) except IOError: os.system('kdialog --error "Sorry, could not save the playlist to %s"'%(dest))
def generate_playlist(self): code_songs = Playlist(name="Code", repeat=True, shuffle=False) for music_file in self.files_in_dir: audio = MP3(self.path + music_file, ID3=EasyID3) artist = audio['artist'][0] title = audio['title'][0] album = audio['album'][0] length = str(datetime.timedelta(seconds=int(audio.info.length))) new_song = Song( title=title, artist=artist, album=album, length=length) new_song.path = self.path + music_file code_songs.add_song(new_song) return code_songs
def __dispatch(self, s): Debug.log("Event received: " + s) if s.find("engineStateChange: empty" ) >= 0: Debug.log("Playlist is empty!") if self.__state.isRunning(): Debug.log("Queuing random song") self.__player.playRandom() else: Debug.log("Not running") elif s.find("trackChange" ) >= 0: pl = Playlist() if not pl.isPlaying(): self.__player.playRandom()
def writeToCard(reader): print("File found" + WRITE_CARD_FILE) config = configparser.RawConfigParser() config.read(WRITE_CARD_FILE) playlist = Playlist(config.get('Card', 'playlist')) random = config.get('Card', 'random') print("Playlist name is " + str(playlist)) writeData = [ int("0x13", 0), int("0x37", 0), int("0xb3", 0), int("0x47", 0) ] writeData.append(2) # Version 2 writeData.append(0) # For version it was the folder if (random.lower() in ['true', '1', 't', 'y', 'yes']): writeData.append(1) # Random value else: writeData.append(0) # Fill the data with 0x00 for x in range(len(writeData), 16): writeData.append(0) print("Sector 4 will now be filled with HeaderData. Length = " + str(len(writeData)) + " Data: " + str(writeData)) # Write the data reader.MFRC522_Write(4, writeData) (header, playlistData) = playlist.asByteArray(16) print("The playlistname " + str(playlist) + " has a length of " + str(len(playlist))) print("Will write " + str(len(playlistData)) + " data blocks to card") dataBlockIdx = 5 for block in playlistData: print("Sector " + str(dataBlockIdx) + " will now be filled with data: " + str(block)) reader.MFRC522_Write(dataBlockIdx, block) dataBlockIdx += 1 if (dataBlockIdx > 6 or dataBlockIdx % 4 == 3): break os.remove(WRITE_CARD_FILE)
class Playlisttest(unittest.TestCase): def setUp(self): self.playlist = Playlist("random") song1 = Song( "We Are!", "Hiroshi Kitadani", "One Piece OST", 5, 240, 512) song2 = Song( "We Are!", "Hiroshi Kitadani", "One Piece OST", 5, 240, 512) self.playlist.add_song(song1) self.playlist.add_song(song2) def test_save(self): #self.playlist.save("jason.txt") print(self.playlist.__dict__)
def __init__(self): self.Playlist = Playlist() self.name = '' self.playlistPosition = 0 self.showTimeOffset = 0 self.lastAccessTime = 0 self.totalTimePlayed = 0 self.fileName = '' self.isPaused = False self.isValid = False self.isRandom = False self.mode = 0 self.ruleList = [] self.channelNumber = 0 self.isSetup = False
def __init__(self, args): QApplication.__init__(self, args) debug("Started.") self.readSettings() self.t = threading.Thread(target=self.readStdin) self.t.start() RequestHandler.PLIST = Playlist() p_incr = 0 while p_incr < 10: try: p_i = p_incr + Globals.PORT self.srv = BaseHTTPServer.HTTPServer( ('', p_i), RequestHandler.RequestHandler) publisher.port = p_i break except socket.error: p_incr += 1 self.zeroconfPublishing() self.snsrv = QSocketNotifier(self.srv.fileno(), QSocketNotifier.Read) self.snsrv.connect(self.snsrv, SIGNAL('activated(int)'), self.readSocket)
def get_playlists(spotify): username = input('Enter username: '******'list-all' to list all of your playlists:""" ) if entered_playlists == 'list-all': print(f'Showing playlists for {username}:') for i, p in enumerate(user_playlists['items']): print(p['name']) else: entered_playlists = [ s.strip() for s in entered_playlists.split(',') ] playlists = [] playlists = [ Playlist(p['id'], p['name'], []) for p in user_playlists['items'] if p['name'] in entered_playlists ] playlists = append_track_data(username, playlists, spotify) return username, playlists
def get_playlist(self, playlist_url, sort_popularity=False, gmusic=None, strict=False, collect_skipped=False): if collect_skipped: global_imports('ToDoist') # playlist_id, username = self.get_playlist_id_username_from_link(playlist_url) # results = self.sp.user_playlist(username, playlist_id, fields="name,description,tracks,next") # playlist_name = self.html_parser.unescape(results['name']) # if results.has_key('description') and results['description'] is not None: # playlist_desc = self.html_parser.unescape(results['description']) # else: # playlist_desc = playlist_name playlist_name, playlist_desc, tracks = self.get_playlist_name_desc_tracks( playlist_url) logger.info( u'Copying {} from Spotify to Google Music'.format(playlist_name)) logger.debug(u'Playlist Name: {}, Playlist Description: {}'.format( playlist_name, playlist_desc)) # tracks = results['tracks'] song_list = self.get_all_tracks_as_list(tracks, gmusic, strict, collect_skipped) if collect_skipped: ToDoist.ToDoist().api.commit() return Playlist(name=playlist_name, description=playlist_desc, song_list=song_list, spotify_popularity_sort=sort_popularity)
def scrape(client_id, client_secret, username): playlists = [] client = spotipy.Spotify( auth_manager=SpotifyClientCredentials(client_id, client_secret)) generated_playlists = client.user_playlists(username) for generated_playlist in generated_playlists["items"]: playlist = Playlist(generated_playlist["name"]) offset = 0 while True: generated_tracks_container = client.playlist_items( generated_playlist["id"], offset=offset) generated_tracks = generated_tracks_container["items"] generated_tracks_count = len(generated_tracks) if len(generated_tracks) == 0: break for generated_track_container in generated_tracks: generated_track = generated_track_container["track"] generated_track_id = generated_track["uri"] if generated_track[ "id"] is None else generated_track["id"] playlist.songs.append( Song(generated_track["name"], generated_track["artists"][0]["name"], generated_track["album"]["name"], generated_track_id)) offset = offset + generated_tracks_count playlists.append(playlist) return playlists
def __init__(self, parent): super(SystemTray, self).__init__(parent) self.sc = QtGui.QFileDialog() self.nowPlayingLabel = parent.nowPlayingLabel self.programLabel = parent.programLabel self.logoLabel = parent.logoLabel self.coverWebView = parent.coverWebView self.programWebView = parent.programWebView self.tray_menu = parent.tray_menu self.tray_icon = parent.tray_icon self.hide_ui = parent.hide_ui self.show_ui = parent.show_ui self.central_widget = parent.central_widget self.timer_show = parent.timer_show self.setup_menu() self.playlist = Playlist(self) self.instance = vlc.Instance() # create a vlc instance self.player = self.instance.media_player_new() # create a empty vlc media player stream = "http://shoutcast.rtl.it:3010/stream/1/" option = "--extraintf=http" # enable web interface self.media = self.instance.media_new(stream, option) # create the media self.player.set_media(self.media) self.info_0 = None # this variable always before set_meta_data call is None self.timer_check = QtCore.QTimer() self.connect(self.timer_check, QtCore.SIGNAL("timeout()"), self.set_meta_data) # polling every second self.my_dict = {}
def read(path): with open(path, "r", encoding="utf-8", newline="") as file: playlists = [] row_count = 0 for row in csv.reader(file): if row_count == 0: title_index = row.index("title") artist_index = row.index("artist") album_index = row.index("album") id_index = row.index("id") playlist_index = row.index("playlist") else: song = Song(row[title_index], row[artist_index], row[album_index], row[id_index]) playlist_name = row[playlist_index] for playlist in playlists: if playlist.name == playlist_name: matching_playlist = playlist break else: matching_playlist = Playlist(playlist_name) playlists.append(matching_playlist) matching_playlist.songs.append(song) row_count += 1 return playlists
class TestPlayList(unittest.TestCase): def setUp(self): self.song1 = Song("a", "b", "ab", "2:00") self.song2 = Song("aa", "b", "ab", "3:00") self.song3 = Song("aa", "bb", "aabb", "2:00") self.pl = Playlist("Mine") def test_equal_song(self): self.assertNotEqual(self.song1, self.song2) def test_add_song(self): self.pl.add_song(self.song1) self.assertEqual(len(self.pl.songs), 1) #self.assertEqual(self.pl.add_song(self.song2), "Fail !") self.assertEqual(self.song1._length,self.song3._length)
def __init__(self, *args, **kwargs): ViewerFactory.__init__(self, *args, **kwargs) self.protocol = PlayerController self.playList = kwargs.get('playlist', Playlist()) self.history = kwargs.get('history', set()) self.currentTrack = None self.lastChanged = 0 self.track_builders = {}
def create_playlist(name, user_id): logging.debug('{CRUD} BEGIN function create_playlist()') playlist = Playlist(name, user_id) logging.debug('{CRUD} Creating playlist: %s by user: %s', playlist, user_id) session.add(playlist) session.commit() logging.debug('{CRUD} END function create_playlist()') logging.info('{CRUD} Playlist created')
def setUp(self): self.testplaylist = Playlist("Test Playlist") self.song = Song("Title", "Artist", "Album", 5, 20, 120) self.song1 = Song("Title1", "Artist", "Album1", 1, 20, 50) self.song2 = Song("Title2", "Artist1", "Album1", 1, 20, 100) self.testplaylist.add_song(self.song) self.testplaylist.add_song(self.song1) self.testplaylist.add_song(self.song2)
class Channel: def __init__(self): self.Playlist = Playlist() self.name = '' self.playlistPosition = 0 self.showTimeOffset = 0 self.lastAccessTime = 0 self.totalTimePlayed = 0 self.fileName = '' self.isPaused = False self.isValid = False self.isRandom = False self.isReverse = False self.mode = 0 self.ruleList = [] self.channelNumber = 0 self.isSetup = False self.hasChanged = False def log(self, msg, level=xbmc.LOGDEBUG): log('Channel: ' + msg, level) def setPlaylist(self, filename): return self.Playlist.load(filename) def loadRules(self, channel): del self.ruleList[:] listrules = RulesList() self.channelNumber = channel try: rulecount = int( ADDON_SETTINGS.getSetting('Channel_' + str(channel) + '_rulecount')) for i in range(rulecount): ruleid = int( ADDON_SETTINGS.getSetting('Channel_' + str(channel) + '_rule_' + str(i + 1) + '_id')) for rule in listrules.ruleList: if rule.getId() == ruleid: self.ruleList.append(rule.copy()) for x in range(rule.getOptionCount()): self.ruleList[-1].optionValues[ x] = ADDON_SETTINGS.getSetting('Channel_' + str(channel) + '_rule_' + str(i + 1) + '_opt_' + str(x + 1)) self.log("Added rule - " + self.ruleList[-1].getTitle()) break except Exception, e: self.ruleList = []
def process(file): pls_file = file m3u_file = re.sub(r".pls$", ".m3u", pls_file) in_playlist = Playlist(pls_file) pls_entries = in_playlist.get_entries() output = ["#EXTM3U\n"] for entry in pls_entries: output.append("#EXTINF:%s, %s\n%s\n" % (entry[3], entry[2], entry[1])) print "Converting %s to %s" % (pls_file, m3u_file) handle = open(m3u_file, "w") handle.writelines(output) handle.close
def __dispatch(self, s): now = time.time() sys.stderr.write("%i \n" % now) if s.find("engineStateChange: empty" ) >= 0: # The following is a trick to make stop work; there's got to be a way to talk to this # thread # Issue: it doesn't work from Amarok itself if (now - self.__last >= 3): self.__player.playRandom() else: sys.stderr.write("Too soon: skipping\n") elif s.find("trackChange" ) >= 0: pl = Playlist() if not pl.isPlaying(): self.__player.playRandom() else: sys.stderr.write("Unknown notification: " + s + " -> ignoring\n") self.__last = now
def main(): pc_dir, player_dir = login() # cls() pc_playlist = Playlist(pc_dir) player_playlist = Playlist(player_dir) print("----------------CLEANING PLAYLIST----------------") clean_player_folders(pc_playlist, player_playlist) print('\n\n') print("----------------SYNCING PLAYLIST----------------") copy_music_to_player(pc_playlist=pc_playlist, player_playlist=player_playlist)
def run(): ''' Starts the app ''' global CONF, PL if len(argv) > 1: if argv[1] == '-h' or argv[1] == '--help': showHelp() elif argv[1] == '-v' or argv[1] == '--version': printexit(VERSION) else: showHelp() if os.path.isfile('config.json'): readConfig() if os.path.isfile('playlist.json'): PL = Playlist('playlist.json') else: PL = Playlist(CONF['url']) else: url = getin('You are creating a new project. Give URL of the playlist') PL = Playlist(url) CONF = { 'output_format': '', 'start': 1, 'end': len(PL.res), 'download': { 'resolution': 720, 'video_format': '', 'bitrate': 0, 'audio_format': '', 'more_options': '-o "%(title)s.%(ext)s"' }, 'url': url } saveConfig() print() confirm = input( 'Config saved as config.json. Edit it if you please. Then press ENTER ' ) readConfig() # CONFIG read/create done. Now downloading while CONF['start'] <= CONF['end']: retcode = PL.download( CONF['start'], **{ 'res': CONF['download']['resolution'], 'bitrate': CONF['download']['bitrate'], 'vext': CONF['download']['video_format'], 'aext': CONF['download']['audio_format'], 'oext': CONF['output_format'], 'more': CONF['download']['more_options'] }) if retcode != 0: # if failed, try again continue CONF['start'] += 1 saveConfig()
def __load_playlists(self): """ Loads the available playlists. """ def cb(pl, name, location): f = self.call_service(msgs.CORE_SVC_GET_FILE, location) if (f): pl.append(f) else: # insert a placeholder for files that are currently # not available f = File(self) f.name = name f.info = location pl.append(f) # create playlist folder if it does not yet exist if (not os.path.exists(_PLAYLIST_DIR)): try: os.makedirs(_PLAYLIST_DIR) except: pass now = time.time() # load playlists self.__lists = [] files = [f for f in os.listdir(_PLAYLIST_DIR) if f.endswith(".m3u")] for f in files: path = os.path.join(_PLAYLIST_DIR, f) pl = Playlist() pl.load_from_file(path, cb) self.__lists.append((pl.get_name(), pl)) #end for self.__ensure_special_playlists() # sort by name self.__lists.sort(lambda a, b: cmp(a[0], b[0])) self.__current_list = self.__lists[0][1] self.__current_folder = None logging.profile(now, "[playlist] loaded playlists")
def __init__(self): self.Playlist = Playlist() self.name = "" self.playlistPosition = 0 self.showTimeOffset = 0 self.lastAccessTime = 0 self.totalTimePlayed = 0 self.fileName = "" self.isPaused = False self.isValid = False self.mode = 0
def playlists_by_channel(self, youtube, channel_id): playlists_response = youtube.playlists().list(part="snippet", channelId=channel_id, maxResults=50).execute() Playlists = [] for item in playlists_response["items"]: Playlists.append( Playlist(item["id"], item["snippet"]["title"], None)) return Playlists
def agregarPlaylist(): global Playlists usuario = request.json['usuario'] spotify = request.json['spotify'] newPlaylist = Playlist(usuario, spotify) Playlists.append(newPlaylist) return jsonify({ 'message': 'Success', 'reason': 'Se agrego a mi Playlist' })
def serve(request): c = Collection() p = Playlist() player = Player() doc = CGI.httpHeaders() doc += CGI.htmlHead({"style": ["../playlist.css"]}) if request.command == "POST": form = request.form if form.has_key("addSongs"): for e in makeList(form.getvalue("song")): if e is not None: doc += addSong(p, c, e) elif form.has_key("addAlbums"): for e in makeList(form.getvalue("album")): if e is not None: doc += addAlbum(p, c, e) elif form.has_key("clear"): p.clear() elif form.has_key("clearAndStop"): p.clear() request.state.stop() player.stop() f = p.update() doc += playlistToHtml(f, p) doc += CGI.htmlTail() request.serve_string(doc)
def serve(request): p = Playlist() player = Player() doc = CGI.httpHeaders() doc += CGI.htmlHead({ 'style':['../playlist.css'] }) if request.command == "POST": form = request.form if form.has_key('addSongs'): for e in makeList(form.getvalue('song')): if e is not None: doc += addSong(p, e) elif form.has_key('addAlbums'): for e in makeList(form.getvalue('album')): if e is not None: doc += addAlbum(p, e) elif form.has_key('clear'): p.clear() elif form.has_key('clearAndStop'): p.clear() request.state.stop() player.stop() f = p.update() doc += playlistToHtml(f, p) doc += CGI.htmlTail() request.serve_string(doc)
def main(): form = cgi.FieldStorage() c = Collection() p = Playlist() player = Player() CGI.httpHeaders() CGI.htmlHead({ 'style':['../playlist.css'] }) if os.environ['REQUEST_METHOD'] == "POST": if form.has_key('addSongs'): for e in makeList(form.getvalue('song')): if e is not None: addSong(p, c, e) elif form.has_key('addAlbums'): for e in makeList(form.getvalue('album')): if e is not None: addAlbum(p, c, e) elif form.has_key('clear'): p.clear() elif form.has_key('clearAndStop'): p.clear() player.stop() f = p.update() playlistToHtml(f, p) CGI.htmlTail()
class Channel: def __init__(self): self.Playlist = Playlist() self.name = '' self.playlistPosition = 0 self.showTimeOffset = 0 self.lastAccessTime = 0 self.totalTimePlayed = 0 self.fileName = '' self.isPaused = False self.isValid = False self.isRandom = False self.isReverse = False self.mode = 0 self.ruleList = [] self.channelNumber = 0 self.isSetup = False self.hasChanged = False def log(self, msg, level = xbmc.LOGDEBUG): log('Channel: ' + msg, level) def setPlaylist(self, filename): return self.Playlist.load(filename) def loadRules(self, channel): del self.ruleList[:] listrules = RulesList() self.channelNumber = channel try: rulecount = int(ADDON_SETTINGS.getSetting('Channel_' + str(channel) + '_rulecount')) for i in range(rulecount): ruleid = int(ADDON_SETTINGS.getSetting('Channel_' + str(channel) + '_rule_' + str(i + 1) + '_id')) for rule in listrules.ruleList: if rule.getId() == ruleid: self.ruleList.append(rule.copy()) for x in range(rule.getOptionCount()): self.ruleList[-1].optionValues[x] = ADDON_SETTINGS.getSetting('Channel_' + str(channel) + '_rule_' + str(i + 1) + '_opt_' + str(x + 1)) self.log("Added rule - " + self.ruleList[-1].getTitle()) break except Exception,e: self.ruleList = []
class PlaylistTest(unittest.TestCase): def setUp(self): self.playlist = Playlist("MyPlaylist") self.song1 = Song("TestTitle", "TestArtist", "TestAlbum", 3, 200, 128, "") self.playlist.add_song(self.song1) def test_init(self): self.assertEqual(self.playlist.name, "MyPlaylist") def test_get_all_songs(self): self.assertEqual(self.playlist.get_all_songs(), [self.song1]) def test_get_first_song(self): self.assertEqual(self.playlist.get_first_song(), self.song1) def test_add_song(self): self.song2 = Song("It's My Life", "Bon Jovi", "Unknown Album", 5, 200, 192, "") self.playlist.add_song(self.song2) self.assertEqual( [self.song1, self.song2], self.playlist.get_all_songs()) def test_remove_song(self): with mock.patch('builtins.input', return_value=1): self.assertEqual( self.playlist.get_first_song().title, 'TestTitle') def test_rate_songs(self): with mock.patch('builtins.input', return_value=3): self.assertEqual( self.playlist.get_first_song().rating, 3) def test_remove_disrated(self): with mock.patch('builtins.input', return_value=4): self.assertEqual(self.playlist.get_all_songs(), [self.song1])
class SystemTray(QtGui.QSystemTrayIcon): """ Class System Tray which show app indicator and supports its actions. """ def __init__(self, parent): super(SystemTray, self).__init__(parent) self.sc = QtGui.QFileDialog() self.nowPlayingLabel = parent.nowPlayingLabel self.programLabel = parent.programLabel self.logoLabel = parent.logoLabel self.coverWebView = parent.coverWebView self.programWebView = parent.programWebView self.tray_menu = parent.tray_menu self.tray_icon = parent.tray_icon self.hide_ui = parent.hide_ui self.show_ui = parent.show_ui self.central_widget = parent.central_widget self.timer_show = parent.timer_show self.setup_menu() self.playlist = Playlist(self) self.instance = vlc.Instance() # create a vlc instance self.player = self.instance.media_player_new() # create a empty vlc media player stream = "http://shoutcast.rtl.it:3010/stream/1/" option = "--extraintf=http" # enable web interface self.media = self.instance.media_new(stream, option) # create the media self.player.set_media(self.media) self.info_0 = None # this variable always before set_meta_data call is None self.timer_check = QtCore.QTimer() self.connect(self.timer_check, QtCore.SIGNAL("timeout()"), self.set_meta_data) # polling every second self.my_dict = {} def setup_menu(self): """ Setup app indicator menu. :return: None """ # menu self.show_action = QtGui.QAction("Show", self.tray_menu) self.connect(self.show_action, QtCore.SIGNAL("triggered()"), self.show_all) self.tray_menu.addAction(self.show_action) self.play_pause_action = QtGui.QAction("Play", self.tray_menu) self.connect(self.play_pause_action, QtCore.SIGNAL("triggered()"), self.play_pause) self.tray_menu.addAction(self.play_pause_action) self.stop_action = QtGui.QAction("Stop", self.tray_menu) self.connect(self.stop_action, QtCore.SIGNAL("triggered()"), self.stop) self.tray_menu.addAction(self.stop_action) self.stop_action.setVisible(False) self.save_cover_action = QtGui.QAction("Save album cover", self.tray_menu) self.connect( self.save_cover_action, QtCore.SIGNAL("triggered()"), lambda: self.save_picture( self.my_dict["album_cover"], self.my_dict[u"artist_name"] + " - " + self.my_dict[u"album_title"] ), ) self.tray_menu.addAction(self.save_cover_action) self.save_cover_action.setVisible(False) self.save_image_action = QtGui.QAction("Save program image", self.tray_menu) self.connect( self.save_image_action, QtCore.SIGNAL("triggered()"), lambda: self.save_picture( self.my_dict["program_image"], self.my_dict[u"program_title"] + " - " + self.my_dict[u"speakers"] ), ) self.tray_menu.addAction(self.save_image_action) self.save_image_action.setVisible(False) quit_action = QtGui.QAction("Quit", self.tray_menu) self.connect(quit_action, QtCore.SIGNAL("triggered()"), self.quit_app) self.tray_menu.addAction(quit_action) # system tray icon self.tray_icon.setIcon(QtGui.QIcon(":/images/icon.png")) self.tray_icon.setContextMenu(self.tray_menu) self.tray_icon.show() def hide_all(self): """ Hide UI. """ self.hide_ui() self.central_widget.hide() def show_all(self): """" Show UI for 10 seconds, then hide it. """ print "show" self.show_ui() self.central_widget.show() self.timer_show.start(10000) # 10 seconds, display UI time in ms self.timer_show.timeout.connect(self.hide_all) def set_meta_data(self): """ Set xml meta data and show message. Check if images are available to download. :return: None """ info_1 = self.media.get_meta(vlc.Meta.NowPlaying) # get xml data if info_1 != self.info_0: self.info_0 = info_1 # print "now playing: {0}".format(self.info_0) self.playlist.set_info(self.playlist.xml_to_dict(self.info_0)) self.playlist.show_msg() self.my_dict = self.playlist.xml_to_dict(self.info_0) # print "my_dict: ", self.my_dict if self.player.is_playing(): try: if self.my_dict["album_cover"]: self.save_cover_action.setVisible(True) else: self.save_cover_action.setVisible(False) except TypeError: # parse data delay when play button pressed pass try: if self.my_dict["program_image"]: self.save_image_action.setVisible(True) else: self.save_image_action.setVisible(False) except TypeError: # parse data delay when play button pressed pass def play_pause(self): """ Play or pause radio stream. :return: None """ if self.player.is_playing(): # print "paused" self.timer_show.killTimer(10) self.timer_check.stop() self.play_pause_action.setText("Paused") self.player.pause() self.hide_all() self.stop_action.setVisible(True) else: # print "play" self.timer_check.start(1000) self.play_pause_action.setText("Pause") self.player.play() self.set_meta_data() self.playlist.show_msg() self.stop_action.setVisible(True) def stop(self): """ Stop stream. :return: None """ # print "stop" self.player.stop() self.play_pause_action.setText("Play") self.stop_action.setVisible(False) self.save_cover_action.setVisible(False) self.save_image_action.setVisible(False) self.hide_all() @staticmethod def save_picture(url, file_name): """ Save album cover and/or program image. :param url: file url :param file_name: file name :return: None """ location = QtGui.QFileDialog() dir_path = QtCore.QDir() path = dir_path.homePath() + dir_path.separator() + unicode(file_name) file_path = location.getSaveFileName(location, "Save file as", path) if location: urllib.urlretrieve(url, unicode(file_path)) @staticmethod def quit_app(): """ Close application. :return: None """ # print "quit" sys.exit()
class Channel: def __init__(self): self.Playlist = Playlist() self.name = "" self.playlistPosition = 0 self.showTimeOffset = 0 self.lastAccessTime = 0 self.totalTimePlayed = 0 self.fileName = "" self.isPaused = False self.isValid = False self.mode = 0 def log(self, msg): log("Channel: " + msg) def setPlaylist(self, filename): return self.Playlist.load(filename) def setPaused(self, paused): self.isPaused = paused def setShowTime(self, thetime): self.showTimeOffset = thetime // 1 def setShowPosition(self, show): show = int(show) self.playlistPosition = self.fixPlaylistIndex(show) def setAccessTime(self, thetime): self.lastAccessTime = thetime // 1 def getCurrentDuration(self): return self.getItemDuration(self.playlistPosition) def getItemDuration(self, index): return self.Playlist.getduration(self.fixPlaylistIndex(index)) def getTotalDuration(self): return self.Playlist.totalDuration def getCurrentDescription(self): return self.getItemDescription(self.playlistPosition) def getItemDescription(self, index): return self.Playlist.getdescription(self.fixPlaylistIndex(index)) def getCurrentEpisodeTitle(self): return self.getItemEpisodeTitle(self.playlistPosition) def getItemEpisodeTitle(self, index): return self.Playlist.getepisodetitle(self.fixPlaylistIndex(index)) def getCurrentTitle(self): return self.getItemTitle(self.playlistPosition) def getItemTitle(self, index): return self.Playlist.getTitle(self.fixPlaylistIndex(index)) def getCurrentFilename(self): return self.getItemFilename(self.playlistPosition) def getItemFilename(self, index): return self.Playlist.getfilename(self.fixPlaylistIndex(index)) def fixPlaylistIndex(self, index): if self.Playlist.size() == 0: return index while index >= self.Playlist.size(): index -= self.Playlist.size() while index < 0: index += self.Playlist.size() return index def addShowPosition(self, addition): self.setShowPosition(self.playlistPosition + addition)
import json from Playlist import Playlist from Song import Song def jdefaultplaylist(o): if isinstance(o, Playlist): return str(o.str()) return o.__dict__ def jdefaultsong(o): if isinstance(o, Song): return str(o.str()) return o.__dict__ new = Playlist("Test Playlist") song = Song("Title", "Artist", "Album", 5, 20, 120) song1 = Song("Title1", "Artist1", "Album", 5, 25, 120) song2 = Song("Title2", "Artist2", "Album", 5, 40, 120) new.add_song(song) new.add_song(song1) new.add_song(song2) with open('playlist.json', mode='w', encoding='utf-8') as f: for each in new.songs: json.dump(each, f, default=jdefaultsong) f.write('\n')
def __init__(self, state): self.__running = True; self.__playlist = Playlist() self.__state = state dcop = Dcop.init() dcop.player.enableRandomMode("false")
def run_command(self,*args) : # args[0] is command if args[0] == "play_pause" : return self.remote.play_pause() elif args[0] == "next": return self.remote.next() elif args[0] == "previous": return self.remote.previous() elif args[0] == "add_playlist": playlist_name = args[1] player_id = args[2] playlist_repo = GetPlaylist() playlist_repo.add_playlist(playlist_name,player_id) elif args[0] == "delete_file_pl": playlist_name = args[1] file_repo = FileRepo() file_repo.delete_from_playlist(self.player_ip,playlist_name) elif args[0] == "add_file_to_pl": file_name = args[1] playlist_name = args[2] file_repo = FileRepo() file_repo.add(file_name,self.player_ip,playlist_name) elif args[0] == "get_playlist_songs": playlist_name = args[1] player_id = args[2] pl = Playlist(playlist_name,player_id) pl.update_filelist(self.player_ip) file_list = pl.get_filelist() return_list = [] for song in file_list: return_list.append(song.get_file_name()) return return_list elif args[0] == "remove": file_management = FileManagment() file_name = args[1] file_management.remove(file_name,self.player_ip) file_repo = FileRepo() file_repo.delete_file(file_name,self.player_ip) else: #Play Song file_queue = [] check = 1 file_list = args[2] file_name = args[1] for file_ in file_list: if check and file_.get_file_name() != file_name: pass else: check = 0 file_queue.append(file_.get_file_name()) return self.remote.play_song(file_queue)
def setUp(self): self.playlist = Playlist("MyPlaylist") self.song1 = Song("TestTitle", "TestArtist", "TestAlbum", 3, 200, 128, "") self.playlist.add_song(self.song1)
def play(p, request): request.state.start() p.play() pl = Playlist() if not pl.isPlaying(): p.playRandom()
class Channel: def __init__(self): self.Playlist = Playlist() self.name = '' self.playlistPosition = 0 self.showTimeOffset = 0 self.lastAccessTime = 0 self.totalTimePlayed = 0 self.fileName = '' self.isPaused = False self.isValid = False self.isRandom = False self.mode = 0 self.ruleList = [] self.channelNumber = 0 self.isSetup = False def log(self, msg, level = xbmc.LOGDEBUG): log('Channel: ' + msg, level) def setPlaylist(self, filename): return self.Playlist.load(filename) def loadRules(self, channel): del self.ruleList[:] listrules = RulesList() self.channelNumber = channel try: rulecount = int(ADDON_SETTINGS.getSetting('Channel_' + str(channel) + '_rulecount')) for i in range(rulecount): ruleid = int(ADDON_SETTINGS.getSetting('Channel_' + str(channel) + '_rule_' + str(i + 1) + '_id')) for rule in listrules.ruleList: if rule.getId() == ruleid: self.ruleList.append(rule.copy()) for x in range(rule.getOptionCount()): self.ruleList[-1].optionValues[x] = ADDON_SETTINGS.getSetting('Channel_' + str(channel) + '_rule_' + str(i + 1) + '_opt_' + str(x + 1)) self.log("Added rule - " + self.ruleList[-1].getTitle()) break except: self.ruleList = [] def setPaused(self, paused): self.isPaused = paused def setShowTime(self, thetime): self.showTimeOffset = thetime // 1 def setShowPosition(self, show): show = int(show) self.playlistPosition = self.fixPlaylistIndex(show) def setAccessTime(self, thetime): self.lastAccessTime = thetime // 1 def getCurrentDuration(self): return self.getItemDuration(self.playlistPosition) def getItemDuration(self, index): return self.Playlist.getduration(self.fixPlaylistIndex(index)) def getTotalDuration(self): return self.Playlist.totalDuration def getCurrentLiveID(self): return self.getItemLiveID(self.playlistPosition) def getItemLiveID(self, index): return self.Playlist.getLiveID(self.fixPlaylistIndex(index)) def getCurrenttimestamp(self): return self.getItemtimestamp(self.playlistPosition) def getItemtimestamp(self, index): return self.Playlist.gettimestamp(self.fixPlaylistIndex(index)) def getCurrentgenre(self): return self.getItemgenre(self.playlistPosition) def getItemgenre(self, index): return self.Playlist.getgenre(self.fixPlaylistIndex(index)) def getCurrentDescription(self): return self.getItemDescription(self.playlistPosition) def getItemDescription(self, index): return self.Playlist.getdescription(self.fixPlaylistIndex(index)) def getCurrentEpisodeTitle(self): return self.getItemEpisodeTitle(self.playlistPosition) def getItemEpisodeTitle(self, index): return self.Playlist.getepisodetitle(self.fixPlaylistIndex(index)) def getCurrentTitle(self): return self.getItemTitle(self.playlistPosition) def getItemTitle(self, index): return self.Playlist.getTitle(self.fixPlaylistIndex(index)) def getCurrentFilename(self): return self.getItemFilename(self.playlistPosition) def getItemFilename(self, index): return self.Playlist.getfilename(self.fixPlaylistIndex(index)) def fixPlaylistIndex(self, index): if self.Playlist.size() == 0: return index while index >= self.Playlist.size(): index -= self.Playlist.size() while index < 0: index += self.Playlist.size() return index def addShowPosition(self, addition): self.setShowPosition(self.playlistPosition + addition)
def setUp(self): self.song1 = Song("a", "b", "ab", "2:00") self.song2 = Song("aa", "b", "ab", "3:00") self.song3 = Song("aa", "bb", "aabb", "2:00") self.pl = Playlist("Mine")