Repository navigation
Expand file tree
/
Copy pathcekmetadata.sh
More file actions
491 lines (430 loc) · 18.6 KB
/
Copy pathcekmetadata.sh
File metadata and controls
491 lines (430 loc) · 18.6 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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
#!/usr/bin/env bash
# cekmetadata.sh — Kelola app upload + ExifTool -> data.csv + tabel UI Tailwind + Export Excel
# Perintah:
# ./cekmetadata.sh install # tulis file, siapkan venv & Flask+openpyxl (+cek exiftool)
# ./cekmetadata.sh jalankan # jalankan server (background, PID + log)
# ./cekmetadata.sh stop # hentikan server
# ./cekmetadata.sh logs # tail -f log
# ./cekmetadata.sh buat-ulang # stop -> install -> start
set -euo pipefail
APP_DIR="${PWD}/cekmetadata_app"
VENV_DIR="${APP_DIR}/.venv"
PID_FILE="${APP_DIR}/run/cekmetadata.pid"
LOG_FILE="${APP_DIR}/logs/cekmetadata.log"
HOST="${HOST:-0.0.0.0}"
PORT="${PORT:-5000}"
usage() {
cat <<EOF
:####: ## ### ### ##
###### ## ### ### ## ## ##
:##: .# ## ###::### ## ## ##
## .####: ## ##: ### ### .####: ####### :#### :###.## :#### ####### :####
##. .######: ## ##: ## ## ## .######: ####### ###### :####### ###### ####### ######
## ##: :## ##:##: ##:##:## ##: :## ## #: :## ### ### #: :## ## #: :##
## ######## #### ##.##.## ######## ## :##### ##. .## :##### ## :#####
##. ######## ##### ## ## ## ######## ## .####### ## ## .####### ## .#######
## ## ##.### ## ## ## ## ## . ## ##. .## ## . ## ## ## . ##
:##: .# ###. :# ## ##: ## ## ###. :# ##. ##: ### ### ### ##: ### ##. ##: ###
###### .####### ## :## ## ## .####### ##### ######## :####### ######## ##### ########
:####: .#####: ## ### ## ## .#####: .#### ###.## :###.## ###.## .#### ###.##
Created by @anlaotz
Metadata Viewer — ExifTool + SHA256
pakai: $0 {install|jalankan|stop|logs|buat-ulang}
Env opsional:
HOST=0.0.0.0 PORT=5000
Contoh:
$0 install
HOST=127.0.0.1 PORT=8080 $0 jalankan
$0 logs
EOF
}
have_cmd() { command -v "$1" >/dev/null 2>&1; }
detect_pkg() {
if have_cmd apt-get; then echo "apt"; return
elif have_cmd apt; then echo "apt"; return
elif have_cmd dnf; then echo "dnf"; return
elif have_cmd yum; then echo "yum"; return
elif have_cmd pacman; then echo "pacman"; return
elif have_cmd apk; then echo "apk"; return
else echo "none"; return
fi
}
pkg_install() {
local mgr="$1"; shift
local pkgs=("$@")
case "$mgr" in
apt) sudo apt-get update -y && sudo apt-get install -y "${pkgs[@]}" ;;
dnf) sudo dnf install -y "${pkgs[@]}" ;;
yum) sudo yum install -y "${pkgs[@]}" ;;
pacman) sudo pacman -Sy --noconfirm "${pkgs[@]}" ;;
apk) sudo apk add --no-cache "${pkgs[@]}" ;;
none) return 1 ;;
esac
}
ensure_layout() {
mkdir -p "${APP_DIR}/uploads" "${APP_DIR}/run" "${APP_DIR}/logs"
}
write_index_html() {
cat > "${APP_DIR}/index.html" <<'HTML'
<!doctype html>
<html lang="id">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Metadata Viewer — ExifTool + SHA256</title>
<!-- Tailwind CDN -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme:{extend:{
colors:{ brand:{DEFAULT:'#0ea5e9'} }
}}
}
</script>
<style>
html,body{height:100%}
.vh { height: calc(100vh - 2rem); }
.sticky-th { position: sticky; top: 0; background: #ffffff; z-index: 10; }
</style>
</head>
<body class="bg-white text-slate-800 antialiased">
<main class="px-4 py-4 xl:px-6 xl:py-4">
<div class="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between mb-4">
<div>
<h1 class="text-2xl font-bold">Metadata Viewer — ExifTool + SHA256</h1>
<p class="text-slate-500">Upload banyak file → metadata tercatat ke <code>data.csv</code> → tampil langsung → Export Excel / Bersih.</p>
</div>
<div class="flex flex-wrap gap-2">
<a href="/export_xlsx" target="_blank"
class="px-4 py-2 rounded-lg bg-emerald-600 text-white hover:bg-emerald-500">Export Excel</a>
<button id="btnBersih"
class="px-4 py-2 rounded-lg bg-rose-600 text-white hover:bg-rose-500">Bersih</button>
</div>
</div>
<section class="rounded-xl border border-slate-200 p-4 mb-4">
<form id="formUpload" class="flex flex-col md:flex-row gap-3 items-start md:items-center">
<input id="files" name="files" type="file" multiple required
class="block w-full md:w-auto text-sm
file:mr-4 file:py-2 file:px-4
file:rounded-md file:border file:border-slate-300
file:text-sm file:font-medium
file:bg-white file:text-slate-700
hover:file:bg-slate-50"/>
<button type="submit"
class="px-4 py-2 rounded-md bg-brand text-white hover:bg-sky-600">
Proses
</button>
<span id="status" class="text-slate-500"></span>
</form>
<div id="progress" class="h-2 bg-slate-200 rounded mt-3 hidden">
<div id="bar" class="h-2 bg-brand rounded" style="width:0%"></div>
</div>
</section>
<section class="flex flex-col md:flex-row md:items-center gap-3 justify-between mb-3">
<div class="flex gap-2 items-center">
<span class="text-slate-500">Total baris:</span>
<span id="rowCount" class="px-2 py-1 rounded bg-slate-100 border border-slate-200">0</span>
</div>
<div class="flex gap-2 items-center w-full md:w-auto">
<input id="q" type="text" placeholder="Cari (nama file, author, MIME, dll.)"
class="w-full md:w-96 px-3 py-2 rounded-md bg-white border border-slate-300 focus:outline-none focus:ring-2 focus:ring-sky-200" />
<button id="btnReset" class="px-3 py-2 rounded-md bg-white border border-slate-300 hover:bg-slate-50">
Reset
</button>
</div>
</section>
<section class="rounded-xl border border-slate-200 overflow-hidden">
<div class="overflow-auto vh">
<table class="min-w-full text-sm">
<thead class="text-left text-slate-600 border-b border-slate-200">
<tr id="thead"></tr>
</thead>
<tbody id="tbody" class="divide-y divide-slate-100"></tbody>
</table>
</div>
</section>
</main>
<script>
const el = (id)=>document.getElementById(id);
const form = el('formUpload'), files = el('files'), statusEl = el('status');
const progress = el('progress'), bar = el('bar');
const rowCount = el('rowCount'), thead = el('thead'), tbody = el('tbody');
const q = el('q'), btnReset = el('btnReset'), btnBersih = el('btnBersih');
let headers = []; let rows = []; let filtered = [];
function renderHeader(){
thead.innerHTML = headers.map(h =>
`<th class="sticky-th px-3 py-2 border-r last:border-r-0 border-slate-200 text-xs font-semibold uppercase tracking-wide">${h}</th>`
).join('');
}
function renderBody(data){
tbody.innerHTML = data.map(r => `
<tr class="hover:bg-slate-50">
${r.map((c,i) => {
const v = (c ?? '').toString();
if (headers[i]==='SHA256' && v && !v.startsWith('(')) {
return `<td class="px-3 py-2 font-mono text-[11px] break-all">
<span>${v}</span>
<button class="ml-2 px-2 py-0.5 rounded border border-slate-300 text-xs hover:bg-slate-100"
onclick="navigator.clipboard.writeText('${v}')">Salin</button>
</td>`;
}
return `<td class="px-3 py-2">${escapeHtml(v)}</td>`;
}).join('')}
</tr>
`).join('');
rowCount.textContent = data.length;
}
function escapeHtml(s){return s.replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]))}
function applyFilter(){
const term=(q.value||'').toLowerCase().trim();
if(!term){ filtered=rows.slice(); renderBody(filtered); return; }
filtered=rows.filter(r=>r.some(c=>(c||'').toString().toLowerCase().includes(term)));
renderBody(filtered);
}
async function loadData(){
const r=await fetch('/data_json'); const d=await r.json();
headers=d.headers||[]; rows=d.rows||[]; filtered=rows.slice();
renderHeader(); renderBody(filtered);
}
form.addEventListener('submit',(e)=>{
e.preventDefault();
if(!files.files.length){statusEl.textContent='Pilih file dulu.';return;}
statusEl.textContent='Mengunggah & memproses...'; progress.classList.remove('hidden'); bar.style.width='0%';
const xhr=new XMLHttpRequest(); const fd=new FormData();
[...files.files].forEach(f=>fd.append('files',f));
xhr.open('POST','/upload');
xhr.upload.onprogress=(ev)=>{ if(ev.lengthComputable){ bar.style.width=Math.round(ev.loaded/ev.total*100)+'%'; } };
xhr.onload=async()=>{ bar.style.width='100%'; progress.classList.add('hidden');
if(xhr.status===200){ await loadData(); statusEl.textContent='Berhasil ditambahkan.'; form.reset(); }
else{ statusEl.textContent='Gagal: '+xhr.responseText; }
};
xhr.onerror=()=>{ statusEl.textContent='Kesalahan jaringan.'; progress.classList.add('hidden'); };
xhr.send(fd);
});
q.addEventListener('input',applyFilter);
btnReset.addEventListener('click',()=>{ q.value=''; applyFilter(); });
btnBersih.addEventListener('click', async ()=>{
if(!confirm('Yakin hapus semua data (data.csv & uploads)?')) return;
const r=await fetch('/bersih',{method:'POST'});
if(r.ok){ await loadData(); statusEl.textContent='Data dibersihkan.'; }
});
loadData();
</script>
</body>
</html>
HTML
}
write_server_py() {
cat > "${APP_DIR}/server.py" <<'PY'
from __future__ import annotations
import os, subprocess, json, csv
from pathlib import Path
from flask import Flask, request, jsonify, send_file, abort
BASE_DIR = Path(__file__).parent.resolve()
UPLOAD_DIR = BASE_DIR / "uploads"
CSV_FILE = BASE_DIR / "data.csv"
XLSX_FILE = BASE_DIR / "metadata.xlsx"
UPLOAD_DIR.mkdir(exist_ok=True)
COLUMNS = [
("ExifTool Version Number", ["ExifToolVersion","ExifTool Version Number"]),
("File Name", ["FileName","File Name"]),
("File Size", ["FileSize","File Size"]),
("File Modification Date/Time", ["FileModifyDate","File Modification Date/Time"]),
("File Access Date/Time", ["FileAccessDate","File Access Date/Time"]),
("File Inode Change Date/Time", ["FileInodeChangeDate","File Inode Change Date/Time"]),
("File Permissions", ["FilePermissions","File Permissions"]),
("File Type", ["FileType","File Type"]),
("File Type Extension", ["FileTypeExtension","File Type Extension"]),
("MIME Type", ["MIMEType","MIME Type"]),
("PDF Version", ["PDFVersion","PDF Version"]),
("Linearized", ["Linearized"]),
("Page Count", ["PageCount","Page Count"]),
("Language", ["Language"]),
("Tagged PDF", ["Tagged PDF","TaggedPDF"]),
("XMP Toolkit", ["XMP Toolkit","XMPToolkit"]),
("Producer", ["Producer"]),
("Creator", ["Creator"]),
("Creator Tool", ["CreatorTool","Creator Tool"]),
("Create Date", ["CreateDate","Create Date"]),
("Modify Date", ["ModifyDate","Modify Date"]),
("Document ID", ["DocumentID","Document ID"]),
("Instance ID", ["InstanceID","Instance ID"]),
("Author", ["Author"]),
("Title", ["Title"]),
("SHA256", ["SHA256"]),
]
def sha256sum(path: Path, chunk_size: int = 1024*1024) -> str:
import hashlib; h=hashlib.sha256()
with path.open('rb') as f:
for chunk in iter(lambda:f.read(chunk_size), b''): h.update(chunk)
return h.hexdigest()
def ensure_csv_header():
if not CSV_FILE.exists():
with CSV_FILE.open('w',newline='',encoding='utf-8') as f:
csv.writer(f).writerow([label for label,_ in COLUMNS])
def append_row(row: dict):
ensure_csv_header(); ordered=[]
for _,keys in COLUMNS:
val=""
for k in keys:
if k in row and row[k] is not None:
v=row[k]
if isinstance(v,(list,dict)): v=json.dumps(v,ensure_ascii=False)
val=str(v); break
ordered.append(val)
with CSV_FILE.open('a',newline='',encoding='utf-8') as f:
csv.writer(f).writerow(ordered)
def read_csv():
if not CSV_FILE.exists(): return {"headers":[l for l,_ in COLUMNS],"rows":[]}
with CSV_FILE.open('r',encoding='utf-8') as f: rows=list(csv.reader(f))
if not rows: return {"headers":[l for l,_ in COLUMNS],"rows":[]}
return {"headers":rows[0],"rows":rows[1:]}
app=Flask(__name__,static_folder=str(BASE_DIR),static_url_path="")
@app.get("/")
def index(): return app.send_static_file("index.html")
@app.get("/data_json")
def data_json(): return jsonify(read_csv())
@app.post("/bersih")
def bersih():
if CSV_FILE.exists(): CSV_FILE.unlink()
for p in UPLOAD_DIR.iterdir():
if p.is_file(): p.unlink()
return jsonify({"ok":True})
@app.get("/export_xlsx")
def export_xlsx():
if not CSV_FILE.exists(): abort(404,"Belum ada data")
import openpyxl
wb=openpyxl.Workbook(); ws=wb.active; ws.title="Metadata"
with CSV_FILE.open('r',encoding='utf-8') as f:
for r_idx,row in enumerate(csv.reader(f),start=1):
for c_idx,val in enumerate(row,start=1): ws.cell(r_idx,c_idx,val)
wb.save(XLSX_FILE)
return send_file(XLSX_FILE,as_attachment=True,download_name="metadata.xlsx")
@app.post("/upload")
def upload():
files=request.files.getlist("files")
if not files: return "Tidak ada file",400
saved=[]
for f in files:
dst=UPLOAD_DIR/f.filename; f.save(dst); saved.append(str(dst))
try:
proc=subprocess.run(["exiftool","-j",*saved],capture_output=True,text=True)
if proc.returncode!=0: return f"Exiftool error: {proc.stderr}",500
data=json.loads(proc.stdout)
for row in data:
src=row.get("SourceFile"); fp=None
if src and Path(src).exists(): fp=Path(src)
else:
fn=row.get("FileName") or row.get("File Name")
if fn and (UPLOAD_DIR/fn).exists(): fp=UPLOAD_DIR/fn
row["SHA256"]=sha256sum(fp) if fp and fp.exists() else "(file tidak ditemukan)"
append_row(row)
return jsonify({"ok":True,"added":len(data)})
except Exception as e: return f"Error: {e}",500
if __name__=="__main__":
app.run(host=os.environ.get("HOST","0.0.0.0"),port=int(os.environ.get("PORT",5000)),debug=True)
PY
}
ensure_python_and_tools() {
local mgr
mgr="$(detect_pkg)"
# python3 wajib
if ! have_cmd python3; then
echo "❌ python3 tidak ditemukan."
if [ "$mgr" != "none" ]; then
echo "-> mencoba memasang python3..."
pkg_install "$mgr" python3 || true
fi
have_cmd python3 || { echo "Mohon pasang python3 secara manual."; exit 1; }
fi
# venv modul (Debian/Ubuntu sering butuh paket terpisah)
if ! python3 -c "import venv" 2>/dev/null; then
if [ "$mgr" != "none" ]; then
echo "-> memasang python3-venv..."
pkg_install "$mgr" python3-venv || true
fi
python3 -c "import venv" 2>/dev/null || {
echo "❌ Modul venv tidak tersedia. Pasang 'python3-venv' lalu ulangi."
exit 1
}
fi
# exiftool
if ! have_cmd exiftool; then
echo "ℹ️ exiftool belum ada."
if [ "$mgr" = "apt" ]; then
echo "-> memasang libimage-exiftool-perl..."
pkg_install "$mgr" libimage-exiftool-perl || true
elif [ "$mgr" = "dnf" ] || [ "$mgr" = "yum" ]; then
pkg_install "$mgr" perl-Image-ExifTool || true
elif [ "$mgr" = "pacman" ]; then
pkg_install "$mgr" exiftool || true
elif [ "$mgr" = "apk" ]; then
pkg_install "$mgr" exiftool || true
fi
if ! have_cmd exiftool; then
echo "⚠️ exiftool tidak terpasang via paket. Anda tetap bisa lanjut, tapi fitur metadata tidak akan bekerja sampai exiftool tersedia."
fi
fi
}
create_or_fix_venv() {
[ -d "${VENV_DIR}" ] || python3 -m venv "${VENV_DIR}"
# aktifkan venv
# shellcheck source=/dev/null
source "${VENV_DIR}/bin/activate"
# Pastikan pip ada (perbaikan masalah Anda)
if ! python -c "import pip" 2>/dev/null; then
echo "-> pip belum ada di venv, menjalankan ensurepip..."
python -m ensurepip --upgrade || true
fi
if ! python -c "import pip" 2>/dev/null; then
echo "❌ Gagal menyediakan pip di venv."
echo " Periksa apakah paket 'python3-venv' / 'ensurepip' terpasang di sistem."
deactivate || true
exit 1
fi
# Upgrade pip & pasang deps Python
python -m pip install --upgrade pip wheel setuptools >/dev/null
python -m pip install flask openpyxl >/dev/null
deactivate
}
install() {
echo "==> Menyiapkan direktori: ${APP_DIR}"
ensure_layout
echo "==> Menulis index.html & server.py"
write_index_html; write_server_py
echo "==> Mengecek Python/venv & exiftool"
ensure_python_and_tools
echo "==> Menyiapkan virtualenv & deps Python"
create_or_fix_venv
echo "✅ Install selesai."
}
is_running() { [ -f "${PID_FILE}" ] && ps -p "$(cat "${PID_FILE}" 2>/dev/null)" >/dev/null 2>&1; }
jalankan() {
ensure_layout
if is_running; then echo "Sudah jalan (PID $(cat "${PID_FILE}"))"; exit 0; fi
# shellcheck source=/dev/null
source "${VENV_DIR}/bin/activate"
mkdir -p "$(dirname "${LOG_FILE}")"
echo "==> Menjalankan server di background ..."
HOST="${HOST}" PORT="${PORT}" nohup python "${APP_DIR}/server.py" >> "${LOG_FILE}" 2>&1 &
echo $! > "${PID_FILE}"
deactivate
echo "✅ Jalan (PID $(cat "${PID_FILE}")), akses http://${HOST}:${PORT}/"
echo " Log: $0 logs"
}
stop() {
if ! is_running; then echo "Tidak jalan"; rm -f "${PID_FILE}"; return; fi
kill "$(cat "${PID_FILE}")" 2>/dev/null || true
rm -f "${PID_FILE}"
echo "✅ Berhenti."
}
logs() { tail -f "${LOG_FILE}"; }
buat_ulang() { stop || true; install; jalankan; }
case "${1:-}" in
install) install ;;
jalankan) jalankan ;;
stop) stop ;;
logs) logs ;;
buat-ulang) buat_ulang ;;
*) usage; exit 1 ;;
esac