#!/usr/sbin/python

import os, sys, json, struct, threading, subprocess


DLPATH = os.path.expanduser("~") + "/Downloads"
MAJOR_VERSION = sys.version_info[0]


def threaded(fn):
    def wrapper(*args, **kwargs):
        threading.Thread(target=fn, args=args, kwargs=kwargs).start()

    return wrapper


# Python 2.x and 3.x read version
# Read a message from stdin and decode it.
def getMessage():
    message   = None
    rawLength = None

    if MAJOR_VERSION == 2:  # py2
        rawLength = sys.stdin.read(4)
    else:  # py3
        rawLength = sys.stdin.buffer.read(4)

    if len(rawLength) == 0:
        sys.exit(0)

    messageLength = struct.unpack('@I', rawLength)[0]
    if MAJOR_VERSION == 2:  # py2
        message = sys.stdin.read(messageLength)
    else:  # py3
        message = sys.stdin.buffer.read(messageLength).decode("utf-8")

    return json.loads(message)



@threaded
def downloadVideo(command):
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)


while True:
    receivedMessage = getMessage()
    if receivedMessage:
        outputFile  = DLPATH + "/%\(title\)s.%\(ext\)s "
        command     = "youtube-dl --no-playlist -o " + outputFile + receivedMessage;
        downloadVideo(command)
