No Description

Blob.js 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. // Copyright 2016 wkh237@github. All rights reserved.
  2. // Use of this source code is governed by a MIT-style license that can be
  3. // found in the LICENSE file.
  4. import RNFetchBlob from '../index.js'
  5. import fs from '../fs.js'
  6. import getUUID from '../utils/uuid'
  7. import Log from '../utils/log.js'
  8. import EventTarget from './EventTarget'
  9. const log = new Log('Blob')
  10. const blobCacheDir = fs.dirs.DocumentDir + '/RNFetchBlob-blobs/'
  11. log.disable()
  12. // log.level(3)
  13. /**
  14. * A RNFetchBlob style Blob polyfill class, this is a Blob which compatible to
  15. * Response object attain fron RNFetchBlob.fetch.
  16. */
  17. export default class Blob extends EventTarget {
  18. cacheName:string;
  19. type:string;
  20. size:number;
  21. isRNFetchBlobPolyfill:boolean = true;
  22. multipartBoundary:string = null;
  23. _ref:string = null;
  24. _blobCreated:boolean = false;
  25. _onCreated:Array<any> = [];
  26. _closed:boolean = false;
  27. /**
  28. * Static method that remove all files in Blob cache folder.
  29. * @nonstandard
  30. * @return {Promise}
  31. */
  32. static clearCache() {
  33. return fs.unlink(blobCacheDir).then(() => fs.mkdir(blobCacheDir))
  34. }
  35. static build(data:any, cType:any):Promise<Blob> {
  36. return new Promise((resolve, reject) => {
  37. new Blob(data, cType).onCreated(resolve)
  38. })
  39. }
  40. get blobPath() {
  41. return this._ref
  42. }
  43. static setLog(level:number) {
  44. if(level === -1)
  45. log.disable()
  46. else
  47. log.level(level)
  48. }
  49. /**
  50. * RNFetchBlob Blob polyfill, create a Blob directly from file path, BASE64
  51. * encoded data, and string. The conversion is done implicitly according to
  52. * given `mime`. However, the blob creation is asynchronously, to register
  53. * event `onCreated` is need to ensure the Blob is creadted.
  54. * @param {any} data Content of Blob object
  55. * @param {any} mime Content type settings of Blob object, `text/plain`
  56. * by default
  57. * @param {boolean} defer When this argument set to `true`, blob constructor
  58. * will not invoke blob created event automatically.
  59. */
  60. constructor(data:any, cType:any, defer:boolean) {
  61. super()
  62. cType = cType || {}
  63. this.cacheName = getBlobName()
  64. this.isRNFetchBlobPolyfill = true
  65. this.isDerived = defer
  66. this.type = cType.type || 'text/plain'
  67. log.verbose('Blob constructor called', 'mime', this.type, 'type', typeof data, 'length', data? data.length:0)
  68. this._ref = blobCacheDir + this.cacheName
  69. let p = null
  70. if(!data)
  71. data = ''
  72. if(data.isRNFetchBlobPolyfill) {
  73. log.verbose('create Blob cache file from Blob object')
  74. let size = 0
  75. this._ref = String(data.getRNFetchBlobRef())
  76. let orgPath = this._ref
  77. p = fs.exists(orgPath)
  78. .then((exist) => {
  79. if(exist)
  80. return fs.writeFile(orgPath, data, 'uri')
  81. .then((size) => Promise.resolve(size))
  82. .catch((err) => {
  83. throw `RNFetchBlob Blob file creation error, ${err}`
  84. })
  85. else
  86. throw `could not create Blob from path ${orgPath}, file not exists`
  87. })
  88. }
  89. // process FormData
  90. else if(data instanceof FormData) {
  91. log.verbose('create Blob cache file from FormData', data)
  92. let boundary = `RNFetchBlob-${this.cacheName}-${Date.now()}`
  93. this.multipartBoundary = boundary
  94. let parts = data.getParts()
  95. let formArray = []
  96. if(!parts) {
  97. p = fs.writeFile(this._ref, '', 'utf8')
  98. }
  99. else {
  100. for(let i in parts) {
  101. formArray.push('\r\n--'+boundary+'\r\n')
  102. let part = parts[i]
  103. for(let j in part.headers) {
  104. formArray.push(j + ': ' +part.headers[j] + '\r\n')
  105. }
  106. formArray.push('\r\n')
  107. if(part.isRNFetchBlobPolyfill)
  108. formArray.push(part)
  109. else
  110. formArray.push(part.string)
  111. }
  112. log.verbose('FormData array', formArray)
  113. formArray.push('\r\n--'+boundary+'--\r\n')
  114. p = createMixedBlobData(this._ref, formArray)
  115. }
  116. }
  117. // if the data is a string starts with `RNFetchBlob-file://`, append the
  118. // Blob data from file path
  119. else if(typeof data === 'string' && data.startsWith('RNFetchBlob-file://')) {
  120. log.verbose('create Blob cache file from file path', data)
  121. this._ref = String(data).replace('RNFetchBlob-file://', '')
  122. let orgPath = this._ref
  123. if(defer)
  124. return
  125. else {
  126. p = fs.stat(orgPath)
  127. .then((stat) => {
  128. return Promise.resolve(stat.size)
  129. })
  130. }
  131. }
  132. // content from variable need create file
  133. else if(typeof data === 'string') {
  134. let encoding = 'utf8'
  135. let mime = String(this.type)
  136. // when content type contains application/octet* or *;base64, RNFetchBlob
  137. // fs will treat it as BASE64 encoded string binary data
  138. if(/(application\/octet|\;base64)/i.test(mime))
  139. encoding = 'base64'
  140. else
  141. data = data.toString()
  142. // create cache file
  143. this.type = String(this.type).replace(/;base64/ig, '')
  144. log.verbose('create Blob cache file from string', 'encode', encoding)
  145. p = fs.writeFile(this._ref, data, encoding)
  146. .then((size) => {
  147. return Promise.resolve(size)
  148. })
  149. }
  150. // TODO : ArrayBuffer support
  151. // else if (data instanceof ArrayBuffer ) {
  152. //
  153. // }
  154. // when input is an array of mixed data types, create a file cache
  155. else if(Array.isArray(data)) {
  156. log.verbose('create Blob cache file from mixed array', data)
  157. p = createMixedBlobData(this._ref, data)
  158. }
  159. else {
  160. data = data.toString()
  161. p = fs.writeFile(this._ref, data, 'utf8')
  162. .then((size) => Promise.resolve(size))
  163. }
  164. p && p.then((size) => {
  165. this.size = size
  166. this._invokeOnCreateEvent()
  167. })
  168. .catch((err) => {
  169. log.error('RNFetchBlob could not create Blob : '+ this._ref, err)
  170. })
  171. }
  172. /**
  173. * Since Blob content will asynchronously write to a file during creation,
  174. * use this method to register an event handler for Blob initialized event.
  175. * @nonstandard
  176. * @param {(b:Blob) => void} An event handler invoked when Blob created
  177. * @return {Blob} The Blob object instance itself
  178. */
  179. onCreated(fn:() => void):Blob {
  180. log.verbose('#register blob onCreated', this._blobCreated)
  181. if(!this._blobCreated)
  182. this._onCreated.push(fn)
  183. else {
  184. fn(this)
  185. }
  186. return this
  187. }
  188. markAsDerived() {
  189. this._isDerived = true
  190. }
  191. get isDerived() {
  192. return this._isDerived || false
  193. }
  194. /**
  195. * Get file reference of the Blob object.
  196. * @nonstandard
  197. * @return {string} Blob file reference which can be consumed by RNFetchBlob fs
  198. */
  199. getRNFetchBlobRef() {
  200. return this._ref
  201. }
  202. /**
  203. * Create a Blob object which is sliced from current object
  204. * @param {number} start Start byte number
  205. * @param {number} end End byte number
  206. * @param {string} contentType Optional, content type of new Blob object
  207. * @return {Blob}
  208. */
  209. slice(start:?number, end:?number, contentType:?string=''):Blob {
  210. if(this._closed)
  211. throw 'Blob has been released.'
  212. log.verbose('slice called', start, end, contentType)
  213. let resPath = blobCacheDir + getBlobName()
  214. let pass = false
  215. log.debug('fs.slice new blob will at', resPath)
  216. let result = new Blob(RNFetchBlob.wrap(resPath), { type : contentType }, true)
  217. fs.exists(blobCacheDir)
  218. .then((exist) => {
  219. if(exist)
  220. return Promise.resolve()
  221. return fs.mkdir(blobCacheDir)
  222. })
  223. .then(() => fs.slice(this._ref, resPath, start, end))
  224. .then((dest) => {
  225. log.debug('fs.slice done', dest)
  226. result._invokeOnCreateEvent()
  227. pass = true
  228. })
  229. .catch((err) => {
  230. console.warn('Blob.slice failed:', err)
  231. pass = true
  232. })
  233. log.debug('slice returning new Blob')
  234. return result
  235. }
  236. /**
  237. * Read data of the Blob object, this is not standard method.
  238. * @nonstandard
  239. * @param {string} encoding Read data with encoding
  240. * @return {Promise}
  241. */
  242. readBlob(encoding:string):Promise<any> {
  243. if(this._closed)
  244. throw 'Blob has been released.'
  245. return fs.readFile(this._ref, encoding || 'utf8')
  246. }
  247. /**
  248. * Release the resource of the Blob object.
  249. * @nonstandard
  250. * @return {Promise}
  251. */
  252. close() {
  253. if(this._closed)
  254. return Promise.reject('Blob has been released.')
  255. this._closed = true
  256. return fs.unlink(this._ref).catch((err) => {
  257. console.warn(err)
  258. })
  259. }
  260. _invokeOnCreateEvent() {
  261. log.verbose('invoke create event', this._onCreated)
  262. this._blobCreated = true
  263. let fns = this._onCreated
  264. for(let i in fns) {
  265. if(typeof fns[i] === 'function') {
  266. fns[i](this)
  267. }
  268. }
  269. delete this._onCreated
  270. }
  271. }
  272. /**
  273. * Get a temp filename for Blob object
  274. * @return {string} Temporary filename
  275. */
  276. function getBlobName() {
  277. return 'blob-' + getUUID()
  278. }
  279. /**
  280. * Create a file according to given array. The element in array can be a number,
  281. * Blob, String, Array.
  282. * @param {string} ref File path reference
  283. * @param {Array} dataArray An array contains different types of data.
  284. * @return {Promise}
  285. */
  286. function createMixedBlobData(ref, dataArray) {
  287. // create an empty file for store blob data
  288. let p = fs.writeFile(ref, '')
  289. let args = []
  290. let size = 0
  291. for(let i in dataArray) {
  292. let part = dataArray[i]
  293. if(!part)
  294. continue
  295. if(part.isRNFetchBlobPolyfill) {
  296. args.push([ref, part._ref, 'uri'])
  297. }
  298. else if(typeof part === 'string')
  299. args.push([ref, part, 'utf8'])
  300. // TODO : ArrayBuffer
  301. // else if (part instanceof ArrayBuffer) {
  302. //
  303. // }
  304. else if (Array.isArray(part))
  305. args.push([ref, part, 'ascii'])
  306. }
  307. // start write blob data
  308. for(let i in args) {
  309. p = p.then(function(written){
  310. let arg = this
  311. if(written)
  312. size += written
  313. log.verbose('mixed blob write', args[i], written)
  314. return fs.appendFile(...arg)
  315. }.bind(args[i]))
  316. }
  317. return p.then(() => Promise.resolve(size))
  318. }