-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathipfsDirectClient.js
More file actions
172 lines (150 loc) · 4.71 KB
/
ipfsDirectClient.js
File metadata and controls
172 lines (150 loc) · 4.71 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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
// Direct HTTP API client for IPFS to bypass multiaddr protocol issues
const fetch = require('node-fetch');
const config = require('./config');
class IPFSDirectClient {
constructor() {
this.baseURL = `${config.ENDPROTOCOL || 'http'}://${config.ENDPOINT}:${config.ENDPORT}/api/v0`;
this.connected = false;
this.id = null;
}
// Test connection and get node ID
async connect() {
try {
const response = await fetch(`${this.baseURL}/id`, { method: 'POST' });
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
this.id = data.ID;
this.connected = true;
console.log('[IPFSDirectClient] Connected to IPFS node:', this.id);
return data;
} catch (error) {
console.error('[IPFSDirectClient] Connection failed:', error.message);
this.connected = false;
throw error;
}
}
// Get repository statistics
async repoStat() {
const response = await fetch(`${this.baseURL}/repo/stat`, { method: 'POST' });
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return response.json();
}
// Add a file to IPFS using multipart boundary
async add(content) {
const boundary = '----FormDataBoundary' + Math.random().toString(36);
const buffer = Buffer.isBuffer(content) ? content : Buffer.from(content);
// Build multipart form data manually
const body = Buffer.concat([
Buffer.from(`--${boundary}\r\n`),
Buffer.from('Content-Disposition: form-data; name="file"; filename="file"\r\n'),
Buffer.from('Content-Type: application/octet-stream\r\n\r\n'),
buffer,
Buffer.from(`\r\n--${boundary}--\r\n`)
]);
const response = await fetch(`${this.baseURL}/add?pin=false`, {
method: 'POST',
headers: {
'Content-Type': `multipart/form-data; boundary=${boundary}`
},
body: body
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
return {
cid: { toString: () => data.Hash },
path: data.Name,
size: data.Size
};
}
// Pin a CID
async pinAdd(cid) {
const response = await fetch(`${this.baseURL}/pin/add?arg=${cid}`, { method: 'POST' });
if (!response.ok) {
const error = await response.text();
throw new Error(`Pin failed: ${error}`);
}
return response.json();
}
// Unpin a CID
async pinRm(cid) {
const response = await fetch(`${this.baseURL}/pin/rm?arg=${cid}`, { method: 'POST' });
if (!response.ok) {
const error = await response.text();
// Don't throw error if file is not pinned - it's already unpinned
if (error.includes('not pinned')) {
return { Message: 'File was not pinned', Code: 0 };
}
throw new Error(`Unpin failed: ${error}`);
}
return response.json();
}
// List pins (generator function)
async *pinLs(options = {}) {
const path = options.paths && options.paths[0];
const url = path ? `${this.baseURL}/pin/ls?arg=${path}` : `${this.baseURL}/pin/ls`;
const response = await fetch(url, { method: 'POST' });
if (!response.ok) {
if (response.status === 500 && path) {
// Path not found
return;
}
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
for (const [cid, info] of Object.entries(data.Keys || {})) {
yield { cid: { toString: () => cid }, type: info.Type };
}
}
// Compatibility wrapper for ipfs.id()
async id() {
if (!this.connected) {
await this.connect();
}
return { id: this.id };
}
// Compatibility wrapper for ipfs.repo.stat()
repo = {
stat: async () => {
const data = await this.repoStat();
return {
repoSize: data.RepoSize,
storageMax: data.StorageMax,
numObjects: data.NumObjects
};
}
};
// Compatibility wrapper for ipfs.pin
pin = {
add: (cid) => this.pinAdd(cid),
rm: (cid) => this.pinRm(cid),
ls: (options) => this.pinLs(options)
};
}
let directClient = null;
function initializeIPFS() {
if (directClient && directClient.connected) {
return directClient;
}
try {
console.log('[IPFSDirectClient] Initializing direct HTTP client...');
directClient = new IPFSDirectClient();
// Don't connect immediately, let the caller handle it
return directClient;
} catch (e) {
console.error('[IPFSDirectClient] Failed to initialize:', e.message);
return null;
}
}
function getIPFSInstance() {
return directClient;
}
module.exports = {
initializeIPFS,
getIPFSInstance
};