示例#1
0
    def download(self, url):
        """
        Downloads a MP3 file that is associated with the track at the URL passed.
        
        :param str url: URL of the track to be downloaded
        """

        try:
            track = self.client.get('/resolve', url=url)
        except HTTPError:
            log.error(f"{url} is not a Soundcloud URL.")
            return
        r = requests.get(self.client.get(track.stream_url,
                                         allow_redirects=False).location,
                         stream=True)
        total_size = int(r.headers['content-length'])
        chunk_size = 1000000
        file_name = track.title + '.mp3'
        with open(file_name, 'wb') as f:
            for data in tqdm(r.iter_content(chunk_size),
                             desc=track.title,
                             total=total_size / chunk_size,
                             unit='MB',
                             file=sys.stdout):
                f.write(data)
        return file_name
示例#2
0
    def connect(self):
        """Creates connection to the Google Drive API, sets the connection attribute to make requests, and creates the Music folder if it doesn't exist."""

        SCOPES = 'https://www.googleapis.com/auth/drive'
        store = file.Storage('drive_credentials.json')
        creds = store.get()
        if not creds or creds.invalid:
            try:
                flow = client.flow_from_clientsecrets('client_secret.json',
                                                      SCOPES)
            except InvalidClientSecretsError:
                log.error(
                    'ERROR: Could not find client_secret.json in current directory, please obtain it from the API console.'
                )
                return
            creds = tools.run_flow(flow, store)
        self.connection = build('drive', 'v3', http=creds.authorize(Http()))

        response = self.connection.files().list(
            q="name='Music' and mimeType='application/vnd.google-apps.folder' and trashed=false"
        ).execute()
        try:
            folder_id = response.get('files', [])[0]['id']
        except IndexError:
            log.warning('Music folder is missing. Creating it.')
            folder_metadata = {
                'name': 'Music',
                'mimeType': 'application/vnd.google-apps.folder'
            }
            folder = self.connection.files().create(body=folder_metadata,
                                                    fields='id').execute()
示例#3
0
    def use_music_service(self, service_name, api_key):
        """
        Sets the current music service to service_name.

        :param str service_name: Name of the music service
        :param str api_key: Optional API key if necessary
        """

        try:
            self.current_music = self.music_services[service_name]
        except KeyError:
            if service_name == 'youtube':
                self.music_services['youtube'] = Youtube()
                self.current_music = self.music_services['youtube']
            elif service_name == 'soundcloud':
                self.music_services['soundcloud'] = Soundcloud(api_key=api_key)
                self.current_music = self.music_services['soundcloud']
            else:
                log.error('Music service name is not recognized.')
示例#4
0
    def download(self, url):
        """
        Downloads a MP4 or WebM file that is associated with the video at the URL passed.

        :param str url: URL of the video to be downloaded
        :return str: Filename of the file in local storage
        """

        try:
            yt = YouTube(url)
        except RegexMatchError:
            log.error(f"Cannot download file at {url}")
        else:
            stream = yt.streams.first()
            log.info(f"Download for {stream.default_filename} has started")
            start_time = time()
            stream.download()
            end_time = time()
            log.info(
                f"Download for {stream.default_filename} has finished in {end_time - start_time} seconds"
            )
            return stream.default_filename
示例#5
0
    def use_storage_service(self, service_name, custom_path):
        """
        Sets the current storage service to service_name and runs the connect method on the service.

        :param str service_name: Name of the storage service
        :param str custom_path: Custom path where to download tracks for local storage (optional, and must already exist, use absolute paths only)
        """

        try:
            self.current_storage = self.storage_services[service_name]
        except KeyError:
            if service_name == 'google drive':
                self.storage_services['google drive'] = GoogleDrive()
                self.current_storage = self.storage_services['google drive']
                self.current_storage.connect()
            elif service_name == 'dropbox':
                log.error('Dropbox is not supported yet.')
            elif service_name == 'local':
                self.storage_services['local'] = LocalStorage(custom_path=custom_path)
                self.current_storage = self.storage_services['local']
                self.current_storage.connect()
            else:
                log.error('Storage service name is not recognized.')