BirdyNet/addons/0.pageDownloader.py

57 lines
1.6 KiB
Python
Raw Normal View History

2021-03-18 15:22:56 +00:00
global urllib
import urllib.request
global downloadPage
2021-03-20 19:02:05 +00:00
def downloadPage(window,downloadId,url,headers = False):
global browserWindowsLock
global browserWindows
2021-03-18 15:22:56 +00:00
if not headers: headers = {}
2021-03-20 15:41:10 +00:00
response = {
"url": url,
2021-03-20 19:02:05 +00:00
"body": "",
2021-03-20 15:41:10 +00:00
"headers": []
}
2021-03-20 16:23:38 +00:00
class rdrh(urllib.request.HTTPRedirectHandler):
def redirect_request(self,req,fp,code,msg,hdrs,newurl):
response["url"] = newurl
2021-03-20 16:57:46 +00:00
try:
return urllib.request.HTTPRedirectHandler.redirect_request(self, req, fp, code, msg, hdrs, newurl)
except urllib.error.HTTPError as e:
return e
2021-03-20 16:23:38 +00:00
opener = urllib.request.build_opener(rdrh)
2021-03-20 17:54:23 +00:00
opener.addheaders = headers
2021-03-20 16:23:38 +00:00
2021-03-18 15:22:56 +00:00
try:
2021-03-20 16:57:46 +00:00
requestHandler = opener.open(url)
# Check whether to transfer the page to the viewer, or if to open downloader
2021-03-20 15:41:10 +00:00
response["headers"] = requestHandler.getheaders()
contentType, contentTypeArguments = getContentType(response["headers"],"application/octet-stream")
if not contentType.startswith("text/"): # Make the fileDownloader handle the request instead
return
2021-03-20 15:41:10 +00:00
response["body"] = requestHandler.read()
requestHandler.close()
2021-03-18 15:22:56 +00:00
except urllib.error.HTTPError as e:
2021-03-20 15:41:10 +00:00
response["body"] = e.read()
requestHandler.close()
2021-03-20 15:41:10 +00:00
except Exception as e:
response["body"] = str(e).encode("utf-8")
response["headers"] = [["content-type","text; charset=utf-8"]]
2021-03-18 15:22:56 +00:00
2021-03-20 19:02:05 +00:00
browserWindowsLock.acquire()
if not window in browserWindows:
browserWindowsLock.release()
return
window.cTaskLock.acquire()
if window.cDownloadId != downloadId:
window.cTaskLock.release()
browserWindowsLock.release()
return
window.cTasks.append((window.cHandleResponse,[response],{}))
window.cTaskLock.release()
browserWindowsLock.release()