# YT_Downloader by gplgps
# Version: 0.0.1
# Requires 'youtube_dl' and 'tld' modules from pypi
# Requires ffmpeg on PATH

from __future__ import unicode_literals
from tld import get_tld
import youtube_dl

link = input('Insert the link: ')
opt = 1
fast = 0

while True:
    opt = input('MP(3) or MP(4): ')
    if (opt == 'MP3' or opt == 'MP4' or opt == '3' or opt == '4'):
        break

url_info = get_tld(link, as_object=True)

if (url_info.fld == 'youtube.com'
    or url_info.fld == 'youtu.be'):
    fast = 1

class MyLogger(object):
    def debug(self, msg):
        pass

    def warning(self, msg):
        pass

    def error(self, msg):
        print(msg)


def my_hook(d):
    if d['status'] == 'finished':
        print('Done downloading, now converting ...')

if (opt == 'MP3' or opt == '3'):
    print('We\'re downloading it for you')
    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
        }],
        'logger': MyLogger(),
        'progress_hooks': [my_hook],
    }
elif (fast == 1):
    print('YouTube video. Fast mode engaged.')
    ydl_opts = {
        'format': 'bestvideo+bestaudio[ext=m4a]',
        'merge_output_format': 'mp4',
        'logger': MyLogger(),
        'progress_hooks': [my_hook],
    }
else:
    print('Not an Youtube Video. Might take more time.')
    ydl_opts = {
        'hls_prefer_native': False,
        'postprocessors': [{
            'key': 'FFmpegVideoConvertor',
            'preferedformat': 'mp4',
        }],
        'logger': MyLogger(),
        'progress_hooks': [my_hook],
    }

with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download([link])
