-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
250 lines (223 loc) · 13.1 KB
/
script.js
File metadata and controls
250 lines (223 loc) · 13.1 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
function openTab(evt, tabName) {
const tabcontents = document.getElementsByClassName("tabcontent");
for (let i = 0; i < tabcontents.length; i++) {
tabcontents[i].style.display = "none";
tabcontents[i].classList.remove("active-tab");
}
const tablinks = document.getElementsByClassName("tablinks");
for (let i = 0; i < tablinks.length; i++) {
tablinks[i].classList.remove("active");
}
const target = document.getElementById(tabName);
target.style.display = "block";
target.classList.add("active-tab");
const btns = document.querySelectorAll('.tablinks');
const labels = { 'splitTab': '分割', 'mergeTab': '結合', 'linkTab': '共有', 'shareTab': '共有' };
btns.forEach(b => {
if (b.innerText.includes(labels[tabName])) b.classList.add('active');
});
}
function toggleCustomSize() {
const s = document.getElementById('splitSize');
document.getElementById('customSizeContainer').classList.toggle('hidden', s.value !== 'custom');
}
// URLパラメータによる自動処理
window.addEventListener('load', async () => {
const p = new URLSearchParams(window.location.search);
const z = p.get('zip');
const d = p.get('data');
if (z) {
openTab(null, 'mergeTab');
document.getElementById('mergeFromUrlAlert').classList.remove('hidden');
document.getElementById('fileSelectionArea').classList.add('hidden');
window.targetZipUrl = decodeURIComponent(z);
updateStatus('mergeStatus', `共有URLからリモートZIPを検出しました。`, 'info');
} else if (d) {
openTab(null, 'mergeTab');
document.getElementById('mergeFromUrlAlert').classList.remove('hidden');
document.getElementById('fileSelectionArea').classList.add('hidden');
try {
updateStatus('mergeStatus', 'インラインデータを展開中...', 'info');
const data = JSON.parse(decodeURIComponent(atob(d)));
window.inlineMergeData = data;
updateStatus('mergeStatus', `インラインデータ (${data.name}) 読込成功。`, 'success');
} catch(e) { updateStatus('mergeStatus', '解析エラー。リンクが壊れている可能性があります。', 'error'); }
}
});
document.getElementById('splitButton').addEventListener('click', async function() {
const input = document.getElementById('fileToSplit');
let sizeMB = document.getElementById('splitSize').value;
if (sizeMB === 'custom') sizeMB = document.getElementById('customSplitSize').value;
const splitSize = parseInt(sizeMB) * 1024 * 1024;
const encOpt = document.getElementById('encryptOption').value;
const pass = encOpt === 'aes256' ? document.getElementById('encryptPassword').value : null;
if (!input.files[0]) return updateStatus('splitStatus', 'ファイルを選んでください', 'error');
try {
const file = input.files[0];
updateStatus('splitStatus', '処理中...', 'info');
document.getElementById('inlineShareArea').classList.add('hidden');
const hash = await calculateSHA256MacroChunked(file, (p) => {
document.getElementById('splitProgress').style.width = `${p * 0.2}%`;
});
// インラインURL生成
if (file.size < 2 * 1024 * 1024) {
updateStatus('splitStatus', 'インラインURLを生成中...', 'info');
const ab = await readFileAsArrayBuffer(file);
const uint8 = new Uint8Array(ab);
let binary = '';
for (let i = 0; i < uint8.byteLength; i++) binary += String.fromCharCode(uint8[i]);
const b64 = btoa(binary);
const shareData = { name: file.name, hash: hash, data: b64 };
const encoded = btoa(encodeURIComponent(JSON.stringify(shareData)));
const url = `${window.location.href.split('?')[0]}?data=${encoded}`;
document.getElementById('quickShareResultInline').value = url;
document.getElementById('inlineShareArea').classList.remove('hidden');
}
const count = Math.ceil(file.size / splitSize);
const zip = new JSZip();
zip.file("metadata.json", JSON.stringify({ originalName: file.name, totalChunkCount: count, fileSize: file.size, hash: hash, encrypted: encOpt === 'aes256' }));
if (encOpt !== 'aes256') {
for (let i = 0; i < count; i++) zip.file(`part${i+1}.bin`, file.slice(i*splitSize, (i+1)*splitSize));
} else {
const ab = await readFileAsArrayBuffer(file);
const enc = await encryptData(ab, pass);
const s = enc.byteLength / count;
for (let i = 0; i < count; i++) zip.file(`part${i+1}.bin`, enc.slice(i*s, (i+1)*s));
}
const blob = await zip.generateAsync({type:'blob', zip64:true, compression: file.size > 500*1024*1024 ? 'STORE':'DEFLATE'}, (m) => {
document.getElementById('splitProgress').style.width = `${20 + m.percent * 0.8}%`;
});
updateStatus('splitStatus', '完了!', 'success');
document.getElementById('splitResults').style.display = 'block';
document.getElementById('splitFilesList').innerHTML = `<p><span>ファイル:</span> ${file.name}</p><p><span>サイズ:</span> ${formatFileSize(file.size)}</p>`;
const url = URL.createObjectURL(blob);
document.getElementById('downloadAllButton').onclick = () => {
const a = document.createElement('a'); a.href = url; a.download = `${file.name}_all.zip`; a.click();
};
document.getElementById('postSplitShareArea').classList.remove('hidden');
} catch(e) { updateStatus('splitStatus', `エラー: ${e.message}`, 'error'); }
});
document.getElementById('mergeButton').addEventListener('click', async function() {
try {
let meta, pMap = {};
if (window.targetZipUrl) {
updateStatus('mergeStatus', 'リモートから読込中...', 'info');
const res = await fetch(window.targetZipUrl);
const blob = await res.blob();
const zip = await JSZip.loadAsync(blob);
meta = JSON.parse(await zip.file("metadata.json").async('text'));
zip.file(/part\d+\.bin$/).forEach(f => pMap[parseInt(f.name.match(/\d+/)[0])] = f);
meta.count = meta.totalChunkCount;
} else if (window.inlineMergeData) {
updateStatus('mergeStatus', '展開中...', 'info');
meta = window.inlineMergeData;
const b64 = meta.data;
const binary = atob(b64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
const resultBlob = new Blob([bytes]);
const h = await calculateSHA256MacroChunked(resultBlob);
if (h !== meta.hash) throw new Error('ハッシュ不一致');
updateStatus('mergeStatus', '成功!', 'success');
document.getElementById('mergeResults').style.display = 'block';
const url = URL.createObjectURL(resultBlob);
document.getElementById('downloadMergedButton').onclick = () => {
const a = document.createElement('a'); a.href = url; a.download = meta.name; a.click();
};
return;
} else {
const input = document.getElementById('zipToMerge');
for (let i = 0; i < input.files.length; i++) {
const zip = await JSZip.loadAsync(input.files[i]);
const m = JSON.parse(await zip.file("metadata.json").async('text'));
if (!meta) meta = m;
zip.file(/part\d+\.bin$/).forEach(f => pMap[parseInt(f.name.match(/\d+/)[0])] = f);
}
if (!meta) throw new Error('ファイルが未選択です。');
meta.count = meta.totalChunkCount || meta.chunkCount;
}
updateStatus('mergeStatus', '結合中...', 'info');
const blobs = [];
for (let i = 1; i <= meta.count; i++) blobs.push(await pMap[i].async('blob'));
let result;
if (meta.encrypted) {
const pass = document.getElementById('decryptPassword').value;
if (!pass) { document.getElementById('decryptContainer').style.display = 'block'; throw new Error('パスワード必要'); }
result = await decryptData(await readFileAsArrayBuffer(new Blob(blobs)), pass);
} else result = new Blob(blobs);
updateStatus('mergeStatus', '検証中...', 'info');
const h = await calculateSHA256MacroChunked(result instanceof Blob ? result : new Blob([result]));
if (h !== meta.hash) throw new Error('ハッシュ不一致');
updateStatus('mergeStatus', '成功!', 'success');
document.getElementById('mergeResults').style.display = 'block';
const url = URL.createObjectURL(result instanceof Blob ? result : new Blob([result]));
document.getElementById('downloadMergedButton').onclick = () => {
const a = document.createElement('a'); a.href = url; a.download = meta.originalName || meta.name; a.click();
};
} catch(e) { updateStatus('mergeStatus', `エラー: ${e.message}`, 'error'); }
});
document.getElementById('generateQuickLink').addEventListener('click', () => {
const url = document.getElementById('inputZipUrl').value;
if (!url) return alert('URLを入れてください');
const shareUrl = `${window.location.href.split('?')[0]}?zip=${encodeURIComponent(url)}`;
document.getElementById('quickShareResult').value = shareUrl;
document.getElementById('quickShareArea').classList.remove('hidden');
});
// コピー機能の改善
async function copyToClipboard(id) {
const el = document.getElementById(id);
const text = el.value || el.innerText;
try {
// モダンなAPIを第一選択とする
if (navigator.clipboard) {
await navigator.clipboard.writeText(text);
} else {
// フォールバック: display:none ではなく画面外で見えない状態にしてコピー
el.style.display = 'block';
el.style.position = 'absolute';
el.style.left = '-9999px';
el.select();
document.execCommand('copy');
el.style.display = 'none';
}
alert('URLをコピーしました!');
} catch (err) {
console.error('コピー失敗:', err);
alert('コピーに失敗しました。お手数ですが、手動でコピーしてください。');
}
}
function updateStatus(id, msg, type) {
const el = document.getElementById(id); el.textContent = msg;
el.style.color = type === 'error' ? '#ed4245' : type === 'success' ? '#3ba55c' : '#ffffff';
}
function readFileAsArrayBuffer(f) { return new Promise((r, j) => { const rd = new FileReader(); rd.onload = () => r(rd.result); rd.onerror = j; rd.readAsArrayBuffer(f); }); }
async function calculateSHA256MacroChunked(blob, onProgress) {
const macroSize = 100 * 1024 * 1024;
const sha256 = CryptoJS.algo.SHA256.create();
for (let offset = 0; offset < blob.size; offset += macroSize) {
const slice = blob.slice(offset, offset + macroSize);
const buffer = await readFileAsArrayBuffer(slice);
sha256.update(CryptoJS.lib.WordArray.create(buffer));
if (onProgress) onProgress((offset + slice.size) / blob.size * 100);
await new Promise(r => setTimeout(r, 0));
}
return sha256.finalize().toString();
}
async function encryptData(d, p) {
const s = crypto.getRandomValues(new Uint8Array(16));
const m = await crypto.subtle.importKey('raw', new TextEncoder().encode(p), {name: 'PBKDF2'}, false, ['deriveKey']);
const k = await crypto.subtle.deriveKey({name: 'PBKDF2', salt: s, iterations: 100000, hash: 'SHA-256'}, m, {name: 'AES-CBC', length: 256}, false, ['encrypt', 'decrypt']);
const iv = crypto.getRandomValues(new Uint8Array(16));
const enc = await crypto.subtle.encrypt({name: 'AES-CBC', iv: iv}, k, d);
const res = new Uint8Array(s.length + iv.length + enc.byteLength);
res.set(s, 0); res.set(iv, s.length); res.set(new Uint8Array(enc), s.length + iv.length);
return res.buffer;
}
async function decryptData(d, p) {
const da = new Uint8Array(d); const s = da.slice(0, 16); const iv = da.slice(16, 32); const enc = da.slice(32);
const m = await crypto.subtle.importKey('raw', new TextEncoder().encode(p), {name: 'PBKDF2'}, false, ['deriveKey']);
const k = await crypto.subtle.deriveKey({name: 'PBKDF2', salt: s, iterations: 100000, hash: 'SHA-256'}, m, {name: 'AES-CBC', length: 256}, false, ['encrypt', 'decrypt']);
return await crypto.subtle.decrypt({name: 'AES-CBC', iv: iv}, k, enc);
}
function formatFileSize(b) { if (b === 0) return '0 Bytes'; const k = 1024; const s = ['Bytes', 'KB', 'MB', 'GB', 'TB']; const i = Math.floor(Math.log(b) / Math.log(k)); return parseFloat((b / Math.pow(k, i)).toFixed(2)) + ' ' + s[i]; }
function getMimeType(f) { const ext = f.split('.').pop().toLowerCase(); const m = { 'jpg': 'image/jpeg', 'png': 'image/png', 'gif': 'image/gif', 'webp': 'image/webp', 'mp4': 'video/mp4', 'webm': 'video/webm', 'mp3': 'audio/mpeg', 'wav': 'audio/wav', 'pdf': 'application/pdf', 'zip': 'application/zip' }; return m[ext] || 'application/octet-stream'; }