-
Notifications
You must be signed in to change notification settings - Fork 0
/
temp.js
114 lines (102 loc) · 2.84 KB
/
temp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
const puppeteer = require('puppeteer')
const fs = require('fs')
const moment = require("moment")
const find = require('find')
const TMP_PATH = "./tmp"
if (!fs.existsSync(TMP_PATH)){
fs.mkdirSync(TMP_PATH)
}
////
/// Make sure to call
///
/// await page._client.send('Page.setDownloadBehavior', {behavior: 'allow', downloadPath: TMP_PATH});
////
function getFileNameFromHeader(dispo) {
var temp = dispo
var idx = temp.indexOf("filename=")
if (idx < 0) {
return ""
}
temp = temp.substr(idx + 10, temp.length - idx - 10)
idx = temp.indexOf(`"`)
if (idx < 0) {
return ""
}
temp = temp.substr(0, idx)
return temp
}
async function waitForFiledownload(timeout) {
const waitObj = {
status:null,
destPath:null,
timestamp:moment()
}
const downFolder = TMP_PATH
const client = await this.page.target().createCDPSession();
await client.send('Network.enable');
let waitInterval = null
const findFileDownloaded = (fileName) => {
var idx = fileName.lastIndexOf(".")
if (idx > 0) {
fileName = fileName.substr(0, idx)
}
return new Promise((resolve, reject) => {
var cont = true
find.file(new RegExp(`${fileName}.*`), downFolder , function(files) {
if (!cont) {
return
}
for (const file of files) {
const stats = fs.statSync(file)
if (stats.isFile()) {
const mTime = moment(stats["mtime"])
if (mTime.isAfter(waitObj.timestamp)) {
resolve(file)
cont = false
return
}
}
}
resolve(false)
})
})
}
const doResolve = async (resolve, destPath) => {
waitObj.status = "ok"
waitObj.destPath = destPath
if (waitInterval) {
clearInterval(waitInterval)
waitInterval = null
}
resolve(waitObj)
}
console.log(`waitForFileDownload ${timeout}`)
return new Promise(async (resolve, reject) => {
setTimeout(async function () {
if (waitInterval) {
clearInterval(waitInterval)
waitInterval = null
}
waitObj.status = "error_timeout"
await client.send('Network.disable');
reject(waitObj)
}, timeout)
client.on('Network.responseReceived', async (param) => {
const respHeaders = param.response.headers
if (respHeaders && respHeaders["Content-Disposition"]) {
const fileName = getFileNameFromHeader(respHeaders["Content-Disposition"])
console.log(`responseReceived ${fileName} `)
if (!waitInterval) {
waitInterval = setInterval(async function() {
// check file exist
const exist = await findFileDownloaded(fileName, waitObj.timestamp)
if (exist) {
await client.send('Network.disable');
doResolve(resolve, exist)
}
}, 500)
}
}
})
})
}