Beispiel #1
0
#!/usr/bin/env python

from metaWrapper import watchEpisode
import sys, json

eid = json.load(open(sys.argv[1]))["eid"]

watchEpisode(eid)
Beispiel #2
0
def mplay(argv, latest=None, queue=None, t_name=None, offline=None):
    if not latest:
        if not t_name:
            ctime = []
            def wfunction(*argv):
                for f in argv[2]:
                    if os.path.isdir(f): continue
                    if os.path.splitext(f)[1] != '.mp4': continue
                    fpath=os.path.join(argv[1],f)
                    ctime.append((fpath,os.stat(fpath).st_ctime))

            def sort_cmp(a,b):
                if a[1] > b[1]: return 1
                elif a[1] == b[1]: return 0
                else: return -1
            os.path.walk(config.wrkdir, wfunction, None)
            ctime.sort(cmp=sort_cmp)
            try:
                latest = ctime[-1][0]
            except IndexError:
                print "There is no fetched episodes"
                sys.exit(1)
        else:
            t_dir = os.path.join(config.wrkdir, t_name)
            series = filter(lambda a: re.match(".*\.mp4",a), os.listdir(t_dir))
            series.sort()
            latest = os.path.join(t_dir,series[0])


    srt = os.path.splitext(latest)[0]+'.srt'

    try:
        metadata = metaWrapper.load_saved_meta(os.path.splitext(latest)[0]+'.meta')
    except IOError:
        print "Seems fetcher is not ready yet"
        return None

    args = [
            "mpv",
            latest,
            "-sub-file",
            srt,
            '-term-status-msg',
            "POSITION: |${=time-pos}|"
            ]
    args.extend(argv[1:])
    if metadata.has_key("lastpos"):
        if metadata["lastpos"] < 0:
            metadata["lastpos"] = 0
        args.extend(["-start", str(metadata["lastpos"])])

    devnull=open(os.devnull, "w")
    tmp = tempfile.NamedTemporaryFile()
    if queue: queue.put_nowait({"tmpfile": tmp.name})
    """
    tee = subprocess.Popen(["tee", tmp.name], stdin=subprocess.PIPE,
            stdout=devnull
            )
"""
    #p = Popen(args, stderr=tmp, stdout=devnull, close_fds=True)
    p = Popen(args, stderr=tmp, stdout=devnull)
    if queue: queue.put_nowait({"pid": p.pid})
    pid, sts = os.waitpid(p.pid, 0)
    tmp.flush()
    tmp.seek(0)
    quit_position=[0]
    l = tmp.readlines()
    if len(l) > 0:
        l = l[-1].strip()
        match = re.match("POSITION: \|(.*)\|", l)
        if match:
            quit_position = match.groups()
        """
    for l in tmp.readlines():
        if len(l.split(u'\033[J\r')) > 1:
            match = re.match("POSITION:\s|(.*)|", l.split(u'\033[J\r')[-2])
    """
    tmp.close()

    fd = open(os.path.splitext(latest)[0]+'.meta', "w+")
    metadata["lastpos"]=float(quit_position[0]) - 5
    fd.write(json.dumps(metadata))
    fd.close()


    if float(quit_position[0])/float(metadata["duration"]) > 0.98:
        response = metaWrapper.watchEpisode(metadata["eid"], offline=offline)
        if response == {'page': ''}:
            print '\n\nEpisode has been watched'
            print 'Cleanup...'
            for e in ('.meta','.mp4', '.srt', '.log'):
                try:
                    os.remove(os.path.splitext(latest)[0]+e)
                except OSError: pass
            if queue: queue.put({"cleaned_up":True})
            if not offline:
                print listunseen()
    if queue: queue.put({"pos":float(quit_position[0])})
    #tee.stdin.close()
    return float(quit_position[0])
Beispiel #3
0
def main(argv):
		if not os.path.isdir(config.wrkdir): os.mkdir(config.wrkdir)
		os.chdir(config.wrkdir)
		quality=config.quality
		playargs=[]
		play=False
		offline=False
		offlineplay=False
		proxy=False
		if "-lq" in argv:
				quality = "default"
				argv.pop(argv.index("-lq"))
		if "-hq" in argv:
				quality = "hq"
				argv.pop(argv.index("-hq"))
		if "-proxy" in argv:
				proxy = True
				argv.pop(argv.index("-proxy"))
		if len(argv) > 1 and argv[1] == 'unseen':
				print listunseen()
				sys.exit(0)
		if "-sub_lang" in argv:
				ix = argv.index("-sub_lang")
				argv.pop(ix)
				config.sub_lang = argv.pop(ix)
		if "play" in argv:
				play=True
				playindex=argv.index("play")
				for i in range(playindex, len(argv)):
						playargs.append(argv.pop(playindex))
				playargs.pop(0)
		if "offline" in argv:
				offline=True
				offindex = argv.index("offline")
				offnum = 0
				if len(argv) > 3:
						offnum = argv[offindex+1]
						argv.pop(offindex)
				argv.pop(offindex)
		if "offlineplay" in argv:
				offlineplay=True
				playindex=argv.index("offlineplay")
				for i in range(playindex, len(argv)):
						playargs.append(argv.pop(playindex))
				playargs.pop(0)

		if "viewmap" in argv:
				from viewmap import viewmap
				viewmap()
				sys.exit(0)

		if "fullunseen" in argv:
				import viewmap
				viewmap.listunseen()
				sys.exit(0)

		if "compactunseen" in argv:
				for e in listunseen(retlist=True):
						print e[1]
				sys.exit(0)

		if len(argv) == 1:
				turboplay.mplay(playargs)
				sys.exit(0)

				tr = filter(lambda a: a[0]==3, listunseen(retlist=True))
				r = Random()
				t_name = r.choice(tr)[1]

		if len(argv) == 2:
				selfname, t_name = argv

		else: usage(argv[0])
		if not os.path.isdir(os.path.join(config.wrkdir,t_name)): os.mkdir(os.path.join(config.wrkdir,t_name))

		play_th = threading.Thread(target=lambda a: a)
		fetch_th = threading.Thread(target=lambda a: a)
		play_queue = Queue.Queue()
		fetch_queue = Queue.Queue()
		mplayer_pid = None

		logfd = sys.stdout

		if not offlineplay:
				try:
						f = open(config.offline_store)
						d = pickle.load(f)
						f.close()
				except IOError:
						d = []
				td = list(d)
				for e in td:
						r = watchEpisode(e["eid"])
						if r == {'page': ''}:
								d.pop(d.index(e))
				f = open(config.offline_store,"w+")
				pickle.dump(d,f)
				f.close()
		if play:
				fetch_done = False
				metadata_fetch_done = False
				sub_fetch_done = False
				pos = nprobes = average = asize = 0
				tmpfilename = None

				while True:
						"""
						if play_th.is_alive() and mplayer_pid and tmpfilename:
								hangmon(tmpfilename, mplayer_pid) """

						if not metadata_fetch_done:
								try:
										metadata, file_base = get_metadata(t_name, quality)
										quality = metadata["fetched_quality"]
										metadata_fetch_done = True
										print "Got metadata" # metadata
								except NoMoreSeries:
										print "No more series"
										sys.exit(0)

						if not sub_fetch_done:
								try:
										if metadata_fetch_done:
												fetch_sub(metadata["subtitles"]["sources"][config.sub_lang], file_base+".srt")
												print "Got subtitles"
								except KeyError:
										print "Subtitles not found"
								sub_fetch_done = True

						if not fetch_th.is_alive() and not fetch_done:
								if metadata_fetch_done:
										fetch_th = threading.Thread(target=pfetcher, args=(metadata, file_base,
												quality),
												kwargs={"silent":False, "queue" : fetch_queue})
										fetch_th.daemon = True
										fetch_th.start()
										#time.sleep(config.wait_time*10)

						if not fetch_queue.empty():
								fetch_done = fetch_queue.get()

						if not play_queue.empty():
								obj = play_queue.get()
								if obj.has_key("pos"): pos = obj["pos"]
								if obj.has_key("tmpfile"): tmpfilename = obj["tmpfile"]
								if obj.has_key("pid"): mplayer_pid = obj["pid"]
								if obj.has_key("cleaned_up"):
										fetch_done = False
										sub_fetch_done = False
										metadata_fetch_done = False
										continue

						if not play_th.is_alive() and os.path.exists(file_base+".mp4") and os.stat(file_base+".mp4").st_size > 0:
								play_th = threading.Thread(target=turboplay.mplay, args=(playargs,),
												kwargs={"latest": file_base+".mp4",
														"queue":play_queue})
								play_th.start()
								print "Playing: \n%s Season %s Episode %s" % (t_name,
										metadata["season"], metadata["number"])
						time.sleep(config.wait_time)

		elif offline:
				offset = 0
				while offnum > offset or offnum == 0:
						metadata, file_base = get_metadata(t_name, quality, offset=offset)
						print "Fetching for offline: \n%s Season %s Episode %s" % (t_name,
								metadata["season"], metadata["number"])
						try:
								fetch_sub(metadata["subtitles"]["sources"][config.sub_lang], file_base+".srt")
						except KeyError:
								print "Subtitles not found"
						pfetcher(metadata, file_base, quality)
						offset += 1
						#print t_name, metadata["season"], metadata["number"]
					
		elif offlineplay:
				while True:
						turboplay.mplay(playargs, t_name=t_name, offline=True)
		else:
				metadata, file_base = get_metadata(t_name, quality)
				print "Got metadata" # metadata

				try:
						fetch_sub(metadata["subtitles"]["sources"][config.sub_lang], file_base+".srt")
						print "Got subtitles"
				except KeyError:
						print "Subtitles not found"
				pfetcher(metadata, file_base, quality)