apkreader.js
2.96 KB
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
115
116
117
118
119
'use strict'
const Zip = require('yauzl')
const Promise = require('bluebird')
const ManifestParser = require('./apkreader/parser/manifest')
const BinaryXmlParser = require('./apkreader/parser/binaryxml')
class ApkReader {
static open(apk) {
return Promise.resolve(new ApkReader(apk))
}
constructor(apk) {
this.apk = apk
}
_open() {
return Promise.fromCallback(callback => {
return Zip.open(this.apk, {lazyEntries: true}, callback)
})
}
usingFile(file, action) {
return this.usingFileStream(file, function(stream) {
let errorListener, readableListener, endListener
const read = () => new Promise(function(resolve, reject) {
const chunks = []
let totalLength = 0
const tryRead = function() {
let chunk
while ((chunk = stream.read())) {
chunks.push(chunk)
totalLength += chunk.length
}
}
readableListener = () => tryRead()
errorListener = err => {
stream.destroy()
reject(err)
}
endListener = () => resolve(Buffer.concat(chunks, totalLength))
stream.on('readable', readableListener)
stream.on('error', errorListener)
stream.on('end', endListener)
tryRead()
})
return read().then(action).finally(function() {
stream.removeListener('readable', readableListener)
stream.removeListener('error', errorListener)
stream.removeListener('end', endListener)
})
})
}
usingFileStream(file, action) {
return this._open().then(function(zipfile) {
let entryListener, errorListener, endListener
const find = () => new Promise(function(resolve, reject) {
entryListener = entry => {
if (entry.fileName === file) {
return resolve(Promise.fromCallback(callback => {
zipfile.openReadStream(entry, callback)
}))
}
zipfile.readEntry()
}
endListener = () => {
reject(new Error(`APK does not contain '${file}'`))
}
errorListener = err => reject(err)
zipfile.on('entry', entryListener)
zipfile.on('end', endListener)
zipfile.on('error', errorListener)
zipfile.readEntry()
})
return find().then(action).finally(function() {
zipfile.removeListener('entry', entryListener)
zipfile.removeListener('error', errorListener)
zipfile.removeListener('end', endListener)
zipfile.close()
})
})
}
readContent(path) {
return this.usingFile(path, content => content)
}
readManifest(options = {}) {
return this.usingFile(ApkReader.MANIFEST, content => {
return new ManifestParser(content, options).parse()
})
}
readXml(path, options = {}) {
return this.usingFile(path, content => {
return new BinaryXmlParser(content, options).parse()
})
}
}
ApkReader.MANIFEST = 'AndroidManifest.xml'
module.exports = ApkReader