something

This commit is contained in:
恍兮惚兮 2024-09-04 19:30:06 +08:00
parent c5a94b4674
commit ccbbd2a02b
9 changed files with 80 additions and 47 deletions

View File

@ -4,16 +4,13 @@ from ctypes import c_long, cast, pointer, POINTER, c_char
from requests import ResponseBase, Timeout, Requester_common from requests import ResponseBase, Timeout, Requester_common
from traceback import print_exc from traceback import print_exc
class Response(ResponseBase): class Response(ResponseBase):
def __init__(self, stream=False): def __init__(self, stream=False):
super().__init__(stream) super().__init__(stream)
self.last_error = 0
self.keeprefs = [] self.keeprefs = []
self.queue = queue.Queue() self.queue = queue.Queue()
def iter_content_impl(self, chunk_size=1): def iter_content_impl(self, chunk_size=1):
downloadeddata = b"" downloadeddata = b""
@ -36,9 +33,6 @@ class Response(ResponseBase):
yield downloadeddata[:chunk_size] yield downloadeddata[:chunk_size]
downloadeddata = downloadeddata[chunk_size:] downloadeddata = downloadeddata[chunk_size:]
def raise_for_status(self):
MaybeRaiseException(self.last_error)
class autostatus: class autostatus:
def __init__(self, ref) -> None: def __init__(self, ref) -> None:
@ -63,22 +57,18 @@ class Requester(Requester_common):
curl_easy_setopt(curl, CURLoption.USERAGENT, self.default_UA.encode("utf8")) curl_easy_setopt(curl, CURLoption.USERAGENT, self.default_UA.encode("utf8"))
return curl return curl
def raise_for_status(self):
MaybeRaiseException(self.last_error)
def _getStatusCode(self, curl): def _getStatusCode(self, curl):
status_code = c_long() status_code = c_long()
self.last_error = curl_easy_getinfo( MaybeRaiseException(
curl, CURLINFO.RESPONSE_CODE, pointer(status_code) curl_easy_getinfo(curl, CURLINFO.RESPONSE_CODE, pointer(status_code))
) )
self.raise_for_status()
return status_code.value return status_code.value
def _set_proxy(self, curl, proxy): def _set_proxy(self, curl, proxy):
if proxy: if proxy:
self.last_error = curl_easy_setopt( MaybeRaiseException(
curl, CURLoption.PROXY, proxy.encode("utf8") curl_easy_setopt(curl, CURLoption.PROXY, proxy.encode("utf8"))
) )
self.raise_for_status()
def _set_verify(self, curl, verify): def _set_verify(self, curl, verify):
if verify == False: if verify == False:
@ -89,8 +79,7 @@ class Requester(Requester_common):
curl_easy_setopt(curl, CURLoption.SSL_VERIFYHOST, 2) curl_easy_setopt(curl, CURLoption.SSL_VERIFYHOST, 2)
def _perform(self, curl): def _perform(self, curl):
self.last_error = curl_easy_perform(curl) MaybeRaiseException(curl_easy_perform(curl))
self.raise_for_status()
def _set_allow_redirects(self, curl, allow_redirects): def _set_allow_redirects(self, curl, allow_redirects):
@ -116,7 +105,7 @@ class Requester(Requester_common):
if _headerb == 0: if _headerb == 0:
break break
elif _headerb == 1: elif _headerb == 1:
self.raise_for_status() raise CURLException()
_headerb = _headerb.decode("utf8") _headerb = _headerb.decode("utf8")
if _headerb.startswith("HTTP/"): if _headerb.startswith("HTTP/"):
header = "" header = ""
@ -131,8 +120,7 @@ class Requester(Requester_common):
lheaders = curl_slist_append( lheaders = curl_slist_append(
cast(lheaders, POINTER(curl_slist)), _.encode("utf8") cast(lheaders, POINTER(curl_slist)), _.encode("utf8")
) )
self.last_error = curl_easy_setopt(curl, CURLoption.HTTPHEADER, lheaders) MaybeRaiseException(curl_easy_setopt(curl, CURLoption.HTTPHEADER, lheaders))
self.raise_for_status()
if cookies: if cookies:
cookie = self._parsecookie(cookies) cookie = self._parsecookie(cookies)
@ -176,8 +164,7 @@ class Requester(Requester_common):
if method == "HEAD": if method == "HEAD":
curl_easy_setopt(curl, CURLoption.NOBODY, 1) curl_easy_setopt(curl, CURLoption.NOBODY, 1)
curl_easy_setopt(curl, CURLoption.CUSTOMREQUEST, method.encode("utf8")) curl_easy_setopt(curl, CURLoption.CUSTOMREQUEST, method.encode("utf8"))
self.last_error = curl_easy_setopt(curl, CURLoption.URL, url.encode("utf8")) MaybeRaiseException(curl_easy_setopt(curl, CURLoption.URL, url.encode("utf8")))
self.raise_for_status()
curl_easy_setopt(curl, CURLoption.PORT, port) curl_easy_setopt(curl, CURLoption.PORT, port)
self._setheaders(curl, headers, cookies) self._setheaders(curl, headers, cookies)
@ -231,7 +218,7 @@ class Requester(Requester_common):
resp.queue.put(None) resp.queue.put(None)
if error: if error:
print(url) print(url)
self.raise_for_status() raise CURLException()
threading.Thread(target=___perform, daemon=True).start() threading.Thread(target=___perform, daemon=True).start()
@ -244,6 +231,6 @@ class Requester(Requester_common):
resp.headers, resp.cookies = self._parseheader2dict(header) resp.headers, resp.cookies = self._parseheader2dict(header)
resp.status_code = self._getStatusCode(curl) resp.status_code = self._getStatusCode(curl)
resp.url = url
resp.last_error = self.last_error
return resp return resp

View File

@ -42,9 +42,6 @@ class Response(ResponseBase):
yield downloadeddata[:chunk_size] yield downloadeddata[:chunk_size]
downloadeddata = downloadeddata[chunk_size:] downloadeddata = downloadeddata[chunk_size:]
def raise_for_status(self):
MaybeRaiseException()
class Requester(Requester_common): class Requester(Requester_common):
def request(self, *argc, **kwarg) -> ResponseBase: def request(self, *argc, **kwarg) -> ResponseBase:
@ -183,6 +180,7 @@ class Requester(Requester_common):
resp.headers, resp.cookies = self._parseheader2dict(self._getheaders(hRequest)) resp.headers, resp.cookies = self._parseheader2dict(self._getheaders(hRequest))
resp.status_code = self._getStatusCode(hRequest) resp.status_code = self._getStatusCode(hRequest)
resp.url = url
if stream: if stream:
resp.hSession = self.hSession resp.hSession = self.hSession
resp.hconn = hConnect resp.hconn = hConnect
@ -204,7 +202,6 @@ class Requester(Requester_common):
if succ == 0: if succ == 0:
MaybeRaiseException() MaybeRaiseException()
downloadeddata += buff[: downloadedSize.value] downloadeddata += buff[: downloadedSize.value]
resp.content = self.decompress(downloadeddata, resp.headers) resp.content = self.decompress(downloadeddata, resp.headers)
return resp return resp

View File

@ -49,17 +49,22 @@
ele.style.fontWeight = args.bold ? "bold" : "" ele.style.fontWeight = args.bold ? "bold" : ""
ele.style.textAlign = args.atcenter ? "center" : "" ele.style.textAlign = args.atcenter ? "center" : ""
} }
function maybesethtml(ele, args, text) {
if (args.userawhtml)
ele.innerHTML = text
else
ele.innerText = text
}
function normal_create_internal(styleargs, text, args) { function normal_create_internal(styleargs, text, args) {
let ele = document.createElement('div') let ele = document.createElement('div')
maybesethtml(ele, args, text)
ele.innerText = text
ele.style.color = args.color ele.style.color = args.color
commoninit_font_align_height(ele, args) commoninit_font_align_height(ele, args)
return ele return ele
} }
function yinying_create_internal(styleargs, text, args) { function yinying_create_internal(styleargs, text, args) {
let ele = document.createElement('div') let ele = document.createElement('div')
ele.innerText = text maybesethtml(ele, args, text)
ele.style.color = styleargs.fillcolor ele.style.color = styleargs.fillcolor
commoninit_font_align_height(ele, args) commoninit_font_align_height(ele, args)
@ -81,7 +86,7 @@
function miaobian0_create_internal(styleargs, text, args) { function miaobian0_create_internal(styleargs, text, args) {
let ele = document.createElement('div') let ele = document.createElement('div')
ele.innerText = text maybesethtml(ele, args, text)
ele.style.color = styleargs.fillcolor ele.style.color = styleargs.fillcolor
commoninit_font_align_height(ele, args) commoninit_font_align_height(ele, args)
let _id = _simpleuid() let _id = _simpleuid()
@ -129,13 +134,13 @@
} }
ele.appendChild(style) ele.appendChild(style)
let p = document.createElement('div') let p = document.createElement('div')
p.innerText = text; maybesethtml(p, args, text)
p.classList.add('nostroken') p.classList.add('nostroken')
ele.appendChild(p) ele.appendChild(p)
for (let i = 0; i < 1 + styleargs.trace * 10; i++) { for (let i = 0; i < 1 + styleargs.trace * 10; i++) {
let p = document.createElement('div') let p = document.createElement('div')
p.innerText = text; maybesethtml(p, args, text)
p.classList.add(`stroken${i}`) p.classList.add(`stroken${i}`)
ele.appendChild(p) ele.appendChild(p)
} }
@ -150,6 +155,15 @@
} }
function dispatch_text_style_line(style, styleargs, text, args) { function dispatch_text_style_line(style, styleargs, text, args) {
let ele = regist_style_imp[style](styleargs, text, args); let ele = regist_style_imp[style](styleargs, text, args);
if (args.userawhtml) {
if (args.atcenter) {
let wrap = document.createElement('div')
wrap.style.textAlign = "center"
wrap.appendChild(ele)
return wrap
}
return ele
}
let begin = 0; let begin1 = ""; let begin = 0; let begin1 = "";
let end = text.length - 1; let end1 = ""; let end = text.length - 1; let end1 = "";
for (; (begin < text.length) && (text[begin] == ' '); begin++) { begin1 += "&nbsp;" } for (; (begin < text.length) && (text[begin] == ' '); begin++) { begin1 += "&nbsp;" }
@ -211,7 +225,7 @@
let args = JSON.parse(decodeURIComponent(argsjson)) let args = JSON.parse(decodeURIComponent(argsjson))
let styleargs = JSON.parse(decodeURIComponent(styleargsjson)) let styleargs = JSON.parse(decodeURIComponent(styleargsjson))
let text = decodeURIComponent(textu) let text = decodeURIComponent(textu)
let innerele = dispatch_text_style(style, styleargs, text, { atcenter: args.atcenter, fontFamily: args.fm, fontSize: args.fs, bold: args.bold, color: args.color, lineHeight: args.line_height }) let innerele = dispatch_text_style(style, styleargs, text, args)
let ele = document.getElementById(_id) let ele = document.getElementById(_id)
ele.innerHTML = '' ele.innerHTML = ''
ele.appendChild(innerele) ele.appendChild(innerele)
@ -265,7 +279,7 @@
tag.forEach(word => { tag.forEach(word => {
let eleori = dispatch_text_style_inlineblock(style, styleargs, word.orig, { atcenter: true, fontFamily: fmori, fontSize: fsori, bold: boldori, color: color, lineHeight: line_height }) let eleori = dispatch_text_style_inlineblock(style, styleargs, word.orig, { atcenter: true, fontFamily: fmori, fontSize: fsori, bold: boldori, color: color, lineHeight: line_height })
if ((isshow_fenci || isfenciclick) && word.hira.trim().length) { if ((isshow_fenci || isfenciclick) && word.hira.trim().length) {
let div = document.createElement('div') let div = document.createElement('div')
div.style.display = 'inline-block' div.style.display = 'inline-block'
div.id = _simpleuid() div.id = _simpleuid()

View File

@ -68,7 +68,7 @@ class TextBrowser(QWidget, dataget):
self.masklabel_top = QLabel(self) self.masklabel_top = QLabel(self)
self.masklabel_top.setMouseTracking(True) self.masklabel_top.setMouseTracking(True)
# self.masklabel_bottom.setStyleSheet('background-color:red') # self.masklabel_bottom.setStyleSheet('background-color:red')
self.saveclickfunction={} self.saveclickfunction = {}
self.masklabel = QLabel(self.webivewwidget) self.masklabel = QLabel(self.webivewwidget)
self.masklabel.setMouseTracking(True) self.masklabel.setMouseTracking(True)
self.webivewwidget.navigate( self.webivewwidget.navigate(
@ -205,7 +205,7 @@ class TextBrowser(QWidget, dataget):
) )
def calllunaclickedword(self, wordinfo): def calllunaclickedword(self, wordinfo):
clickfunction= wordinfo.get('clickfunction',None) clickfunction = wordinfo.get("clickfunction", None)
if clickfunction: if clickfunction:
self.saveclickfunction.get(clickfunction)(False) self.saveclickfunction.get(clickfunction)(False)
else: else:
@ -250,7 +250,7 @@ class TextBrowser(QWidget, dataget):
]["webview"][0] ]["webview"][0]
return currenttype return currenttype
def _webview_append(self, _id, origin, atcenter, text, tag, flags, color): def _webview_append(self, _id, origin, atcenter, text: str, tag, flags, color):
fmori, fsori, boldori = self._getfontinfo(origin) fmori, fsori, boldori = self._getfontinfo(origin)
fmkana, fskana, boldkana = self._getfontinfo_kana() fmkana, fskana, boldkana = self._getfontinfo_kana()
@ -287,17 +287,28 @@ class TextBrowser(QWidget, dataget):
if clickfunction: if clickfunction:
func = "luna" + str(uuid.uuid4()).replace("-", "_") func = "luna" + str(uuid.uuid4()).replace("-", "_")
_tag["clickfunction"] = func _tag["clickfunction"] = func
self.saveclickfunction[func]=clickfunction self.saveclickfunction[func] = clickfunction
self.create_internal_rubytext(style, styleargs, _id, tag, args) self.create_internal_rubytext(style, styleargs, _id, tag, args)
else: else:
sig = "LUNASHOWHTML"
userawhtml = text.startswith(sig)
if userawhtml:
text = text[len(sig) :]
else:
if sig in text:
# 显示名称时。不管了,就这样吧
text = text.replace(sig, "")
userawhtml = True
args = dict( args = dict(
atcenter=atcenter, atcenter=atcenter,
fm=fmori, fontFamily=fmori,
fs=fsori, fontSize=fsori,
bold=boldori, bold=boldori,
color=color, color=color,
line_height=line_height, lineHeight=line_height,
userawhtml=userawhtml,
) )
self.create_internal_text(style, styleargs, _id, text, args) self.create_internal_text(style, styleargs, _id, text, args)
def clear(self): def clear(self):

View File

@ -16,6 +16,10 @@ class Timeout(RequestException):
pass pass
class HTTPError(RequestException):
pass
class CaseInsensitiveDict(MutableMapping): class CaseInsensitiveDict(MutableMapping):
def __init__(self, data=None, **kwargs): def __init__(self, data=None, **kwargs):
@ -65,6 +69,7 @@ class ResponseBase:
def __init__(self, stream): def __init__(self, stream):
self.headers = CaseInsensitiveDict() self.headers = CaseInsensitiveDict()
self.stream = stream self.stream = stream
self.url = ""
self.cookies = {} self.cookies = {}
self.status_code = 0 self.status_code = 0
self.__content = b"" self.__content = b""
@ -150,6 +155,22 @@ class ResponseBase:
if pending is not None: if pending is not None:
yield pending yield pending
def raise_for_status(self):
reason = ""
http_error_msg = ""
if 400 <= self.status_code < 500:
http_error_msg = (
f"{self.status_code} Client Error: {reason} for url: {self.url}"
)
elif 500 <= self.status_code < 600:
http_error_msg = (
f"{self.status_code} Server Error: {reason} for url: {self.url}"
)
if http_error_msg:
raise HTTPError(http_error_msg)
class Requester_common: class Requester_common:
Accept_Encoding = "gzip, deflate, br" Accept_Encoding = "gzip, deflate, br"

View File

@ -75,7 +75,7 @@ class TS(basetrans):
"target_lang": self.tgtlang, "target_lang": self.tgtlang,
} }
response = self.proxysession.post(self.config["api"], json=payload) response = self.proxysession.post(self.multiapikeycurrent["api"], json=payload)
try: try:
return response.json()["data"] return response.json()["data"]

View File

@ -41,7 +41,8 @@ class TS(basetrans):
maxsim = 0 maxsim = 0
savet = "{}" savet = "{}"
ret = self.sql.execute("SELECT * FROM artificialtrans ").fetchall() ret = self.sql.execute("SELECT * FROM artificialtrans ").fetchall()
if not ret:
return {}
for line in ret: for line in ret:
text = line[1] text = line[1]
trans = line[2] trans = line[2]
@ -61,6 +62,8 @@ class TS(basetrans):
ret = self.sql.execute( ret = self.sql.execute(
"SELECT machineTrans FROM artificialtrans WHERE source = ?", (content,) "SELECT machineTrans FROM artificialtrans WHERE source = ?", (content,)
).fetchone() ).fetchone()
if not ret:
return {}
try: try:
ret = json.loads(ret[0]) ret = json.loads(ret[0])
except: except:

View File

@ -5,7 +5,7 @@ from myutils.utils import checkmd5reloadmodule
class TS(basetrans): class TS(basetrans):
def mayreinit(self): def mayreinit(self):
isnew, module = checkmd5reloadmodule("./userconfig/selfbuild.py", "selfbuild") isnew, module = checkmd5reloadmodule("./userconfig/selfbuild.py", "selfbuild")
if not isnew: if (not isnew) and self.internal:
return return
if module: if module:
self.internal = module.TS("selfbuild") self.internal = module.TS("selfbuild")

View File

@ -29,7 +29,7 @@ include(generate_product_version)
set(VERSION_MAJOR 5) set(VERSION_MAJOR 5)
set(VERSION_MINOR 33) set(VERSION_MINOR 33)
set(VERSION_PATCH 8) set(VERSION_PATCH 9)
add_library(pch pch.cpp) add_library(pch pch.cpp)
target_precompile_headers(pch PUBLIC pch.h) target_precompile_headers(pch PUBLIC pch.h)