支持api获取状态

This commit is contained in:
2019-04-07 15:30:57 +08:00
committed by JerryYan
parent f8d4be5385
commit b9b0994f4c
6 changed files with 300 additions and 106 deletions

View File

@ -2,71 +2,14 @@ import shutil
import sys
import time
from datetime import datetime
import queue
import threading
from config import config
from api import XiGuaLiveApi
from bilibili import *
from Common import *
import os
import requests
q = queue.Queue()
base_uri = ""
isEncode = False
isDownload = False
uq = queue.Queue()
eq = queue.Queue()
class downloader(XiGuaLiveApi):
files = []
playlist: str = None
def updRoomInfo(self):
super(downloader, self).updRoomInfo()
if self.isLive:
self.updPlayList()
else:
print("未开播,等待开播")
self.files = []
def updPlayList(self):
if self.isLive:
if "stream_url" in self._rawRoomInfo:
if self.playlist is None:
self.apiChangedError("无法获取直播链接")
self.playlist = False
else:
self.playlist = self._rawRoomInfo["stream_url"]["flv_pull_url"]
self.playlist = self.playlist.replace("_uhd", "").replace("_sd", "").replace("_ld", "")
def onLike(self, user):
pass
def onAd(self, i):
pass
def onChat(self, chat):
pass
def onEnter(self, msg):
pass
def onJoin(self, user):
pass
def onLeave(self, json):
self.updRoomInfo()
def onMessage(self, msg):
pass
def onPresent(self, gift):
pass
def onPresentEnd(self, gift):
pass
def onSubscribe(self, user):
pass
def download(url):
@ -74,38 +17,42 @@ def download(url):
path = datetime.strftime(datetime.now(), "%Y%m%d_%H%M.flv")
p = requests.get(url, stream=True)
if p.status_code != 200:
print("{} : Download Response 404 ,will stop looping".format(datetime.strftime(datetime.now(), "%y%m%d %H%M")))
appendDownloadStatus("Download [{}] Response 404 ,will stop looping".format(url))
return True
isDownload = True
print("{} : Download {}".format(datetime.strftime(datetime.now(), "%y%m%d %H%M"), path))
appendDownloadStatus("Starting Download >{}<".format(path))
f = open(path, "wb")
try:
for t in p.iter_content(chunk_size=64 * 1024):
if t:
f.write(t)
if os.path.getsize(path) > 1024 * 1024 * 1024 * 1.5:
_size = os.path.getsize(path)
modifyLastDownloadStatus("Download >{}< @ {:.2f}%".format(path, 100.0 * _size/config["size"]))
if _size > config["size"]:
break
print("{} : Download Quiting".format(datetime.strftime(datetime.now(), "%y%m%d %H%M")))
modifyLastDownloadStatus("Finished Download >{}<".format(path))
except Exception as e:
print("{} : Download Quiting With Exception {}".format(datetime.strftime(datetime.now(), "%y%m%d %H%M"),
appendError("Download >{}< With Exception {}".format(path, datetime.strftime(datetime.now(), "%y%m%d %H%M"),
e.__str__()))
f.close()
isDownload = False
if os.path.getsize(path) == 0:
os.remove(path)
return False
eq.put(path)
encodeQueue.put(path)
download(url)
def encode():
global isEncode
while True:
i = eq.get()
i = encodeQueue.get()
if os.path.exists(i):
isEncode = True
os.system("ffmpeg -i {} -c:v copy -c:a copy -f mp4 {}".format(i, i[:13] + ".mp4"))
uq.put(i[:13] + ".mp4")
appendEncodeStatus("Start Encoding >{}<".format(i))
os.system("ffmpeg -i {} -c:v copy -c:a copy -f mp4 {} -y".format(i, i[:13] + ".mp4"))
uploadQueue.put(i[:13] + ".mp4")
modifyLastEncodeStatus("Finished Encoding >{}<".format(i))
if config["mv"]:
shutil.move(i, config["mtd"])
elif config["del"]:
@ -114,51 +61,45 @@ def encode():
def upload(date=datetime.strftime(datetime.now(), "%Y_%m_%d")):
print("{} : Upload Daemon Starting".format(datetime.strftime(datetime.now(), "%y%m%d %H%M")))
i = uq.get()
i = uploadQueue.get()
while True:
if isinstance(i, bool):
print("{} : Upload Daemon Receive Command {}"
.format(datetime.strftime(datetime.now(), "%y%m%d %H%M"), i))
if i is True:
print("自动投稿中,请稍后")
appendUploadStatus("[{}]自动投稿中,请稍后".format(config["t_t"].format(date)))
b.finishUpload(config["t_t"].format(date), 17, config["tag"], config["des"],
source=config["src"], no_reprint=0)
b.clear()
break
print("{} : Upload {}".format(datetime.strftime(datetime.now(), "%y%m%d %H%M"), i))
if not os.path.exists(i):
print("{} : Upload File Not Exist {}".format(datetime.strftime(datetime.now(), "%y%m%d %H%M"), i))
i = uq.get()
appendError("Upload File Not Exist {}".format(i))
i = uploadQueue.get()
continue
try:
b.preUpload(VideoPart(i, os.path.basename(i)))
except:
continue
except Exception as e:
appendError(e.__str__())
os.remove(i)
i = uq.get()
i = uploadQueue.get()
print("{} : Upload Daemon Quiting".format(datetime.strftime(datetime.now(), "%y%m%d %H%M")))
appendUploadStatus("Upload Daemon Quiting")
b = Bilibili()
b.login(config["b_u"], config["b_p"])
if __name__ == "__main__":
name = config["l_u"]
print("西瓜直播录播助手 by JerryYan")
def run(name):
global isEncode, isDownload
api = downloader(name)
print("进入", api.roomLiver, "的直播间")
if not api.isValidRoom:
input("房间不存在")
sys.exit()
print("=" * 30)
d = datetime.strftime(datetime.now(), "%Y_%m_%d")
t = threading.Thread(target=download)
ut = threading.Thread(target=upload, args=(d,))
et = threading.Thread(target=encode, args=())
et.setDaemon(True)
et.start()
if not api.isValidRoom:
appendError("[{}]房间不存在".format(name))
return
d = None
t = threading.Thread(target=download)
ut = threading.Thread(target=upload, args=(d,))
_count = 0
_count_error = 0
while True:
@ -185,7 +126,7 @@ if __name__ == "__main__":
_count = 0
_count_error = 0
except Exception as e:
print(e.__str__())
appendError(e.__str__())
time.sleep(20)
_count_error += 1
continue
@ -197,15 +138,13 @@ if __name__ == "__main__":
if d is not None:
d = None
if not isEncode and not isDownload:
uq.put(True)
uploadQueue.put(True)
isEncode = True
isDownload = True
del config
from config import config
# print("主播未开播等待1分钟后重试")
time.sleep(60)
try:
api.updRoomInfo()
_count_error = 0
except Exception as e:
print(e.__str__())
appendError(e.__str__())