yt

youtube like a pro
git clone git://r-36.net/yt
Log | Files | Refs | README | LICENSE

yt (2606B)


      1 #!/usr/bin/env python
      2 #
      3 # Copy me if you can.
      4 # by 20h
      5 #
      6 
      7 import os
      8 import sys
      9 import getopt
     10 import requests
     11 import io
     12 import subprocess
     13 import json
     14 import urllib.parse
     15 from lxml import etree
     16 import youtube_dl
     17 
     18 def getxpath(fd, xpath):
     19 	parser = etree.HTMLParser()
     20 	return etree.parse(fd, parser).xpath(xpath)
     21 
     22 def usage(app):
     23 	app = os.path.basename(app)
     24 	sys.stderr.write("usage: %s [-h] [-a player] [-p page] "\
     25 		"[-r URI|-s searchterm...|-d URI|URI]\n" % (app))
     26 	sys.exit(1)
     27 
     28 def main(args):
     29 	try:
     30 		opts, largs = getopt.getopt(args[1:], "ha:dsrp:")
     31 	except getopt.GetoptError as err:
     32 		print(str(err))
     33 		usage(args[0])
     34 
     35 	player = "ypl"
     36 	dosearch = 0
     37 	dorelated = 0
     38 	page = None
     39 	dodownload = None
     40 
     41 	tplayer = os.getenv("MEDIAPLAYER")
     42 	if tplayer != None:
     43 		player = tplayer
     44 
     45 	for o, a in opts:
     46 		if o == "-h":
     47 			usage(args[0])
     48 		elif o == "-a":
     49 			player = a
     50 		elif o == "-d":
     51 			dodownload = 1
     52 		elif o == "-r":
     53 			dorelated = 1
     54 		elif o == "-s":
     55 			dosearch = 1
     56 		elif o == "-p":
     57 			page = int(a)
     58 	
     59 	if len(largs) < 1:
     60 		usage(args[0])
     61 
     62 	headers = {"content-type": "text/html;charset=utf-8"}
     63 	if dorelated:
     64 		for arg in largs:
     65 			req = requests.get(arg, headers=headers)
     66 			related = getxpath(io.StringIO(req.text), \
     67 				"//ul[@id=\"watch-related\"]")[0]
     68 			elements = related.xpath("./li")
     69 
     70 			for elem in elements:
     71 				href = elem.xpath("./a")[0].attrib["href"]
     72 				title = "".join(elem.xpath(\
     73 						"./a/span[@class=\"title\"]")[0].\
     74 						itertext()).strip()
     75 
     76 				print("https://www.youtube.com%s %s" % (href, title))
     77 	elif dosearch:
     78 		params = {"search_query": " ".join(largs)}
     79 		if page != None:
     80 			params["page"] = str(page)
     81 		req = requests.get("https://www.youtube.com/results",\
     82 				params=params, headers=headers)
     83 		resultdiv = getxpath(io.StringIO(req.text), \
     84 				"//div[@id=\"results\"]")[0]
     85 		results = resultdiv.xpath("./ol/li/ol/li")
     86 		for result in results:
     87 			content = result.xpath(\
     88 				"./div/div[@class=\"yt-lockup-content\"]")
     89 			if len(content) < 1:
     90 				continue
     91 			link = content[0].xpath(\
     92 				"./h3[@class=\"yt-lockup-title\"]/a")[0]
     93 			href = link.attrib["href"]
     94 			title = link.attrib["title"]
     95 
     96 			print("https://www.youtube.com%s %s" % (href, title))
     97 	elif dodownload:
     98 		for arg in largs:
     99 			postprocs = [
    100 					{"key": "FFmpegMetadata"},
    101 					{"key": "FFmpegEmbedSubtitle"}
    102 			]
    103 			with youtube_dl.YoutubeDL(params={"postprocessors":postprocs,\
    104 				"forcefilename": True})\
    105 					as ydl:
    106 				ydl.download([arg])
    107 	else:
    108 		for arg in largs:
    109 			subprocess.call("%s \"%s\"" % (player, arg), shell=True)
    110 
    111 	return 0
    112 
    113 if __name__ == "__main__":
    114 	sys.exit(main(sys.argv))
    115