def recursive_resolve(video_id, lookup_table): umap = resolve3(video_id).urlmap for i in lookup_table: if i in umap: return umap[i], i else: return None, None
def youtube1(self): print("[libyo.youtube Test]") pl="98113EFC99B5878C" from libyo.youtube import Playlist,resolve from random import choice p=Playlist.Playlist(pl).advanced() v=choice(p["data"]["items"]) x=resolve.resolve3(v["video"]["id"]) print(x.title) print()
def _mode_sin(args): q = _job_quality(DummyParser({"resolution":str(args.q),"profile":args.a})) m = {"items":[],"local":[],"local_id":{},"downloads":{},"local_title":{}} if not os.path.exists(args.target_dir): os.makedirs(os.path.abspath(args.target_dir)) for video_id in args.video_id: vid = video_id if not args.u else id_from_url(video_id) vi = resolve3(vid) v = {"id":vid, "title": vi.title} _download(args,m,args.target_dir,q,v)
def youtube2(self): from libyo.youtube.url import id_from_url print("[libyo.youtube.resolve Test]") vid = "http://www.youtube.com/watch?v=zUQCgTFSxBE&list=PL037FB54C523B4637&index=6&feature=plpp_video" id = id_from_url(vid) from libyo.youtube.resolve import resolve3 v= resolve3(id) print (",".join([":".join((str(a),b[:5])) for a,b in v.urlmap.items()])) print(v.title) print(v.uploader) v.fmt_url_map=None v.url_encoded_fmt_stream_map=None v.fmt_stream_map=None for i,j in sorted(v.items()): print("{i}={j}".format(i=repr(i),j=repr(j)))
def resolve_libyo(self): """ ask libyo to resolve. """ # check if we already have the data if "resolve" in self.done: return True # get it from libyo otherwise info = resolve.resolve3(self.video_id) if not info: self.error.emit("Could not find out about video %s using libyo" % self.video_id) return False self.title = info["title"] self.description = info["description"] self.uploader = info["uploader"] self.urlmap = info["fmt_url_map"] self.done.add("resolve") return True
def youtube_init_video(self,video_url): # Get VideoId self.logger_youtube.debug("New Video: "+video_url) match = self.youtube_regexp.match(video_url) if not match: return self.youtube_message.format(video_url) self.logger_youtube.debug("Search String: %s"%match.group(1)) params = sdict_parser(match.group(1)) self.logger_youtube.debug("Parameters: %s"%str(params)) if "v" not in params: return self.youtube_message.format(video_url) vid = params["v"] # Resolve Video self.logger_youtube.debug("Resolving Video: "+vid) video_info = resolve.resolve3(vid,self.resolver) if not video_info: return self.resolve_message.format(vid) self.video_info = video_info # Create Quality List self.logger_youtube.debug("Assembling Format List") self.qa_map = OrderedDict() for f in self.main_q_lookup: if f in video_info.urlmap: self.qa_map[profiles.descriptions[f]]=f # Determine Initial Quality self.logger_youtube.debug("Determining fitting Quality Level") for f in self.pref_q_lookup: if f in video_info.urlmap: fmt = f break; else: fmt = self.qa_map.values()[0] # Update UI self.logger_player.debug("Setting up UI for Video: "+video_info.title) self.uilock=True self.main_window.setWindowTitle(self.window_title_2.format(video_info.title)) # Populate Quality ComboBox self.main_window.ui.combo_quality.clear() self.main_window.ui.combo_quality.addItems(list(self.qa_map.keys())) self.main_window.ui.combo_quality.setCurrentIndex( self.main_window.ui.combo_quality.findText(profiles.descriptions[fmt], flags=QtCore.Qt.MatchExactly)) self.uilock=False # Set Quality Level self.youtube_set_fmt(fmt)
def process(args): if args.extract_url: args.url=args.id try: args.id=getIdFromUrl(args.url) except AttributeError: print("ERROR: invalid URL") return fmt_map = profiles.profiles[cichoice.unify(args.avc)][0] if args.fmt is None and not args.force: fmt_request = [fmt_map[i] for i in (1080,720,480,360,240) if i in fmt_map and i<=qchoice.unify(args.quality)] elif args.fmt is not None: fmt_request = [args.fmt] elif args.force: fmt_request = [fmt_map[qchoice.unify(args.quality)]] print("Receiving Video with ID '{0}'".format(args.id)) video_info = resolve3(args.id) if not video_info: print("ERROR: Could not find Video (Maybe your Internet connection is down?)") return 1 print("Found Video: \"{0}\"".format(video_info.title)) print("Searching for a video url: {0}p ({1})".format(qchoice.unify(args.quality),args.avc)) if (args.verbose): print("Requested FMT: [{0}]".format(",".join(str(k) for k in fmt_request))) print("Available FMT: [{0}]".format(",".join(str(k) for k in video_info.urlmap.keys()))) for fmt in fmt_request: if fmt in video_info.urlmap: url = video_info.fmt_url(fmt) break else: print("ERROR: Could not find a video url matching your request. maybe try another profile?") return 1 if args.verbose: print("Found FMT: {0} ({1})".format(fmt,profiles.descriptions[fmt])) else: print("Found a Video URL: {0}".format(profiles.descriptions[fmt])) #Subtitles subtitle_file="" if args.sub: print("Looking for Subtitles",end="\r") tracks = getSubTracks(args.id) if len(tracks)<1: print("No Subtitles Found! ") else: track = tracks[0] print("Enabling Subtitles: "+track.lang_original) srtfile = TempFile("afpSubtitle_",".srt") srtfile.write(track.getSRT()) srtfile.unlock() subtitle_file = srtfile.name #XSPF File if args.xspf: from libyo.xspf.simple import Playlist,Track xspf = Playlist(video_info.title) xspf.append(Track(video_info.title,video_info.uploader,uri=url)) xspf[0].annotation = video_info.description xspf[0].image = "http://s.ytimg.com/vi/{0}/default.jpg".format(video_info.video_id) xspf[0].info = "http://www.youtube.com/watch?v={0}".format(video_info.video_id) temp = TempFile("afp_",".xspf") xspf.write(temp) fn=temp.name if args.verbose: print("XSPF Filename: "+fn) temp.unlock() else: fn=url argv = map(uni.u,shlex.split(uni.nativestring(args.command))) for pair in [("\0",""), ("%u",fn), ("%s",subtitle_file), ("%n",video_info.title), #("%a",video_info.uploader), ("%e",profiles.file_extensions[fmt]), ("%f","{0}.{1}".format(tofilename(video_info.title),profiles.file_extensions[fmt]))]: argv = lreplace(argv,*pair) if args.quiet: out_fp=open(os.devnull,"w") else: print("calling '{0}'".format(" ".join(argv))) out_fp=None print() subprocess.call(argv,stdout=out_fp,stderr=out_fp) if args.xspf: temp.dispose() return 0
def _recursive_resolve(video_id,resolve_order): umap=resolve3(video_id).urlmap for i in resolve_order: if i in umap: return umap[i],i
def _download(args,meta,target,fmt_list,video_item): try: video_title = video_item["title"] video_id = video_item["id"] if video_id == "": print("[VIDEO] Found Deleted Video in Playlist. please clean up!") return print("[VIDEO] Found new Video: \"{0}\" (ID='{1}')".format(video_title,video_id)) print("[VIDEO] Preparing to Download...",end="\r") try: url,fmt = _recursive_resolve(video_id,fmt_list) except YouTubeResolveError: print("[VIDEO] Video could not be resolved.") return print("[VIDEO] Downloading with Quality level {0}".format(fmtdesc[fmt])) except Exception: import traceback print("-"*40) print("Exception while Resolving Video:") if args.verbose: traceback.print_exc(limit=None,chain=True) else: print("".join(traceback.format_exception_only(*sys.exc_info()[:2])),end="") print("-"*40) return meta if not args.dummy: video = resolve3(video_id) filename = tofilename(video.title)+"."+fmtext[fmt] path = target fullpath = os.path.join(path,filename) progress = SimpleFileProgress("{position}/{total} {bar} {percent} {speed} ETA: {eta}") retry = 0 while retry<5: try: downloadFile(url,fullpath,progress,2,bytecount) except Exception: import traceback traceback.print_exception(*sys.exc_info()) #print("[ERROR] " + "".join(traceback.format_exception_only(*sys.exc_info()[:2]))) retry+=1 else: break else: print("[ERROR] Cannot Download. Continuing") return meta meta["items"].append(video_id) meta["local"].append(video_item) idx = meta["local"].index(video_item) meta["local_id"][video_id] = idx meta["local_title"][video_title] = idx meta["downloads"][video_id] = { "path": fullpath, "location": path, "filename": filename, "type": fmtext[fmt], "fmt": fmt, "quality": fmtdesc[fmt] } else: print("[ URL ] '{0}'".format(url)) return meta