<!doctype html>

<html lang="ja">

<meta charset="utf-8">

<meta name="viewport" content="width=device-width,initial-scale=1">

<title>EQLive 動画アップロード</title>

<style>

:root{color-scheme:light dark}

body{font:15px/1.7 system-ui,"Hiragino Sans","Yu Gothic UI",sans-serif;max-width:780px;margin:28px auto;padding:0 16px}

h1{font-size:20px;margin:0 0 16px}h2{font-size:16px;margin:28px 0 8px}

label{display:block;margin:10px 0 2px;font-weight:600}

input[type=text],input[type=email],input[type=password],input[type=date]{width:100%;box-sizing:border-box;padding:8px;font:inherit}

button{padding:8px 16px;font:inherit;cursor:pointer}

progress{width:100%;height:18px}

table{width:100%;border-collapse:collapse}td,th{border-bottom:1px solid #8884;padding:6px 4px;text-align:left;vertical-align:top;word-break:break-all}

.sub{opacity:.7;font-size:13px}.err{color:#d33}.warn{color:#d33;font-weight:600}

[hidden]{display:none!important}

</style>

<body>

<h1>EQLive 動画アップロード</h1>


<section id="login">

<label>メールアドレス</label><input id="em" type="email" autocomplete="username">

<label>パスワード</label><input id="pw" type="password" autocomplete="current-password">

<p><button id="in">ログイン</button> <span id="lerr" class="err"></span></p>

</section>


<section id="app" hidden>

<p class="sub"><span id="me"></span> <button id="out">ログアウト</button></p>


<label>番組ID</label><input id="sid" type="text" placeholder="例: news-weekly">

<label>動画ファイル(MP4)</label><input id="file" type="file" accept="video/mp4,.mp4">

<label>保存期限(この日の終わりに自動削除)</label>

<input id="exp" type="date"><label style="font-weight:400"><input id="none" type="checkbox"> 期限なし(手動で削除するまで保存)</label>

<p><button id="go">アップロード</button> <span id="msg"></span></p>

<progress id="bar" value="0" max="1" hidden></progress>

<p id="done" hidden>配信用URL:<br><input id="url" type="text" readonly> <button id="cp">コピー</button></p>


<h2>保存中の動画</h2>

<p class="sub" id="usage"></p>

<table><thead><tr><th>動画</th><th>サイズ</th><th>期限</th><th></th></tr></thead><tbody id="rows"></tbody></table>

</section>


<script type="module">

import {initializeApp} from 'https://www.gstatic.com/firebasejs/10.14.1/firebase-app.js';

import {getAuth,signInWithEmailAndPassword,onAuthStateChanged,signOut} from 'https://www.gstatic.com/firebasejs/10.14.1/firebase-auth.js';


// ★ ここを書き換える

const API = 'https://video.eqlive.workers.dev';

const FIREBASE = { apiKey: ''AIzaSyBREDd6ZluDsoliexonII3nY8SYPSH7brQ, authDomain: 'new-eqlive.firebaseapp.com', projectId: 'new-eqlive', appId: '1:454196070227:web:6f738cce873eda2c8543a6' };

const DEFAULT_DAYS = 14, FREE_GB = 10, PART = 50 * 1024 * 1024;


const auth = getAuth(initializeApp(FIREBASE));

const $ = id => document.getElementById(id);

const gb = n => (n / 1e9).toFixed(2) + 'GB';

const urlOf = k => `${API}/v/${k.split('/').map(encodeURIComponent).join('/')}`;

const esc = s => s.replace(/[&<>"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));

const day = d => new Date(Date.now() + d * 864e5 + 9 * 36e5).toISOString().slice(0, 10);


async function api(path, body) {

const t = await auth.currentUser.getIdToken();

const r = await fetch(API + path, { method: body ? 'POST' : 'GET', body: body && JSON.stringify(body), headers: { Authorization: 'Bearer ' + t } });

const j = await r.json();

if (!r.ok) throw new Error(j.error || r.status);

return j;

}


$('exp').value = day(DEFAULT_DAYS);

$('in').onclick = async () => {

$('lerr').textContent = '';

try { await signInWithEmailAndPassword(auth, $('em').value, $('pw').value); }

catch { $('lerr').textContent = 'ログインできませんでした。メールアドレスとパスワードを確認してください'; }

};

$('out').onclick = () => signOut(auth);

onAuthStateChanged(auth, u => {

$('login').hidden = !!u; $('app').hidden = !u;

if (u) { $('me').textContent = u.email; load(); }

});


async function load() {

try {

const j = await api('/api/list');

$('usage').innerHTML = `使用量 ${gb(j.total)} / 無料枠 ${FREE_GB}GB` + (j.total > FREE_GB * 0.8e9 ? ' <span class="warn">無料枠に近づいています</span>' : '');

j.items.sort((a, b) => a.key.localeCompare(b.key));

$('rows').innerHTML = j.items.map(o => `<tr><td>${esc(o.key)}</td><td>${gb(o.size)}</td>

<td>${o.expires === 'none' ? 'なし' : new Date(o.expires).toLocaleDateString('ja-JP')}</td>

<td><button data-cp="${esc(o.key)}">URL</button> <button data-del="${esc(o.key)}">削除</button></td></tr>`).join('')

|| '<tr><td colspan="4" class="sub">まだ動画がありません。上のフォームからアップロードしてください</td></tr>';

} catch (e) { $('usage').innerHTML = `<span class="err">${esc(e.message)}</span>`; }

}


$('rows').onclick = async e => {

const b = e.target;

if (b.dataset.cp) { await navigator.clipboard.writeText(urlOf(b.dataset.cp)); b.textContent = 'コピー済み'; }

if (b.dataset.del && confirm(`${b.dataset.del}\nを削除します。配信に使っていないか確認してください`)) {

await api('/api/delete', { key: b.dataset.del }); load();

}

};

$('cp').onclick = async () => { await navigator.clipboard.writeText($('url').value); $('cp').textContent = 'コピー済み'; };


$('go').onclick = async () => {

const f = $('file').files[0], sid = $('sid').value.trim().replace(/[\s\/\\]/g, '_');

if (!f || !sid) return alert('番組IDと動画ファイルを指定してください');

if (!$('none').checked && !$('exp').value) return alert('保存期限を指定するか、「期限なし」にチェックしてください');

const key = `${sid}/${day(0)}_${f.name.replace(/[\s\/\\]/g, '_')}`;

const expires = $('none').checked ? 'none' : $('exp').value + 'T23:59:59+09:00';

const n = Math.ceil(f.size / PART), parts = [], prog = new Array(n).fill(0);

let next = 0, uploadId;

$('go').disabled = true; $('done').hidden = true; $('bar').hidden = false; $('msg').className = '';

const draw = () => { const s = prog.reduce((a, b) => a + b, 0); $('bar').value = s / f.size; $('msg').textContent = `${Math.floor(s / f.size * 100)}%(${gb(s)} / ${gb(f.size)})`; };


const putPart = async i => {

for (let a = 0; a < 4; a++) {

try {

const t = await auth.currentUser.getIdToken();

return await new Promise((ok, ng) => {

const x = new XMLHttpRequest();

x.open('PUT', `${API}/api/part?key=${encodeURIComponent(key)}&uploadId=${uploadId}&n=${i + 1}`);

x.setRequestHeader('Authorization', 'Bearer ' + t);

x.upload.onprogress = e => { prog[i] = e.loaded; draw(); };

x.onload = () => x.status === 200 ? ok(JSON.parse(x.responseText)) : ng(new Error('HTTP ' + x.status));

x.onerror = () => ng(new Error('通信エラー'));

x.send(f.slice(i * PART, (i + 1) * PART));

});

} catch (e) {

prog[i] = 0;

if (a === 3) throw e;

await new Promise(r => setTimeout(r, 1500 * (a + 1)));

}

}

};

const worker = async () => { while (next < n) { const i = next++; parts[i] = await putPart(i); prog[i] = Math.min(PART, f.size - i * PART); draw(); } };


try {

uploadId = (await api('/api/create', { key, expires })).uploadId;

await Promise.all([worker(), worker(), worker()]);

await api('/api/complete', { key, uploadId, parts });

$('msg').textContent = 'アップロード完了'; $('url').value = urlOf(key); $('done').hidden = false; $('cp').textContent = 'コピー';

load();

} catch (e) {

$('msg').className = 'err'; $('msg').textContent = '失敗: ' + e.message;

if (uploadId) api('/api/abort', { key, uploadId }).catch(() => {});

}

$('go').disabled = false;

};

</script>

</body>

</html>