--------------------------------------------------------------------------
 User Library
 --------------------------------------------------------------------------
 Fetch songs from library
195769
def library(page = 0)
      songs = []
      resp = @client.request('userGetSongsInLibrary',
                             userID: @id,
                             page: page.to_s)
      songs = resp['songs'].map do |song|
        Song.new song
      end if resp.key?('songs')
      songs
    end
1062574
def songlyrics(song):
    
    translate = {
        URLESCAPE: '',
        ' ': '-'
    }
    artist = song.artist.lower()
    artist = normalize(artist, translate)
    title = song.title.lower()
    title = normalize(title, translate)

    artist = re.sub(r'\-{2,}', '-', artist)
    title = re.sub(r'\-{2,}', '-', title)

    url = 'http://www.songlyrics.com/{}/{}-lyrics'.format(artist, title)
    soup = get_url(url)
    text = soup.find(id='songLyricsDiv')
    if not text:
        return ''

    text = text.getText().strip()
    if not text or text.lower().startswith('we do not have the lyrics for'):
        return ''

    return text
1267060
def download_song_by_search(self, song_name):
        

        try:
            song = self.crawler.search_song(song_name, self.quiet)
        except RequestException as exception:
            click.echo(exception)
        else:
            self.download_song_by_id(song.song_id, song.song_name, self.folder)
35054
def download_playlist(playlist):
    
    global arguments
    invalid_chars = '\/:*?|<>"'
    playlist_name = playlist['title'].encode('utf-8', 'ignore')
    playlist_name = playlist_name.decode('utf8')
    playlist_name = ''.join(c for c in playlist_name if c not in invalid_chars)

    if not arguments['--no-playlist-folder']:
        if not os.path.exists(playlist_name):
            os.makedirs(playlist_name)
        os.chdir(playlist_name)

    try:
        with codecs.open(playlist_name + '.m3u', 'w+', 'utf8') as playlist_file:
            playlist_file.write('#EXTM3U' + os.linesep)
            del playlist['tracks'][:offset - 1]
            for counter, track_raw in enumerate(playlist['tracks'], offset):
                logger.debug(track_raw)
                logger.info('Track n°{0}'.format(counter))
                download_track(track_raw, playlist['title'], playlist_file)
    finally:
        os.chdir('..')
925394
def download_person_playlists(self):
        

        with open(person_info_path, 'r') as person_info:
            user_id = int(person_info.read())
        self.download_user_playlists_by_id(user_id)
784657
function() {
		var api_url,
			self = this;

		// Create Dom element
		this._el.content_item	= TL.Dom.create("div", "tl-media-item tl-media-iframe tl-media-spotify", this._el.content);

		// Get Media ID
		if (this.data.url.match(/^spotify:track/) || this.data.url.match(/^spotify:album/) || this.data.url.match(/^spotify:user:.+:playlist:/)) {
			this.media_id = this.data.url;
		}

		if (this.data.url.match(/spotify\.com\/track\/(.+)/)) {
			this.media_id = "spotify:track:" + this.data.url.match(/spotify\.com\/track\/(.+)/)[1];
		} else if (this.data.url.match(/spotify\.com\/album\/(.+)/)) {
			this.media_id = "spotify:album:" + this.data.url.match(/spotify\.com\/album\/(.+)/)[1];
		} else if (this.data.url.match(/spotify\.com\/user\/(.+?)\/playlist\/(.+)/)) {
			var user = this.data.url.match(/spotify\.com\/user\/(.+?)\/playlist\/(.+)/)[1];
			var playlist = this.data.url.match(/spotify\.com\/user\/(.+?)\/playlist\/(.+)/)[2];
			this.media_id = "spotify:user:" + user + ":playlist:" + playlist;
		} else if (this.data.url.match(/spotify\.com\/artist\/(.+)/)) {
			var artist = this.data.url.match(/spotify\.com\/artist\/(.+)/)[1];
			this.media_id = "spotify:artist:" + artist;
		}


		if (this.media_id) {
			// API URL
			api_url = "https://embed.spotify.com/?uri=" + this.media_id + "&theme=white&view=coverart";

			this.player = TL.Dom.create("iframe", "tl-media-shadow", this._el.content_item);
			this.player.width 		= "100%";
			this.player.height 		= "100%";
			this.player.frameBorder = "0";
			this.player.src 		= api_url;

			// After Loaded
			this.onLoaded();

		} else {
				this.loadErrorDisplay(this._('spotify_invalid_url'));
		}
	}
532885
function resolveUri(options) {
    return new Promise(function (resolve, reject) {
        if (!options.client_id) {
            reject(new Error('Error resolveUri options.client_id is required but is null'));
        } else {

            if (!options.uri) {
                throw new Error('Error resolveUri options.uri is required and is: ' + options.uri);
            } else {
                var uri = 'http://api.soundcloud.com/resolve.json?url=' + options.uri + '&client_id=' + options.client_id;
                request.getAsync(uri, {timeout: 10000}).spread(function (response) {

                    if (!response.body || response.body.indexOf('404') !== -1) {
                        if (DEBUG_MODE_ON) {
                            console.log('Error while resolveUri track: ');
                        }
                        reject(new Error('Error while resolveUri track: '));

                    } else {
                        if (DEBUG_MODE_ON) {
                            console.log('resolveUri successful');
                        }
                        try {
                            resolve(JSON.parse(response.body.toString('utf8')));
                        } catch (e) {
                            if (DEBUG_MODE_ON) {
                                console.log('Error while resolveUri track: ' + e);
                            }
                            reject(new Error('Error while resolveUri track: ' + e));
                        }

                    }
                }).catch(function (e) {
                    if (DEBUG_MODE_ON) {
                        console.log('Error while resolveUri track: ', e);
                    }
                    reject(e);
                });
            }
        }
    });
}
1164750
def download(self, directory='~/Music', song_name='%a - %s - %A'):
        
        formatted = self.format(song_name)
        path = os.path.expanduser(directory) + os.path.sep + formatted + '.mp3'
        try:
            raw = self.safe_download()
            with open(path, 'wb') as f:
                f.write(raw)
        except:
            raise
        return formatted
461888
def parse_library(lib_files):
    
    tracks, playlists = lib_files
    lib = MusicLibrary()
    lib_length = len(tracks)
    i = 0

    writer = lib.ix.writer()
    previous_procent_done_str = ""
    for f in tracks:
        track_info = TrackInfo(f)
        lib.add_track_internal(track_info, writer)
        current_percent_done_str = "%d%%" % (i / lib_length * 100)
        if current_percent_done_str != previous_procent_done_str:
            logs.print_info("Analizowanie biblioteki muzycznej... " + current_percent_done_str)
            previous_procent_done_str = current_percent_done_str
        i += 1.0
    logs.print_info("Analizowanie playlist...")
    for f in playlists:
        with open(f, 'r') as fo:
            playlist_dict = loads(fo.read())
            playlist = Playlist(lib, f, playlist_dict['title'], playlist_dict['tracks'])
            lib.add_playlist(playlist)
    writer.commit()
    logs.print_info("Optymalizacja index-u...")
    lib.ix.optimize()
    return lib
1331829
def download_next_song(self, song):
        """"""

        dl_ydl_opts = dict(ydl_opts)
        dl_ydl_opts["progress_hooks"] = [self.ytdl_progress_hook]
        dl_ydl_opts["outtmpl"] = self.output_format

        # Move the songs from the next cache to the current cache
        self.move_next_cache()

        self.state = 'ready'
        self.play_empty()
        # Download the file and create the stream
        with youtube_dl.YoutubeDL(dl_ydl_opts) as ydl:
            try:
                ydl.download([song])
            except DownloadStreamException:
                # This is a livestream, use the appropriate player
                future = asyncio.run_coroutine_threadsafe(self.create_stream_player(song, dl_ydl_opts), client.loop)
                try:
                    future.result()
                except Exception as e:
                    logger.exception(e)
                    self.vafter_ts()
                    return
            except PermissionError:
                # File is still in use, it'll get cleared next time
                pass
            except youtube_dl.utils.DownloadError as e:
                self.logger.exception(e)
                self.statuslog.error(e)
                self.vafter_ts()
                return
            except Exception as e:
                self.logger.exception(e)
                self.vafter_ts()
                return
873372
def getPlaylists(extras=nil)
      method = 'getPlaylists'
      type = Playlist
      args = {}
      args[:extras] = extras if extras
      return_object type,method,args,true
    end
405113
def playlists
      return @playlists if @playlists
      results = @client.request('userGetPlaylists', userID: @id)
      @playlists = results['playlists'].map do |list|
        Playlist.new(@client, list, @id)
      end
    end
600394
def iterplayables():
    '''  '''
    ls = DirScanner(stripdot=True)
    ## filter out just mp3 files (and dirs to support recursion)
    filt = lambda x: ( os.path.isdir(x) or x[-4:].lower() in ALLOWED_TYPES )
    ## take the last two segments of the path as the label
    func = lambda x: '/'.join(x.split('/')[-2:])
    ## iterate over all the files (excluding dirs), filtering for .mp3 and .m4a
    for x,y in ls.iteritems(want_files=True, want_dirs=False, func=func, filt=filt):
        yield {      'name': x.decode('utf-8'),
                'file_name': escape_utf8(y)     }
177629
function getSourceList(playlist) {
  return (playlist || []).map((_, i) => getTrackSources(playlist, i)[0].src);
}
51091
def load_playlist(self, loc, title):
        '''
        
        '''
        lines = [l.strip() for l in open(loc).readlines()]
        self.playlists.setdefault(title, [])
        self.playlists[title].append(Playlist(lines, True))
1002460
async def create_playlist(self, name, *songs):
    '''
    '''
    data = {'Name': name}
    ids = [i.id for i in (await self.process(songs))]

    if ids:
      data['Ids'] = ','.join(ids)

    # TODO - return playlist not status
    return await self.connector.post('/Playlists',
      data=data,
      pass_uid=True,
      remote=False
    )
1064721
function Snippets(options) {
  this.options = options || {};
  this.store = store(this.options);

  this.snippets = {};
  this.presets = {};
  this.cache = {};
  this.cache.data = {};

  var FetchFiles = lazy.FetchFiles();
  this.downloader = new FetchFiles(this.options);
  this.presets = this.downloader.presets;

  if (typeof this.options.templates === 'object') {
    this.visit('set', this.options.templates);
  }
}