-
Notifications
You must be signed in to change notification settings - Fork 489
/
files.js
102 lines (79 loc) · 2.11 KB
/
files.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
import fileReader from 'pull-file-reader'
const ignore = [
'.DS_Store',
'thumbs.db',
'desktop.ini'
]
export async function filesToStreams (files) {
if (files.hasOwnProperty('content')) {
// this is a promise
return files.content
}
const streams = []
let totalSize = 0
let isDir = false
for (let file of files) {
if (ignore.includes(file.name)) {
continue
}
const stream = fileReader(file)
if (file.webkitRelativePath) {
isDir = true
}
streams.push({
name: file.webkitRelativePath || file.name,
content: stream,
size: file.size
})
totalSize += file.size
}
return { streams, totalSize, isDir }
}
async function downloadSingle (file, gatewayUrl, apiUrl) {
let url, filename
if (file.type === 'directory') {
url = `${apiUrl}/api/v0/get?arg=${file.hash}&archive=true&compress=true`
filename = `${file.name}.tar.gz`
} else {
url = `${gatewayUrl}/ipfs/${file.hash}`
filename = file.name
}
return { url, filename }
}
export async function makeHashFromFiles (files, ipfs) {
let node = await ipfs.object.new('unixfs-dir')
for (const file of files) {
node = await ipfs.object.patch.addLink(node.toJSON().multihash, {
name: file.name,
size: file.size,
multihash: file.hash
})
}
return node.toJSON().multihash
}
async function downloadMultiple (files, apiUrl, ipfs) {
if (!apiUrl) {
const e = new Error('api url undefined')
return Promise.reject(e)
}
const multihash = await makeHashFromFiles(files, ipfs)
return {
url: `${apiUrl}/api/v0/get?arg=${multihash}&archive=true&compress=true`,
filename: `download_${multihash}.tar.gz`
}
}
export async function getDownloadLink (files, gatewayUrl, apiUrl, ipfs) {
if (files.length === 1) {
return downloadSingle(files[0], gatewayUrl, apiUrl)
}
return downloadMultiple(files, apiUrl, ipfs)
}
export async function getShareableLink (files, ipfs) {
let hash
if (files.length === 1) {
hash = files[0].hash
} else {
hash = await makeHashFromFiles(files, ipfs)
}
return `https://ipfs.io/ipfs/${hash}`
}