Ingen beskrivning

Blob.js 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. const log = new Log('Blob')
  9. const blobCacheDir = fs.dirs.DocumentDir + '/RNFetchBlob-blobs/'
  10. log.level(3)
  11. /**
  12. * A RNFetchBlob style Blob polyfill class, this is a Blob which compatible to
  13. * Response object attain fron RNFetchBlob.fetch.
  14. */
  15. export default class Blob {
  16. cacheName:string;
  17. type:string;
  18. size:number;
  19. isRNFetchBlobPolyfill:boolean = true;
  20. _ref:string = null;
  21. _blobCreated:boolean = false;
  22. _onCreated:Array<any> = [];
  23. /**
  24. * Static method that remove all files in Blob cache folder.
  25. * @nonstandard
  26. * @return {Promise}
  27. */
  28. static clearCache() {
  29. return fs.unlink(blobCacheDir).then(() => fs.mkdir(blobCacheDir))
  30. }
  31. /**
  32. * RNFetchBlob Blob polyfill, create a Blob directly from file path, BASE64
  33. * encoded data, and string. The conversion is done implicitly according to
  34. * given `mime`. However, the blob creation is asynchronously, to register
  35. * event `onCreated` is need to ensure the Blob is creadted.
  36. * @param {any} data Content of Blob object
  37. * @param {any} mime Content type settings of Blob object, `text/plain`
  38. * by default
  39. */
  40. constructor(data:any, cType:any) {
  41. cType = cType || {}
  42. this.cacheName = getBlobName()
  43. this.isRNFetchBlobPolyfill = true
  44. this.type = cType.type || 'text/plain'
  45. log.verbose('Blob constructor called', 'mime', this.type, 'type', typeof data, 'length', data.length)
  46. this._ref = blobCacheDir + this.cacheName
  47. let p = null
  48. if(data instanceof Blob) {
  49. log.verbose('create Blob cache file from Blob object')
  50. let size = 0
  51. this._ref = String(data.getRNFetchBlobRef())
  52. let orgPath = this._ref
  53. p = fs.exists(orgPath)
  54. .then((exist) => {
  55. if(exist)
  56. return fs.writeFile(orgPath, data, 'uri')
  57. .then((size) => Promise.resolve(size))
  58. .catch((err) => {
  59. throw `RNFetchBlob Blob file creation error, ${err}`
  60. })
  61. else
  62. throw `could not create Blob from path ${orgPath}, file not exists`
  63. })
  64. }
  65. // if the data is a string starts with `RNFetchBlob-file://`, append the
  66. // Blob data from file path
  67. else if(typeof data === 'string' && data.startsWith('RNFetchBlob-file://')) {
  68. log.verbose('create Blob cache file from file path', data)
  69. this._ref = String(data).replace('RNFetchBlob-file://', '')
  70. let orgPath = this._ref
  71. p = fs.stat(orgPath)
  72. .then((stat) => {
  73. return Promise.resolve(stat.size)
  74. })
  75. }
  76. // content from variable need create file
  77. else if(typeof data === 'string') {
  78. let encoding = 'utf8'
  79. let mime = String(this.type)
  80. // when content type contains application/octet* or *;base64, RNFetchBlob
  81. // fs will treat it as BASE64 encoded string binary data
  82. if(/(application\/octet|\;base64)/i.test(mime))
  83. encoding = 'base64'
  84. else
  85. data = data.toString()
  86. // create cache file
  87. log.verbose('create Blob cache file from string', 'encode', encoding)
  88. p = fs.writeFile(this._ref, data, encoding)
  89. .then((size) => Promise.resolve(size))
  90. }
  91. // TODO : ArrayBuffer support
  92. // else if (data instanceof ArrayBuffer ) {
  93. //
  94. // }
  95. // when input is an array of mixed data types, create a file cache
  96. else if(Array.isArray(data)) {
  97. log.verbose('create Blob cache file from mixed array', data)
  98. p = createMixedBlobData(this._ref, data)
  99. }
  100. else {
  101. data = data.toString()
  102. p = fs.writeFile(this._ref, data, 'utf8')
  103. .then((size) => Promise.resolve(size))
  104. }
  105. p && p.then((size) => {
  106. this.size = size
  107. this._invokeOnCreateEvent()
  108. })
  109. .catch((err) => {
  110. log.error('RNFetchBlob could not create Blob : '+ this._ref, err)
  111. })
  112. }
  113. /**
  114. * Since Blob content will asynchronously write to a file during creation,
  115. * use this method to register an event handler for Blob initialized event.
  116. * @nonstandard
  117. * @param {[type]} fn:( [description]
  118. * @return {[type]} [description]
  119. */
  120. onCreated(fn:() => void) {
  121. log.verbose('register blob onCreated', this._onCreated.length)
  122. this._onCreated.push(fn)
  123. }
  124. /**
  125. * Get file reference of the Blob object.
  126. * @nonstandard
  127. * @return {string} Blob file reference which can be consumed by RNFetchBlob fs
  128. */
  129. getRNFetchBlobRef() {
  130. return this._ref
  131. }
  132. /**
  133. * Create a Blob object which is sliced from current object
  134. * @param {number} start Start byte number
  135. * @param {number} end End byte number
  136. * @param {string} contentType Optional, content type of new Blob object
  137. * @return {Blob}
  138. */
  139. slice(start:?number, end:?number, encoding:?string):Blob {
  140. log.verbose('slice called')
  141. // TODO : fs.slice
  142. // return fs.slice(this.cacheName, getBlobName(), contentType, start, end)
  143. }
  144. /**
  145. * Release the resource of the Blob object.
  146. * @nonstandard
  147. * @return {Promise}
  148. */
  149. close() {
  150. return fs.unlink(this._ref)
  151. }
  152. _invokeOnCreateEvent() {
  153. log.verbose('invoke create event')
  154. this._blobCreated = true
  155. let fns = this._onCreated
  156. for(let i in fns) {
  157. if(typeof fns[i] === 'function')
  158. fns[i](this)
  159. }
  160. delete this._onCreated
  161. }
  162. }
  163. /**
  164. * Get a temp filename for Blob object
  165. * @return {string} Temporary filename
  166. */
  167. function getBlobName() {
  168. return 'blob-' + getUUID()
  169. }
  170. /**
  171. * Create a file according to given array. The element in array can be a number,
  172. * Blob, String, Array.
  173. * @param {string} ref File path reference
  174. * @param {Array} dataArray An array contains different types of data.
  175. * @return {Promise}
  176. */
  177. function createMixedBlobData(ref, dataArray) {
  178. let p = fs.writeFile(ref, '')
  179. let args = []
  180. let size = 0
  181. for(let i in dataArray) {
  182. let part = dataArray[i]
  183. if(part instanceof Blob)
  184. args.push([ref, part.getRNFetchBlobRef(), 'uri'])
  185. else if(typeof part === 'string')
  186. args.push([ref, part, 'utf8'])
  187. // TODO : ArrayBuffer
  188. // else if (part instanceof ArrayBuffer) {
  189. //
  190. // }
  191. else if (Array.isArray(part))
  192. args.push([ref, part, 'ascii'])
  193. }
  194. return p.then(() => {
  195. let promises = args.map((p) => {
  196. log.verbose('mixed blob write', ...p)
  197. return fs.appendFile.call(this, ...p)
  198. })
  199. return Promise.all(promises).then((sizes) => {
  200. console.log('blob write size', sizes)
  201. for(let i in sizes) {
  202. size += sizes[i]
  203. }
  204. return Promise.resolve(size)
  205. })
  206. })
  207. }