-
Notifications
You must be signed in to change notification settings - Fork 904
Expand file tree
/
Copy pathadd-to-ipfs.js
More file actions
152 lines (125 loc) · 4.05 KB
/
add-to-ipfs.js
File metadata and controls
152 lines (125 loc) · 4.05 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
const { extname, basename } = require('path')
const { clipboard } = require('electron')
const fs = require('fs-extra')
const i18n = require('i18next')
const { globSource } = require('ipfs-http-client')
const last = require('it-last')
const { analyticsKeys } = require('./analytics/keys')
const logger = require('./common/logger')
const { notify, notifyError } = require('./common/notify')
const getCtx = require('./context')
async function copyFileToMfs (ipfs, cid, filename) {
let i = 0
const ext = extname(filename)
const base = basename(filename, ext)
while (true) {
const newName = (i === 0 ? base : `${base} (${i})`) + ext
try {
await ipfs.files.stat(`/${newName}`)
} catch (err) {
filename = newName
break
}
i++
}
return ipfs.files.cp(`/ipfs/${cid.toString()}`, `/${filename}`)
}
async function getShareableCid (ipfs, files) {
if (files.length === 1) {
// If it's just one object, we link it directly.
return files[0]
}
// Note: we don't use 'object patch' here, it was deprecated.
// We are using MFS for creating CID of an ephemeral directory
// because it handles HAMT-sharding of big directories automatically
// See: https://github.com/ipfs/kubo/issues/8106
const dirpath = `/zzzz_${Date.now()}`
await ipfs.files.mkdir(dirpath, { cidVersion: 1 })
for (const { cid, filename } of files) {
await ipfs.files.cp(`/ipfs/${cid}`, `${dirpath}/${filename}`)
}
const stat = await ipfs.files.stat(dirpath)
await ipfs.files.rm(dirpath, { recursive: true })
return { cid: stat.cid, filename: '' }
}
function sendNotification (launchWebUI, hasFailures, successCount, filename) {
let link, title, body, fn
if (!hasFailures) {
// All worked well!
fn = notify
if (successCount === 1) {
link = `/files/${filename}`
title = i18n.t('itemAddedNotification.title')
body = i18n.t('itemAddedNotification.message')
} else {
link = '/files'
title = i18n.t('itemsAddedNotification.title')
body = i18n.t('itemsAddedNotification.message', { count: successCount })
}
} else {
// Some/all failed!
fn = notifyError
title = i18n.t('itemsFailedNotification.title')
body = i18n.t('itemsFailedNotification.message')
}
// @ts-expect-error
fn({ title, body }, () => {
// force refresh for Files screen to pick up newly added items
// https://github.com/ipfs/ipfs-desktop/issues/1763
launchWebUI(link, { forceRefresh: true })
})
}
async function addFileOrDirectory (ipfs, filepath) {
const stat = fs.statSync(filepath)
let cid = null
if (stat.isDirectory()) {
const files = globSource(filepath, '**/*')
const res = await last(ipfs.addAll(files, {
pin: false,
wrapWithDirectory: true,
cidVersion: 1
}))
cid = res.cid
} else {
const readStream = fs.createReadStream(filepath)
const res = await ipfs.add(readStream, {
pin: false,
cidVersion: 1
})
cid = res.cid
}
const filename = basename(filepath)
await copyFileToMfs(ipfs, cid, filename)
return { cid, filename }
}
module.exports = async function (files) {
const ctx = getCtx()
const getIpfsd = await ctx.getProp('getIpfsd')
const ipfsd = await getIpfsd()
if (!ipfsd) {
return
}
const successes = []
const failures = []
const log = logger.start('[add to ipfs] started', { withAnalytics: analyticsKeys.ADD_VIA_DESKTOP })
await Promise.all(files.map(async file => {
try {
const res = await addFileOrDirectory(ipfsd.api, file)
successes.push(res)
} catch (e) {
failures.push(String(e))
}
}))
if (failures.length > 0) {
log.fail(new Error(failures.join('\n')))
} else {
log.end()
}
const { cid, filename } = await getShareableCid(ipfsd.api, successes)
const launchWebUI = ctx.getFn('launchWebUI')
sendNotification(launchWebUI, failures.length !== 0, successes.length, filename)
const query = filename ? `?filename=${encodeURIComponent(filename)}` : ''
const url = `https://dweb.link/ipfs/${cid.toString()}${query}`
clipboard.writeText(url)
return cid
}