Browse Source

#3703 公用-图片上传sdk开发 (#1)

ifbbprochris 5 years ago
parent
commit
de831f5e80

+ 52
- 1
README.md View File

@@ -1,3 +1,54 @@
1 1
 # upload_sdk
2 2
 
3
-上传插件,不包含上传的前端实现,只提供后端接口等,其他地方接入插件上传。包括上传进度、断点续传等
3
+上传插件,不包含上传的前端实现,只提供后端接口等,其他地方接入插件上传。包括上传进度、断点续传等
4
+
5
+## 使用方法
6
+
7
+### 在 package.json 里添加 
8
+```
9
+"upload_sdk": "git+ssh://git@git.links123.net:npm/upload_sdk.git"
10
+```
11
+
12
+### 在文件中引入
13
+
14
+```
15
+import UploadSdk from 'upload_sdk'
16
+
17
+```
18
+
19
+### 初始化传入 host(api), origin(社区 'forum'), token, file
20
+```
21
+let uploadSdk = new UploadSdk(host,origin,token,file)
22
+```
23
+
24
+### 主要方法
25
+```
26
+//上传图片,默认实现断点续传,如果上次上传中断,第二次上传如果服务器那边还没过期会接着上传
27
+uploadSdk.imageUploadAction().then((res) => {
28
+      const { url } = res
29
+      this.updateFileList(file, url)
30
+    }).catch((err) => {
31
+      console.log(err)
32
+})
33
+
34
+//上传视频
35
+uploadSdk.videoUploadAction().then((res) => {
36
+      const { url } = res
37
+      this.updateFileList(file, url)
38
+    }).catch((err) => {
39
+      console.log(err)
40
+})
41
+
42
+//监听上传进度,用于有显示上传进度条的需求
43
+uploadSdk.onUpdateProgress( progress => {
44
+      console.log(progress)
45
+})
46
+```
47
+
48
+### 返回的 error 在 catch里面捕捉
49
+```
50
+IMAGE_TYPE_ERROR: 101,
51
+VIDOE_TYPE_ERROR: 102,
52
+UPLOAD_SUCCESS_CODE: 200,
53
+UPLOAD_FAILED_CODE: 400
54
+```

+ 170
- 0
index.js View File

@@ -0,0 +1,170 @@
1
+import { Constants } from './utils/contants'
2
+import getFilemd5sum from './utils/utils'
3
+
4
+function FileFactory(file) {
5
+  this.offset = 0; //用于断点续传,默认为 0
6
+  this.BYTES_PER_CHUNK = 1024 * 1024
7
+  this.file = file
8
+  this.fileSize = file.size
9
+  this.fileType = (file.name.split('.')[1]).toLowerCase()
10
+  this.chunkNum = this.BYTES_PER_CHUNK > this.fileSize ? Math.ceil(this.fileSize / this.BYTES_PER_CHUNK) : 1
11
+  this.chunkSize = this.BYTES_PER_CHUNK > this.fileSize ? this.fileSize : this.BYTES_PER_CHUNK
12
+}
13
+
14
+FileFactory.prototype.setOffset = function (offset) {
15
+  this.offset = offset
16
+}
17
+
18
+export default function UploadSdk(host, origin, token, file) {
19
+
20
+  this.handlers = [] //用于处理出触发事件
21
+  this.host = host.indexOf('http:') > -1 ? 'http:'+ host: host
22
+  this.origin = origin
23
+  this.token = token
24
+  this.file = file
25
+
26
+  this.generateMd5 = function (callback) {
27
+    getFilemd5sum(this.file).then(result => {
28
+      callback(result)
29
+    })
30
+  }
31
+
32
+  this.imageUploadAction = function () {
33
+    return new Promise((resolve, reject) => {
34
+      let fileFactory = new FileFactory(this.file)
35
+      if (!fileFactory.fileType.match('[(jpg)|(png)|(gif)]+$')) {
36
+        reject(Constants.IMAGE_TYPE_ERROR)
37
+      }
38
+      this.generateMd5((md5) => {
39
+        this.md5 = md5
40
+        this.postImage(this.md5, fileFactory).then(res => {
41
+          resolve(res)
42
+        }).catch((err) => {
43
+          reject(err)
44
+        })
45
+      })
46
+    })
47
+  }
48
+
49
+  this.videoUploadAction = function () {
50
+    return new Promise((resolve, reject) => {
51
+      if (!this.file.type.match('[(mp4)|(rmvb)|(flv)|(mpeg)|(avi)]+$')) {
52
+        reject(Constants.VIDOE_TYPE_ERROR)
53
+      }
54
+      this.postVideo().then(res => {
55
+        resolve(res)
56
+      }).catch((err) => {
57
+        reject(err)
58
+      })
59
+    })
60
+  }
61
+
62
+  this.postVideo = function () {
63
+    const self = this
64
+    return new Promise((resolve, reject) => {
65
+      let xhr = new XMLHttpRequest()
66
+      xhr.open('POST', this.host + Constants.VIDEO_MULTIPART + this.origin, true)
67
+      xhr.withCredentials = true;
68
+      xhr.setRequestHeader('Authorization', `Bearer ${this.token}`)
69
+      xhr.setRequestHeader('Content-type', 'application/json')
70
+      xhr.upload.addEventListener("progress", function updateProgress(oEvent) {
71
+        if (oEvent.lengthComputable) {
72
+          let percentComplete = oEvent.loaded / oEvent.total * 100;
73
+          self.emitUpdateProgress(percentComplete)
74
+        }
75
+      }, false)
76
+      let fd = new FormData()
77
+      fd.append('file', this.file)
78
+      fd.append('code_rate', 'ld,sd,hd')
79
+      xhr.send(fd)
80
+      xhr.onreadystatechange = function () {
81
+        if (xhr.readyState === 4) {
82
+          let obj = JSON.parse(xhr.responseText)
83
+          if (xhr.status === 304 || (xhr.status >= 200 && xhr.status < 300)) {
84
+            resolve({
85
+              code: Constants.UPLOAD_SUCCESS_CODE,
86
+              url: obj.url,
87
+              msg: 'success'
88
+            })
89
+          } else {
90
+            reject({
91
+              code: Constants.UPLOAD_FAILED_CODE,
92
+              url: '',
93
+              msg: obj.message
94
+            })
95
+          }
96
+        }
97
+      }
98
+    })
99
+  }
100
+
101
+  this.postImage = function (md5, fileFactory) {
102
+    const self = this
103
+    return new Promise((resolve, reject) => {
104
+      let xhr = new XMLHttpRequest()
105
+      xhr.upload.addEventListener("progress", function updateProgress(oEvent) {
106
+        if (oEvent.lengthComputable) {
107
+          let percentComplete = oEvent.loaded / oEvent.total * 100;
108
+          self.emitUpdateProgress(percentComplete)
109
+        }
110
+      }, false)
111
+      xhr.open('POSt', this.host + Constants.IMAGE_MULTIPART + this.origin, true)
112
+      xhr.withCredentials = true
113
+      xhr.setRequestHeader('Authorization', `Bearer ${this.token}`)
114
+      xhr.setRequestHeader('X-Upload-File-Size', fileFactory.fileSize)
115
+      xhr.setRequestHeader('X-Upload-Chunk-Index', 1 + '')
116
+      xhr.setRequestHeader('X-Upload-Chunk-Num', fileFactory.chunkNum)
117
+      xhr.setRequestHeader('X-Upload-Chunk-Size', fileFactory.chunkSize)
118
+      xhr.setRequestHeader('X-Upload-Offset', fileFactory.offset + '')
119
+      xhr.setRequestHeader('X-Upload-File-Md5', md5)
120
+      xhr.setRequestHeader('X-Upload-File-Type', fileFactory.fileType)
121
+      let fd = new FormData()
122
+      fd.append('file', this.file)
123
+      xhr.send(fd)
124
+      xhr.onreadystatechange = function () {
125
+        if (xhr.readyState === 4) {
126
+          let obj = JSON.parse(xhr.responseText)
127
+          if (xhr.status === 304 || (xhr.status >= 200 && xhr.status < 300)) {
128
+
129
+            if (obj.status === 1) {
130
+              resolve({
131
+                code: Constants.UPLOAD_SUCCESS_CODE,
132
+                url: obj.url,
133
+                msg: 'success'
134
+              })
135
+            } else if (obj.status === 0) {
136
+              fileFactory.setOffset(obj.msg)
137
+              this.getAllResponseHeaders.postImage(md5, fileFactory)
138
+            }
139
+          } else {
140
+            reject({
141
+              code: Constants.UPLOAD_FAILED_CODE,
142
+              url: '',
143
+              msg: obj.message
144
+            })
145
+          }
146
+        }
147
+      }
148
+    })
149
+  }
150
+}
151
+
152
+UploadSdk.prototype = {
153
+
154
+  onUpdateProgress: function(subscriber){
155
+    let isExist = this.handlers.some(function(item){
156
+      return item == subscriber;
157
+    })
158
+    if(!isExist){
159
+      this.handlers.push(subscriber);
160
+    }
161
+    return this;
162
+  },
163
+  
164
+  emitUpdateProgress: function(data){
165
+    this.handlers.forEach(function(fn){
166
+      fn(data)
167
+    })
168
+    return this;
169
+  }
170
+}

+ 21
- 0
node_modules/@types/spark-md5/LICENSE View File

@@ -0,0 +1,21 @@
1
+    MIT License
2
+
3
+    Copyright (c) Microsoft Corporation. All rights reserved.
4
+
5
+    Permission is hereby granted, free of charge, to any person obtaining a copy
6
+    of this software and associated documentation files (the "Software"), to deal
7
+    in the Software without restriction, including without limitation the rights
8
+    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+    copies of the Software, and to permit persons to whom the Software is
10
+    furnished to do so, subject to the following conditions:
11
+
12
+    The above copyright notice and this permission notice shall be included in all
13
+    copies or substantial portions of the Software.
14
+
15
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+    SOFTWARE

+ 16
- 0
node_modules/@types/spark-md5/README.md View File

@@ -0,0 +1,16 @@
1
+# Installation
2
+> `npm install --save @types/spark-md5`
3
+
4
+# Summary
5
+This package contains type definitions for spark-md5 (https://github.com/satazor/js-spark-md5#readme).
6
+
7
+# Details
8
+Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/spark-md5
9
+
10
+Additional Details
11
+ * Last updated: Fri, 24 Aug 2018 18:22:08 GMT
12
+ * Dependencies: none
13
+ * Global values: none
14
+
15
+# Credits
16
+These definitions were written by Bastien Moulia <https://github.com/bastienmoulia>.

+ 42
- 0
node_modules/@types/spark-md5/index.d.ts View File

@@ -0,0 +1,42 @@
1
+// Type definitions for spark-md5 3.0
2
+// Project: https://github.com/satazor/js-spark-md5#readme
3
+// Definitions by: Bastien Moulia <https://github.com/bastienmoulia>
4
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
5
+// TypeScript Version: 2.3
6
+
7
+interface State {
8
+	buff: Uint8Array;
9
+	length: number;
10
+	hash: number[];
11
+}
12
+
13
+// copy of ArrayBuffer because of a conflict with the class SparkMD5.ArrayBuffer
14
+interface ArrayBufferCopy extends ArrayBuffer {}
15
+
16
+declare class SparkMD5 {
17
+	constructor();
18
+	append(str: string): SparkMD5;
19
+	appendBinary(contents: string): SparkMD5;
20
+	end(raw?: boolean): string;
21
+	reset(): SparkMD5;
22
+	getState(): State;
23
+	setState(state: State): State;
24
+	destroy(): void;
25
+	static hash(str: string, raw?: boolean): string;
26
+	static hashBinary(content: string, raw?: boolean): string;
27
+}
28
+
29
+declare namespace SparkMD5 {
30
+	class ArrayBuffer {
31
+		constructor();
32
+		append(str: ArrayBufferCopy): ArrayBuffer;
33
+		end(raw?: boolean): string;
34
+		reset(): ArrayBuffer;
35
+		getState(): State;
36
+		setState(state: State): State;
37
+		destroy(): void;
38
+		static hash(arr: ArrayBufferCopy, raw?: boolean): string;
39
+	}
40
+}
41
+
42
+export = SparkMD5;

+ 52
- 0
node_modules/@types/spark-md5/package.json View File

@@ -0,0 +1,52 @@
1
+{
2
+  "_from": "@types/spark-md5",
3
+  "_id": "@types/spark-md5@3.0.1",
4
+  "_inBundle": false,
5
+  "_integrity": "sha1-NRs4OzL6empXm4Nu+Hhik8Sn5zs=",
6
+  "_location": "/@types/spark-md5",
7
+  "_phantomChildren": {},
8
+  "_requested": {
9
+    "type": "tag",
10
+    "registry": true,
11
+    "raw": "@types/spark-md5",
12
+    "name": "@types/spark-md5",
13
+    "escapedName": "@types%2fspark-md5",
14
+    "scope": "@types",
15
+    "rawSpec": "",
16
+    "saveSpec": null,
17
+    "fetchSpec": "latest"
18
+  },
19
+  "_requiredBy": [
20
+    "#USER",
21
+    "/"
22
+  ],
23
+  "_resolved": "http://registry.npm.taobao.org/@types/spark-md5/download/@types/spark-md5-3.0.1.tgz",
24
+  "_shasum": "351b383b32fa7a6a579b836ef8786293c4a7e73b",
25
+  "_spec": "@types/spark-md5",
26
+  "_where": "/Users/chris/Desktop/yunteam/npm/upload_sdk",
27
+  "bugs": {
28
+    "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues"
29
+  },
30
+  "bundleDependencies": false,
31
+  "contributors": [
32
+    {
33
+      "name": "Bastien Moulia",
34
+      "url": "https://github.com/bastienmoulia"
35
+    }
36
+  ],
37
+  "dependencies": {},
38
+  "deprecated": false,
39
+  "description": "TypeScript definitions for spark-md5",
40
+  "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme",
41
+  "license": "MIT",
42
+  "main": "",
43
+  "name": "@types/spark-md5",
44
+  "repository": {
45
+    "type": "git",
46
+    "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git"
47
+  },
48
+  "scripts": {},
49
+  "typeScriptVersion": "2.3",
50
+  "typesPublisherContentHash": "2a43caed2d990f7e42f104d1ba1b29d2fd582cf68e20828026785d2fc0774a6b",
51
+  "version": "3.0.1"
52
+}

+ 13
- 0
node_modules/spark-md5/LICENSE View File

@@ -0,0 +1,13 @@
1
+            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
2
+                    Version 2, December 2004
3
+
4
+ Copyright (C) 2015 André Cruz <amdfcruz@gmail.com>
5
+
6
+ Everyone is permitted to copy and distribute verbatim or modified
7
+ copies of this license document, and changing it is allowed as long
8
+ as the name is changed.
9
+
10
+            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
11
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
12
+
13
+  0. You just DO WHAT THE FUCK YOU WANT TO.

+ 186
- 0
node_modules/spark-md5/README.md View File

@@ -0,0 +1,186 @@
1
+# SparkMD5
2
+
3
+SparkMD5 is a fast md5 implementation of the MD5 algorithm.
4
+This script is based in the JKM md5 library which is the [fastest](http://jsperf.com/md5-shootout/7) algorithm around. This is most suitable for browser usage, because `nodejs` version might be faster.
5
+
6
+NOTE: Please disable Firebug while performing the test!
7
+      Firebug consumes a lot of memory and CPU and slows the test by a great margin.
8
+
9
+
10
+**[Demo](http://9px.ir/demo/incremental-md5.html)**
11
+
12
+
13
+## Improvements over the JKM md5 library
14
+
15
+ * Strings are converted to utf8, like most server side algorithms
16
+ * Fix computation for large amounts of data (overflow)
17
+ * Incremental md5 (see bellow)
18
+ * Support for array buffers (typed arrays)
19
+ * Functionality wrapped in a closure, to avoid global assignments
20
+ * Object oriented library
21
+ * CommonJS (it can be used in node) and AMD integration
22
+ * Code passed through JSHint and JSCS
23
+
24
+
25
+Incremental md5 performs a lot better for hashing large amounts of data, such as
26
+files. One could read files in chunks, using the FileReader & Blob's, and append
27
+each chunk for md5 hashing while keeping memory usage low. See example below.
28
+
29
+
30
+## Usage
31
+
32
+### Normal usage
33
+
34
+```js
35
+var hexHash = SparkMD5.hash('Hi there');        // hex hash
36
+var rawHash = SparkMD5.hash('Hi there', true);  // OR raw hash (binary string)
37
+```
38
+
39
+### Incremental usage
40
+
41
+```js
42
+var spark = new SparkMD5();
43
+spark.append('Hi');
44
+spark.append(' there');
45
+var hexHash = spark.end();                      // hex hash
46
+var rawHash = spark.end(true);                  // OR raw hash (binary string)
47
+```
48
+
49
+### Hash a file incrementally
50
+
51
+NOTE: If you test the code bellow using the file:// protocol in chrome you must start the browser with -allow-file-access-from-files argument.
52
+      Please see: http://code.google.com/p/chromium/issues/detail?id=60889
53
+
54
+```js
55
+document.getElementById('file').addEventListener('change', function () {
56
+    var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
57
+        file = this.files[0],
58
+        chunkSize = 2097152,                             // Read in chunks of 2MB
59
+        chunks = Math.ceil(file.size / chunkSize),
60
+        currentChunk = 0,
61
+        spark = new SparkMD5.ArrayBuffer(),
62
+        fileReader = new FileReader();
63
+
64
+    fileReader.onload = function (e) {
65
+        console.log('read chunk nr', currentChunk + 1, 'of', chunks);
66
+        spark.append(e.target.result);                   // Append array buffer
67
+        currentChunk++;
68
+
69
+        if (currentChunk < chunks) {
70
+            loadNext();
71
+        } else {
72
+            console.log('finished loading');
73
+            console.info('computed hash', spark.end());  // Compute hash
74
+        }
75
+    };
76
+
77
+    fileReader.onerror = function () {
78
+        console.warn('oops, something went wrong.');
79
+    };
80
+
81
+    function loadNext() {
82
+        var start = currentChunk * chunkSize,
83
+            end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
84
+
85
+        fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
86
+    }
87
+
88
+    loadNext();
89
+});
90
+```
91
+
92
+You can see some more examples in the test folder.
93
+
94
+## Documentation
95
+
96
+
97
+### SparkMD5 class
98
+
99
+#### SparkMD5#append(str)
100
+
101
+Appends a string, encoding it to UTF8 if necessary.
102
+
103
+#### SparkMD5#appendBinary(str)
104
+
105
+Appends a binary string (e.g.: string returned from the deprecated [readAsBinaryString](https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsBinaryString)).
106
+
107
+#### SparkMD5#end(raw)
108
+
109
+Finishes the computation of the md5, returning the hex result.
110
+If `raw` is true, the result as a binary string will be returned instead.
111
+
112
+#### SparkMD5#reset()
113
+
114
+Resets the internal state of the computation.
115
+
116
+#### SparkMD5#getState()
117
+
118
+Returns an object representing the internal computation state.
119
+You can pass this state to setState(). This feature is useful to resume an incremental md5.
120
+
121
+#### SparkMD5#setState(state)
122
+
123
+Sets the internal computation state. See: getState().
124
+
125
+#### SparkMD5#destroy()
126
+
127
+Releases memory used by the incremental buffer and other additional resources.
128
+
129
+#### SparkMD5.hash(str, raw)
130
+
131
+Hashes a string directly, returning the hex result.
132
+If `raw` is true, the result as a binary string will be returned instead.
133
+Note that this function is `static`.
134
+
135
+#### SparkMD5.hashBinary(str, raw)
136
+
137
+Hashes a binary string directly (e.g.: string returned from the deprecated [readAsBinaryString](https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsBinaryString)), returning the hex result.
138
+If `raw` is true, the result as a binary string will be returned instead.
139
+Note that this function is `static`.
140
+
141
+
142
+### SparkMD5.ArrayBuffer class
143
+
144
+#### SparkMD5.ArrayBuffer#append(arr)
145
+
146
+Appends an array buffer.
147
+
148
+#### SparkMD5.ArrayBuffer#end(raw)
149
+
150
+Finishes the computation of the md5, returning the hex result.
151
+If `raw` is true, the result as a binary string will be returned instead.
152
+
153
+#### SparkMD5.ArrayBuffer#reset()
154
+
155
+Resets the internal state of the computation.
156
+
157
+#### SparkMD5.ArrayBuffer#destroy()
158
+
159
+Releases memory used by the incremental buffer and other additional resources.
160
+
161
+#### SparkMD5.ArrayBuffer#getState()
162
+
163
+Returns an object representing the internal computation state.
164
+You can pass this state to setState(). This feature is useful to resume an incremental md5.
165
+
166
+#### SparkMD5.ArrayBuffer#setState(state)
167
+
168
+Sets the internal computation state. See: getState().
169
+
170
+#### SparkMD5.ArrayBuffer.hash(arr, raw)
171
+
172
+Hashes an array buffer directly, returning the hex result.
173
+If `raw` is true, the result as a binary string will be returned instead.
174
+Note that this function is `static`.
175
+
176
+
177
+## License
178
+
179
+The project is double licensed, being [WTF2](./LICENSE) the master license and [MIT](./LICENSE2) the alternative license.
180
+The reason to have two licenses is that some entities refuse to use the master license (WTF2) due to
181
+bad language. If that's also your case, you can choose the alternative license.
182
+
183
+
184
+## Credits
185
+
186
+[Joseph Myers](http://www.myersdaily.org/joseph/javascript/md5-text.html)

+ 65
- 0
node_modules/spark-md5/package.json View File

@@ -0,0 +1,65 @@
1
+{
2
+  "_from": "spark-md5",
3
+  "_id": "spark-md5@3.0.0",
4
+  "_inBundle": false,
5
+  "_integrity": "sha1-NyIifFTi+vJLHcbZM8wUTm9xv+8=",
6
+  "_location": "/spark-md5",
7
+  "_phantomChildren": {},
8
+  "_requested": {
9
+    "type": "tag",
10
+    "registry": true,
11
+    "raw": "spark-md5",
12
+    "name": "spark-md5",
13
+    "escapedName": "spark-md5",
14
+    "rawSpec": "",
15
+    "saveSpec": null,
16
+    "fetchSpec": "latest"
17
+  },
18
+  "_requiredBy": [
19
+    "#USER",
20
+    "/"
21
+  ],
22
+  "_resolved": "http://registry.npm.taobao.org/spark-md5/download/spark-md5-3.0.0.tgz",
23
+  "_shasum": "3722227c54e2faf24b1dc6d933cc144e6f71bfef",
24
+  "_spec": "spark-md5",
25
+  "_where": "/Users/chris/Desktop/yunteam/npm/upload_sdk",
26
+  "author": {
27
+    "name": "André Cruz",
28
+    "email": "andremiguelcruz@msn.com"
29
+  },
30
+  "bugs": {
31
+    "url": "https://github.com/satazor/js-spark-md5/issues"
32
+  },
33
+  "bundleDependencies": false,
34
+  "deprecated": false,
35
+  "description": "Lightning fast normal and incremental md5 for javascript",
36
+  "devDependencies": {
37
+    "uglify-js": "^2.4.16"
38
+  },
39
+  "directories": {
40
+    "test": "test"
41
+  },
42
+  "files": [
43
+    "spark-md5.js",
44
+    "spark-md5.min.js"
45
+  ],
46
+  "homepage": "https://github.com/satazor/js-spark-md5#readme",
47
+  "keywords": [
48
+    "md5",
49
+    "fast",
50
+    "spark",
51
+    "incremental"
52
+  ],
53
+  "license": "WTFPL",
54
+  "main": "spark-md5.js",
55
+  "name": "spark-md5",
56
+  "repository": {
57
+    "type": "git",
58
+    "url": "git+ssh://git@github.com/satazor/js-spark-md5.git"
59
+  },
60
+  "scripts": {
61
+    "min": "uglifyjs spark-md5.js > spark-md5.min.js",
62
+    "test": "open test/index.html"
63
+  },
64
+  "version": "3.0.0"
65
+}

+ 751
- 0
node_modules/spark-md5/spark-md5.js View File

@@ -0,0 +1,751 @@
1
+(function (factory) {
2
+    if (typeof exports === 'object') {
3
+        // Node/CommonJS
4
+        module.exports = factory();
5
+    } else if (typeof define === 'function' && define.amd) {
6
+        // AMD
7
+        define(factory);
8
+    } else {
9
+        // Browser globals (with support for web workers)
10
+        var glob;
11
+
12
+        try {
13
+            glob = window;
14
+        } catch (e) {
15
+            glob = self;
16
+        }
17
+
18
+        glob.SparkMD5 = factory();
19
+    }
20
+}(function (undefined) {
21
+
22
+    'use strict';
23
+
24
+    /*
25
+     * Fastest md5 implementation around (JKM md5).
26
+     * Credits: Joseph Myers
27
+     *
28
+     * @see http://www.myersdaily.org/joseph/javascript/md5-text.html
29
+     * @see http://jsperf.com/md5-shootout/7
30
+     */
31
+
32
+    /* this function is much faster,
33
+      so if possible we use it. Some IEs
34
+      are the only ones I know of that
35
+      need the idiotic second function,
36
+      generated by an if clause.  */
37
+    var add32 = function (a, b) {
38
+        return (a + b) & 0xFFFFFFFF;
39
+    },
40
+        hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
41
+
42
+
43
+    function cmn(q, a, b, x, s, t) {
44
+        a = add32(add32(a, q), add32(x, t));
45
+        return add32((a << s) | (a >>> (32 - s)), b);
46
+    }
47
+
48
+    function md5cycle(x, k) {
49
+        var a = x[0],
50
+            b = x[1],
51
+            c = x[2],
52
+            d = x[3];
53
+
54
+        a += (b & c | ~b & d) + k[0] - 680876936 | 0;
55
+        a  = (a << 7 | a >>> 25) + b | 0;
56
+        d += (a & b | ~a & c) + k[1] - 389564586 | 0;
57
+        d  = (d << 12 | d >>> 20) + a | 0;
58
+        c += (d & a | ~d & b) + k[2] + 606105819 | 0;
59
+        c  = (c << 17 | c >>> 15) + d | 0;
60
+        b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
61
+        b  = (b << 22 | b >>> 10) + c | 0;
62
+        a += (b & c | ~b & d) + k[4] - 176418897 | 0;
63
+        a  = (a << 7 | a >>> 25) + b | 0;
64
+        d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
65
+        d  = (d << 12 | d >>> 20) + a | 0;
66
+        c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
67
+        c  = (c << 17 | c >>> 15) + d | 0;
68
+        b += (c & d | ~c & a) + k[7] - 45705983 | 0;
69
+        b  = (b << 22 | b >>> 10) + c | 0;
70
+        a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
71
+        a  = (a << 7 | a >>> 25) + b | 0;
72
+        d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
73
+        d  = (d << 12 | d >>> 20) + a | 0;
74
+        c += (d & a | ~d & b) + k[10] - 42063 | 0;
75
+        c  = (c << 17 | c >>> 15) + d | 0;
76
+        b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
77
+        b  = (b << 22 | b >>> 10) + c | 0;
78
+        a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
79
+        a  = (a << 7 | a >>> 25) + b | 0;
80
+        d += (a & b | ~a & c) + k[13] - 40341101 | 0;
81
+        d  = (d << 12 | d >>> 20) + a | 0;
82
+        c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
83
+        c  = (c << 17 | c >>> 15) + d | 0;
84
+        b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
85
+        b  = (b << 22 | b >>> 10) + c | 0;
86
+
87
+        a += (b & d | c & ~d) + k[1] - 165796510 | 0;
88
+        a  = (a << 5 | a >>> 27) + b | 0;
89
+        d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
90
+        d  = (d << 9 | d >>> 23) + a | 0;
91
+        c += (d & b | a & ~b) + k[11] + 643717713 | 0;
92
+        c  = (c << 14 | c >>> 18) + d | 0;
93
+        b += (c & a | d & ~a) + k[0] - 373897302 | 0;
94
+        b  = (b << 20 | b >>> 12) + c | 0;
95
+        a += (b & d | c & ~d) + k[5] - 701558691 | 0;
96
+        a  = (a << 5 | a >>> 27) + b | 0;
97
+        d += (a & c | b & ~c) + k[10] + 38016083 | 0;
98
+        d  = (d << 9 | d >>> 23) + a | 0;
99
+        c += (d & b | a & ~b) + k[15] - 660478335 | 0;
100
+        c  = (c << 14 | c >>> 18) + d | 0;
101
+        b += (c & a | d & ~a) + k[4] - 405537848 | 0;
102
+        b  = (b << 20 | b >>> 12) + c | 0;
103
+        a += (b & d | c & ~d) + k[9] + 568446438 | 0;
104
+        a  = (a << 5 | a >>> 27) + b | 0;
105
+        d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
106
+        d  = (d << 9 | d >>> 23) + a | 0;
107
+        c += (d & b | a & ~b) + k[3] - 187363961 | 0;
108
+        c  = (c << 14 | c >>> 18) + d | 0;
109
+        b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
110
+        b  = (b << 20 | b >>> 12) + c | 0;
111
+        a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
112
+        a  = (a << 5 | a >>> 27) + b | 0;
113
+        d += (a & c | b & ~c) + k[2] - 51403784 | 0;
114
+        d  = (d << 9 | d >>> 23) + a | 0;
115
+        c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
116
+        c  = (c << 14 | c >>> 18) + d | 0;
117
+        b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
118
+        b  = (b << 20 | b >>> 12) + c | 0;
119
+
120
+        a += (b ^ c ^ d) + k[5] - 378558 | 0;
121
+        a  = (a << 4 | a >>> 28) + b | 0;
122
+        d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
123
+        d  = (d << 11 | d >>> 21) + a | 0;
124
+        c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
125
+        c  = (c << 16 | c >>> 16) + d | 0;
126
+        b += (c ^ d ^ a) + k[14] - 35309556 | 0;
127
+        b  = (b << 23 | b >>> 9) + c | 0;
128
+        a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
129
+        a  = (a << 4 | a >>> 28) + b | 0;
130
+        d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
131
+        d  = (d << 11 | d >>> 21) + a | 0;
132
+        c += (d ^ a ^ b) + k[7] - 155497632 | 0;
133
+        c  = (c << 16 | c >>> 16) + d | 0;
134
+        b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
135
+        b  = (b << 23 | b >>> 9) + c | 0;
136
+        a += (b ^ c ^ d) + k[13] + 681279174 | 0;
137
+        a  = (a << 4 | a >>> 28) + b | 0;
138
+        d += (a ^ b ^ c) + k[0] - 358537222 | 0;
139
+        d  = (d << 11 | d >>> 21) + a | 0;
140
+        c += (d ^ a ^ b) + k[3] - 722521979 | 0;
141
+        c  = (c << 16 | c >>> 16) + d | 0;
142
+        b += (c ^ d ^ a) + k[6] + 76029189 | 0;
143
+        b  = (b << 23 | b >>> 9) + c | 0;
144
+        a += (b ^ c ^ d) + k[9] - 640364487 | 0;
145
+        a  = (a << 4 | a >>> 28) + b | 0;
146
+        d += (a ^ b ^ c) + k[12] - 421815835 | 0;
147
+        d  = (d << 11 | d >>> 21) + a | 0;
148
+        c += (d ^ a ^ b) + k[15] + 530742520 | 0;
149
+        c  = (c << 16 | c >>> 16) + d | 0;
150
+        b += (c ^ d ^ a) + k[2] - 995338651 | 0;
151
+        b  = (b << 23 | b >>> 9) + c | 0;
152
+
153
+        a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
154
+        a  = (a << 6 | a >>> 26) + b | 0;
155
+        d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
156
+        d  = (d << 10 | d >>> 22) + a | 0;
157
+        c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
158
+        c  = (c << 15 | c >>> 17) + d | 0;
159
+        b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
160
+        b  = (b << 21 |b >>> 11) + c | 0;
161
+        a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
162
+        a  = (a << 6 | a >>> 26) + b | 0;
163
+        d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
164
+        d  = (d << 10 | d >>> 22) + a | 0;
165
+        c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
166
+        c  = (c << 15 | c >>> 17) + d | 0;
167
+        b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
168
+        b  = (b << 21 |b >>> 11) + c | 0;
169
+        a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
170
+        a  = (a << 6 | a >>> 26) + b | 0;
171
+        d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
172
+        d  = (d << 10 | d >>> 22) + a | 0;
173
+        c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
174
+        c  = (c << 15 | c >>> 17) + d | 0;
175
+        b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
176
+        b  = (b << 21 |b >>> 11) + c | 0;
177
+        a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
178
+        a  = (a << 6 | a >>> 26) + b | 0;
179
+        d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
180
+        d  = (d << 10 | d >>> 22) + a | 0;
181
+        c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
182
+        c  = (c << 15 | c >>> 17) + d | 0;
183
+        b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
184
+        b  = (b << 21 | b >>> 11) + c | 0;
185
+
186
+        x[0] = a + x[0] | 0;
187
+        x[1] = b + x[1] | 0;
188
+        x[2] = c + x[2] | 0;
189
+        x[3] = d + x[3] | 0;
190
+    }
191
+
192
+    function md5blk(s) {
193
+        var md5blks = [],
194
+            i; /* Andy King said do it this way. */
195
+
196
+        for (i = 0; i < 64; i += 4) {
197
+            md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
198
+        }
199
+        return md5blks;
200
+    }
201
+
202
+    function md5blk_array(a) {
203
+        var md5blks = [],
204
+            i; /* Andy King said do it this way. */
205
+
206
+        for (i = 0; i < 64; i += 4) {
207
+            md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
208
+        }
209
+        return md5blks;
210
+    }
211
+
212
+    function md51(s) {
213
+        var n = s.length,
214
+            state = [1732584193, -271733879, -1732584194, 271733878],
215
+            i,
216
+            length,
217
+            tail,
218
+            tmp,
219
+            lo,
220
+            hi;
221
+
222
+        for (i = 64; i <= n; i += 64) {
223
+            md5cycle(state, md5blk(s.substring(i - 64, i)));
224
+        }
225
+        s = s.substring(i - 64);
226
+        length = s.length;
227
+        tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
228
+        for (i = 0; i < length; i += 1) {
229
+            tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
230
+        }
231
+        tail[i >> 2] |= 0x80 << ((i % 4) << 3);
232
+        if (i > 55) {
233
+            md5cycle(state, tail);
234
+            for (i = 0; i < 16; i += 1) {
235
+                tail[i] = 0;
236
+            }
237
+        }
238
+
239
+        // Beware that the final length might not fit in 32 bits so we take care of that
240
+        tmp = n * 8;
241
+        tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
242
+        lo = parseInt(tmp[2], 16);
243
+        hi = parseInt(tmp[1], 16) || 0;
244
+
245
+        tail[14] = lo;
246
+        tail[15] = hi;
247
+
248
+        md5cycle(state, tail);
249
+        return state;
250
+    }
251
+
252
+    function md51_array(a) {
253
+        var n = a.length,
254
+            state = [1732584193, -271733879, -1732584194, 271733878],
255
+            i,
256
+            length,
257
+            tail,
258
+            tmp,
259
+            lo,
260
+            hi;
261
+
262
+        for (i = 64; i <= n; i += 64) {
263
+            md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
264
+        }
265
+
266
+        // Not sure if it is a bug, however IE10 will always produce a sub array of length 1
267
+        // containing the last element of the parent array if the sub array specified starts
268
+        // beyond the length of the parent array - weird.
269
+        // https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
270
+        a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
271
+
272
+        length = a.length;
273
+        tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
274
+        for (i = 0; i < length; i += 1) {
275
+            tail[i >> 2] |= a[i] << ((i % 4) << 3);
276
+        }
277
+
278
+        tail[i >> 2] |= 0x80 << ((i % 4) << 3);
279
+        if (i > 55) {
280
+            md5cycle(state, tail);
281
+            for (i = 0; i < 16; i += 1) {
282
+                tail[i] = 0;
283
+            }
284
+        }
285
+
286
+        // Beware that the final length might not fit in 32 bits so we take care of that
287
+        tmp = n * 8;
288
+        tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
289
+        lo = parseInt(tmp[2], 16);
290
+        hi = parseInt(tmp[1], 16) || 0;
291
+
292
+        tail[14] = lo;
293
+        tail[15] = hi;
294
+
295
+        md5cycle(state, tail);
296
+
297
+        return state;
298
+    }
299
+
300
+    function rhex(n) {
301
+        var s = '',
302
+            j;
303
+        for (j = 0; j < 4; j += 1) {
304
+            s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
305
+        }
306
+        return s;
307
+    }
308
+
309
+    function hex(x) {
310
+        var i;
311
+        for (i = 0; i < x.length; i += 1) {
312
+            x[i] = rhex(x[i]);
313
+        }
314
+        return x.join('');
315
+    }
316
+
317
+    // In some cases the fast add32 function cannot be used..
318
+    if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {
319
+        add32 = function (x, y) {
320
+            var lsw = (x & 0xFFFF) + (y & 0xFFFF),
321
+                msw = (x >> 16) + (y >> 16) + (lsw >> 16);
322
+            return (msw << 16) | (lsw & 0xFFFF);
323
+        };
324
+    }
325
+
326
+    // ---------------------------------------------------
327
+
328
+    /**
329
+     * ArrayBuffer slice polyfill.
330
+     *
331
+     * @see https://github.com/ttaubert/node-arraybuffer-slice
332
+     */
333
+
334
+    if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
335
+        (function () {
336
+            function clamp(val, length) {
337
+                val = (val | 0) || 0;
338
+
339
+                if (val < 0) {
340
+                    return Math.max(val + length, 0);
341
+                }
342
+
343
+                return Math.min(val, length);
344
+            }
345
+
346
+            ArrayBuffer.prototype.slice = function (from, to) {
347
+                var length = this.byteLength,
348
+                    begin = clamp(from, length),
349
+                    end = length,
350
+                    num,
351
+                    target,
352
+                    targetArray,
353
+                    sourceArray;
354
+
355
+                if (to !== undefined) {
356
+                    end = clamp(to, length);
357
+                }
358
+
359
+                if (begin > end) {
360
+                    return new ArrayBuffer(0);
361
+                }
362
+
363
+                num = end - begin;
364
+                target = new ArrayBuffer(num);
365
+                targetArray = new Uint8Array(target);
366
+
367
+                sourceArray = new Uint8Array(this, begin, num);
368
+                targetArray.set(sourceArray);
369
+
370
+                return target;
371
+            };
372
+        })();
373
+    }
374
+
375
+    // ---------------------------------------------------
376
+
377
+    /**
378
+     * Helpers.
379
+     */
380
+
381
+    function toUtf8(str) {
382
+        if (/[\u0080-\uFFFF]/.test(str)) {
383
+            str = unescape(encodeURIComponent(str));
384
+        }
385
+
386
+        return str;
387
+    }
388
+
389
+    function utf8Str2ArrayBuffer(str, returnUInt8Array) {
390
+        var length = str.length,
391
+           buff = new ArrayBuffer(length),
392
+           arr = new Uint8Array(buff),
393
+           i;
394
+
395
+        for (i = 0; i < length; i += 1) {
396
+            arr[i] = str.charCodeAt(i);
397
+        }
398
+
399
+        return returnUInt8Array ? arr : buff;
400
+    }
401
+
402
+    function arrayBuffer2Utf8Str(buff) {
403
+        return String.fromCharCode.apply(null, new Uint8Array(buff));
404
+    }
405
+
406
+    function concatenateArrayBuffers(first, second, returnUInt8Array) {
407
+        var result = new Uint8Array(first.byteLength + second.byteLength);
408
+
409
+        result.set(new Uint8Array(first));
410
+        result.set(new Uint8Array(second), first.byteLength);
411
+
412
+        return returnUInt8Array ? result : result.buffer;
413
+    }
414
+
415
+    function hexToBinaryString(hex) {
416
+        var bytes = [],
417
+            length = hex.length,
418
+            x;
419
+
420
+        for (x = 0; x < length - 1; x += 2) {
421
+            bytes.push(parseInt(hex.substr(x, 2), 16));
422
+        }
423
+
424
+        return String.fromCharCode.apply(String, bytes);
425
+    }
426
+
427
+    // ---------------------------------------------------
428
+
429
+    /**
430
+     * SparkMD5 OOP implementation.
431
+     *
432
+     * Use this class to perform an incremental md5, otherwise use the
433
+     * static methods instead.
434
+     */
435
+
436
+    function SparkMD5() {
437
+        // call reset to init the instance
438
+        this.reset();
439
+    }
440
+
441
+    /**
442
+     * Appends a string.
443
+     * A conversion will be applied if an utf8 string is detected.
444
+     *
445
+     * @param {String} str The string to be appended
446
+     *
447
+     * @return {SparkMD5} The instance itself
448
+     */
449
+    SparkMD5.prototype.append = function (str) {
450
+        // Converts the string to utf8 bytes if necessary
451
+        // Then append as binary
452
+        this.appendBinary(toUtf8(str));
453
+
454
+        return this;
455
+    };
456
+
457
+    /**
458
+     * Appends a binary string.
459
+     *
460
+     * @param {String} contents The binary string to be appended
461
+     *
462
+     * @return {SparkMD5} The instance itself
463
+     */
464
+    SparkMD5.prototype.appendBinary = function (contents) {
465
+        this._buff += contents;
466
+        this._length += contents.length;
467
+
468
+        var length = this._buff.length,
469
+            i;
470
+
471
+        for (i = 64; i <= length; i += 64) {
472
+            md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));
473
+        }
474
+
475
+        this._buff = this._buff.substring(i - 64);
476
+
477
+        return this;
478
+    };
479
+
480
+    /**
481
+     * Finishes the incremental computation, reseting the internal state and
482
+     * returning the result.
483
+     *
484
+     * @param {Boolean} raw True to get the raw string, false to get the hex string
485
+     *
486
+     * @return {String} The result
487
+     */
488
+    SparkMD5.prototype.end = function (raw) {
489
+        var buff = this._buff,
490
+            length = buff.length,
491
+            i,
492
+            tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
493
+            ret;
494
+
495
+        for (i = 0; i < length; i += 1) {
496
+            tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
497
+        }
498
+
499
+        this._finish(tail, length);
500
+        ret = hex(this._hash);
501
+
502
+        if (raw) {
503
+            ret = hexToBinaryString(ret);
504
+        }
505
+
506
+        this.reset();
507
+
508
+        return ret;
509
+    };
510
+
511
+    /**
512
+     * Resets the internal state of the computation.
513
+     *
514
+     * @return {SparkMD5} The instance itself
515
+     */
516
+    SparkMD5.prototype.reset = function () {
517
+        this._buff = '';
518
+        this._length = 0;
519
+        this._hash = [1732584193, -271733879, -1732584194, 271733878];
520
+
521
+        return this;
522
+    };
523
+
524
+    /**
525
+     * Gets the internal state of the computation.
526
+     *
527
+     * @return {Object} The state
528
+     */
529
+    SparkMD5.prototype.getState = function () {
530
+        return {
531
+            buff: this._buff,
532
+            length: this._length,
533
+            hash: this._hash
534
+        };
535
+    };
536
+
537
+    /**
538
+     * Gets the internal state of the computation.
539
+     *
540
+     * @param {Object} state The state
541
+     *
542
+     * @return {SparkMD5} The instance itself
543
+     */
544
+    SparkMD5.prototype.setState = function (state) {
545
+        this._buff = state.buff;
546
+        this._length = state.length;
547
+        this._hash = state.hash;
548
+
549
+        return this;
550
+    };
551
+
552
+    /**
553
+     * Releases memory used by the incremental buffer and other additional
554
+     * resources. If you plan to use the instance again, use reset instead.
555
+     */
556
+    SparkMD5.prototype.destroy = function () {
557
+        delete this._hash;
558
+        delete this._buff;
559
+        delete this._length;
560
+    };
561
+
562
+    /**
563
+     * Finish the final calculation based on the tail.
564
+     *
565
+     * @param {Array}  tail   The tail (will be modified)
566
+     * @param {Number} length The length of the remaining buffer
567
+     */
568
+    SparkMD5.prototype._finish = function (tail, length) {
569
+        var i = length,
570
+            tmp,
571
+            lo,
572
+            hi;
573
+
574
+        tail[i >> 2] |= 0x80 << ((i % 4) << 3);
575
+        if (i > 55) {
576
+            md5cycle(this._hash, tail);
577
+            for (i = 0; i < 16; i += 1) {
578
+                tail[i] = 0;
579
+            }
580
+        }
581
+
582
+        // Do the final computation based on the tail and length
583
+        // Beware that the final length may not fit in 32 bits so we take care of that
584
+        tmp = this._length * 8;
585
+        tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
586
+        lo = parseInt(tmp[2], 16);
587
+        hi = parseInt(tmp[1], 16) || 0;
588
+
589
+        tail[14] = lo;
590
+        tail[15] = hi;
591
+        md5cycle(this._hash, tail);
592
+    };
593
+
594
+    /**
595
+     * Performs the md5 hash on a string.
596
+     * A conversion will be applied if utf8 string is detected.
597
+     *
598
+     * @param {String}  str The string
599
+     * @param {Boolean} raw True to get the raw string, false to get the hex string
600
+     *
601
+     * @return {String} The result
602
+     */
603
+    SparkMD5.hash = function (str, raw) {
604
+        // Converts the string to utf8 bytes if necessary
605
+        // Then compute it using the binary function
606
+        return SparkMD5.hashBinary(toUtf8(str), raw);
607
+    };
608
+
609
+    /**
610
+     * Performs the md5 hash on a binary string.
611
+     *
612
+     * @param {String}  content The binary string
613
+     * @param {Boolean} raw     True to get the raw string, false to get the hex string
614
+     *
615
+     * @return {String} The result
616
+     */
617
+    SparkMD5.hashBinary = function (content, raw) {
618
+        var hash = md51(content),
619
+            ret = hex(hash);
620
+
621
+        return raw ? hexToBinaryString(ret) : ret;
622
+    };
623
+
624
+    // ---------------------------------------------------
625
+
626
+    /**
627
+     * SparkMD5 OOP implementation for array buffers.
628
+     *
629
+     * Use this class to perform an incremental md5 ONLY for array buffers.
630
+     */
631
+    SparkMD5.ArrayBuffer = function () {
632
+        // call reset to init the instance
633
+        this.reset();
634
+    };
635
+
636
+    /**
637
+     * Appends an array buffer.
638
+     *
639
+     * @param {ArrayBuffer} arr The array to be appended
640
+     *
641
+     * @return {SparkMD5.ArrayBuffer} The instance itself
642
+     */
643
+    SparkMD5.ArrayBuffer.prototype.append = function (arr) {
644
+        var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),
645
+            length = buff.length,
646
+            i;
647
+
648
+        this._length += arr.byteLength;
649
+
650
+        for (i = 64; i <= length; i += 64) {
651
+            md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));
652
+        }
653
+
654
+        this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);
655
+
656
+        return this;
657
+    };
658
+
659
+    /**
660
+     * Finishes the incremental computation, reseting the internal state and
661
+     * returning the result.
662
+     *
663
+     * @param {Boolean} raw True to get the raw string, false to get the hex string
664
+     *
665
+     * @return {String} The result
666
+     */
667
+    SparkMD5.ArrayBuffer.prototype.end = function (raw) {
668
+        var buff = this._buff,
669
+            length = buff.length,
670
+            tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
671
+            i,
672
+            ret;
673
+
674
+        for (i = 0; i < length; i += 1) {
675
+            tail[i >> 2] |= buff[i] << ((i % 4) << 3);
676
+        }
677
+
678
+        this._finish(tail, length);
679
+        ret = hex(this._hash);
680
+
681
+        if (raw) {
682
+            ret = hexToBinaryString(ret);
683
+        }
684
+
685
+        this.reset();
686
+
687
+        return ret;
688
+    };
689
+
690
+    /**
691
+     * Resets the internal state of the computation.
692
+     *
693
+     * @return {SparkMD5.ArrayBuffer} The instance itself
694
+     */
695
+    SparkMD5.ArrayBuffer.prototype.reset = function () {
696
+        this._buff = new Uint8Array(0);
697
+        this._length = 0;
698
+        this._hash = [1732584193, -271733879, -1732584194, 271733878];
699
+
700
+        return this;
701
+    };
702
+
703
+    /**
704
+     * Gets the internal state of the computation.
705
+     *
706
+     * @return {Object} The state
707
+     */
708
+    SparkMD5.ArrayBuffer.prototype.getState = function () {
709
+        var state = SparkMD5.prototype.getState.call(this);
710
+
711
+        // Convert buffer to a string
712
+        state.buff = arrayBuffer2Utf8Str(state.buff);
713
+
714
+        return state;
715
+    };
716
+
717
+    /**
718
+     * Gets the internal state of the computation.
719
+     *
720
+     * @param {Object} state The state
721
+     *
722
+     * @return {SparkMD5.ArrayBuffer} The instance itself
723
+     */
724
+    SparkMD5.ArrayBuffer.prototype.setState = function (state) {
725
+        // Convert string to buffer
726
+        state.buff = utf8Str2ArrayBuffer(state.buff, true);
727
+
728
+        return SparkMD5.prototype.setState.call(this, state);
729
+    };
730
+
731
+    SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
732
+
733
+    SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
734
+
735
+    /**
736
+     * Performs the md5 hash on an array buffer.
737
+     *
738
+     * @param {ArrayBuffer} arr The array buffer
739
+     * @param {Boolean}     raw True to get the raw string, false to get the hex one
740
+     *
741
+     * @return {String} The result
742
+     */
743
+    SparkMD5.ArrayBuffer.hash = function (arr, raw) {
744
+        var hash = md51_array(new Uint8Array(arr)),
745
+            ret = hex(hash);
746
+
747
+        return raw ? hexToBinaryString(ret) : ret;
748
+    };
749
+
750
+    return SparkMD5;
751
+}));

+ 1
- 0
node_modules/spark-md5/spark-md5.min.js
File diff suppressed because it is too large
View File


+ 18
- 0
package-lock.json View File

@@ -0,0 +1,18 @@
1
+{
2
+  "name": "upload_sdk",
3
+  "version": "1.0.0",
4
+  "lockfileVersion": 1,
5
+  "requires": true,
6
+  "dependencies": {
7
+    "@types/spark-md5": {
8
+      "version": "3.0.1",
9
+      "resolved": "http://registry.npm.taobao.org/@types/spark-md5/download/@types/spark-md5-3.0.1.tgz",
10
+      "integrity": "sha1-NRs4OzL6empXm4Nu+Hhik8Sn5zs="
11
+    },
12
+    "spark-md5": {
13
+      "version": "3.0.0",
14
+      "resolved": "http://registry.npm.taobao.org/spark-md5/download/spark-md5-3.0.0.tgz",
15
+      "integrity": "sha1-NyIifFTi+vJLHcbZM8wUTm9xv+8="
16
+    }
17
+  }
18
+}

+ 22
- 0
package.json View File

@@ -0,0 +1,22 @@
1
+{
2
+  "name": "upload_sdk",
3
+  "version": "1.0.0",
4
+  "description": "upload_sdk",
5
+  "main": "index.ts",
6
+  "scripts": {
7
+    "test": "echo \"Error: no test specified\" && exit 1"
8
+  },
9
+  "repository": {
10
+    "type": "git",
11
+    "url": "git@git.links123.net:ifbbprochris/upload_sdk.git"
12
+  },
13
+  "keywords": [
14
+    "upload_sdk"
15
+  ],
16
+  "author": "ifbbprochris",
17
+  "license": "ISC",
18
+  "dependencies": {
19
+    "@types/spark-md5": "^3.0.1",
20
+    "spark-md5": "^3.0.0"
21
+  }
22
+}

+ 10
- 0
utils/contants.js View File

@@ -0,0 +1,10 @@
1
+var Constants = {
2
+  IMAGE_MULTIPART: '/multipart/upload/',
3
+  VIDEO_MULTIPART: '/upload/',
4
+  IMAGE_TYPE_ERROR: 101,
5
+  VIDOE_TYPE_ERROR: 102,
6
+  UPLOAD_SUCCESS_CODE: 200,
7
+  UPLOAD_FAILED_CODE: 400
8
+}
9
+
10
+export { Constants }

+ 40
- 0
utils/utils.js View File

@@ -0,0 +1,40 @@
1
+import SparkMD5 from 'spark-md5'
2
+
3
+export default function getFilemd5sum(ofile) {
4
+    return new Promise((resolve, reject) => {
5
+        let file = ofile;
6
+        let tmp_md5;
7
+        let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
8
+            // file = this.files[0],
9
+            chunkSize = 8097152, // Read in chunks of 2MB
10
+            chunks = Math.ceil(file.size / chunkSize),
11
+            currentChunk = 0,
12
+            spark = new SparkMD5.ArrayBuffer(),
13
+            fileReader = new FileReader();
14
+
15
+        function loadNext()  {
16
+            var start = currentChunk * chunkSize,
17
+                end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
18
+            fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
19
+        }
20
+
21
+        fileReader.onload = function (e) {
22
+            spark.append(e.target.result); // Append array buffer
23
+            currentChunk++;
24
+
25
+            if (currentChunk < chunks) {
26
+                loadNext();
27
+            } else {
28
+                tmp_md5 = spark.end();
29
+                resolve(tmp_md5)
30
+            }
31
+        };
32
+
33
+        fileReader.onerror = function () {
34
+            reject('error');
35
+        };
36
+
37
+        
38
+        loadNext();
39
+    })
40
+}