#!/usr/bin/env python3 import datetime import glob import json import music_tag import os from os.path import isfile, join from pathlib import Path import readline import sys import youtube_dl # MUSIC_DIRECTORY = "~/Music/" MUSIC_DIRECTORY = "./music/" COMMANDS = ['extra', 'extension', 'stuff', 'errors', 'email', 'foobar', 'foo'] FILES = [] DIRECTORIES = [] AUDIO_OPTIONS = { 'format': 'bestaudio/best', 'cookiefile': 'cookies.txt', 'outtmpl': MUSIC_DIRECTORY + '%(title)s.%(ext)s', 'postprocessors': [ { 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }, {'key': 'FFmpegMetadata'}, ], 'writeinfojson': True } ytdl = youtube_dl.YoutubeDL(AUDIO_OPTIONS) # TODO: Make this better with argparse def get_playlist_url(): return sys.argv[1] def download_song(song_url): """ Download a song using youtube url and song title """ return ytdl.extract_info(song_url, download=True) def write_metadata_to_song_file(file, metadata): f = music_tag.load_file(file) f['name'] = metadata['title'] f['artist'] = metadata['artist'] f['album'] = metadata['album'] f['year'] = format_youtube_date(metadata['release_date']) f.save() def format_youtube_date(date): fmt = "%Y%m%d" d = datetime.datetime.strptime(date, fmt) return d.year def sort_stuff(): # read in all the files and directories to move get_all_files() # setup tab completion readline.parse_and_bind("tab: complete") readline.set_completer(complete) in_directory = False # loop over all the files left and print(len(FILES)) for f in FILES: in_directory = False while not in_directory: print(f) directory = input('Enter directory: ') if directory in DIRECTORIES: move_file(directory, f) in_directory = True if directory == "refresh": get_directories() def complete(text, state): for cmd in DIRECTORIES: if cmd.startswith(text): if not state: return cmd else: state -= 1 def get_all_files(directory): things = glob.glob(os.path.join(directory, '*.mp3')) files = [] for thing in things: if os.path.isfile(thing): files.append(thing) return files def get_directories(): files = os.listdir() global DIRECTORIES for f in files: if os.path.isdir(f): DIRECTORIES.append(f) def move_file(file, metadata): p = os.path.join( MUSIC_DIRECTORY, metadata['artist'].replace(' ', '_').lower(), metadata['album'].replace(' ', '_').lower()) Path(p).mkdir(parents=True, exist_ok=True) os.rename( file, os.path.join( p, metadata['artist'].replace(' ', '_').lower() + '_' + metadata['title'].replace(' ', '_').lower() + '.mp3')) if __name__ == "__main__": # Get the playlist url from the command line playlist_url = get_playlist_url() # Download the songs download_song(playlist_url) files = get_all_files(MUSIC_DIRECTORY) for f in files: json_data = None with open(f.replace('.mp3', '.info.json')) as json_file: json_data = json.load(json_file) write_metadata_to_song_file(f, json_data) move_file(f, json_data)