archive-ccc8458/video/api/chunked/finalize.php 5.8 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
<?php
declare(strict_types=1);
header('Content-Type: application/json');

require_once __DIR__ . '/../../lib/auth.php';
require_once __DIR__ . '/../../lib/chunked.php';

require_https();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'method not allowed']);
    exit;
}

if (!rate_limit_check()) {
    http_response_code(429);
    echo json_encode(['error' => 'too many failed attempts, try again later']);
    exit;
}

$pw = password_from_request();
if ($pw === null || $pw === '' || !verify_password($pw)) {
    rate_limit_fail();
    http_response_code(401);
    echo json_encode(['error' => 'invalid password']);
    exit;
}
rate_limit_reset();

// upload_id accepted from form field (so multipart with thumbnail works) or JSON body.
$id = (string)($_POST['upload_id'] ?? '');
if ($id === '' && str_starts_with($_SERVER['CONTENT_TYPE'] ?? '', 'application/json')) {
    $body = json_decode((string) file_get_contents('php://input'), true);
    if (is_array($body)) $id = (string)($body['upload_id'] ?? '');
}

if (!is_valid_upload_id($id)) {
    http_response_code(400);
    echo json_encode(['error' => 'invalid upload id']);
    exit;
}
$meta = read_meta($id);
if ($meta === null) {
    http_response_code(404);
    echo json_encode(['error' => 'unknown upload id']);
    exit;
}

$expected  = (int) $meta['expected_chunks'];
$totalSize = (int) $meta['total_size'];

// Verify every chunk is present and tally the total size.
$missing = [];
$sumSize = 0;
for ($i = 0; $i < $expected; $i++) {
    $p = chunk_path($id, $i);
    if ($p === null || !is_file($p)) {
        $missing[] = $i;
    } else {
        $sumSize += filesize($p) ?: 0;
    }
}
if (count($missing) > 0) {
    http_response_code(409);
    echo json_encode([
        'error'   => 'missing chunks',
        'missing' => $missing,
        'received'=> $expected - count($missing),
        'expected'=> $expected,
    ]);
    exit;
}
if ($sumSize !== $totalSize) {
    http_response_code(409);
    echo json_encode([
        'error'    => 'reassembled size mismatch',
        'expected' => $totalSize,
        'got'      => $sumSize,
    ]);
    exit;
}

// Reassemble into a temp file via streaming so we never load the whole thing into RAM.
$tmp = tempnam(sys_get_temp_dir(), 'reassemble-');
if ($tmp === false) {
    http_response_code(500);
    echo json_encode(['error' => 'could not create temp file']);
    exit;
}
$out = fopen($tmp, 'wb');
if ($out === false) {
    @unlink($tmp);
    http_response_code(500);
    echo json_encode(['error' => 'could not open temp file']);
    exit;
}
for ($i = 0; $i < $expected; $i++) {
    $p = chunk_path($id, $i);
    $in = fopen($p, 'rb');
    if ($in === false) {
        fclose($out); @unlink($tmp);
        http_response_code(500);
        echo json_encode(['error' => 'could not read chunk', 'index' => $i]);
        exit;
    }
    if (stream_copy_to_stream($in, $out) === false) {
        fclose($in); fclose($out); @unlink($tmp);
        http_response_code(500);
        echo json_encode(['error' => 'reassembly copy failed', 'index' => $i]);
        exit;
    }
    fclose($in);
}
fclose($out);

// Server-side MIME sniff on the reassembled bytes — the declared MIME from init is not trusted.
$mime = (new finfo(FILEINFO_MIME_TYPE))->file($tmp) ?: '';
if (!isset(ALLOWED_TYPES[$mime])) {
    @unlink($tmp);
    delete_upload_dir($id);
    http_response_code(415);
    echo json_encode(['error' => 'unsupported video type', 'detected' => $mime]);
    exit;
}
$ext = ALLOWED_TYPES[$mime];

if (!is_dir(VIDEO_DIR)) @mkdir(VIDEO_DIR, 0755, true);

do {
    $hash = generate_video_hash();
    $dest = VIDEO_DIR . '/' . $hash . '.' . $ext;
} while (file_exists($dest));

if (!@rename($tmp, $dest)) {
    // Cross-device rename can fail (sys_get_temp_dir() may be on a different mount).
    if (!@copy($tmp, $dest)) {
        @unlink($tmp);
        http_response_code(500);
        echo json_encode(['error' => 'could not save file']);
        exit;
    }
    @unlink($tmp);
}
@chmod($dest, 0644);

// Optional thumbnail — same validation rules as /api/upload.
$thumbUrl = null;
if (isset($_FILES['thumbnail']) && $_FILES['thumbnail']['error'] !== UPLOAD_ERR_NO_FILE) {
    $t = $_FILES['thumbnail'];
    if ($t['error'] !== UPLOAD_ERR_OK) {
        @unlink($dest);
        delete_upload_dir($id);
        http_response_code(400);
        echo json_encode(['error' => 'thumbnail upload failed', 'code' => $t['error']]);
        exit;
    }
    if ($t['size'] > MAX_THUMB_BYTES) {
        @unlink($dest);
        delete_upload_dir($id);
        http_response_code(413);
        echo json_encode(['error' => 'thumbnail too large']);
        exit;
    }
    $tMime = (new finfo(FILEINFO_MIME_TYPE))->file($t['tmp_name']) ?: '';
    if (!isset(ALLOWED_THUMB_TYPES[$tMime])) {
        @unlink($dest);
        delete_upload_dir($id);
        http_response_code(415);
        echo json_encode(['error' => 'unsupported thumbnail type', 'detected' => $tMime]);
        exit;
    }
    $tExt = ALLOWED_THUMB_TYPES[$tMime];
    $tDest = VIDEO_DIR . '/' . $hash . '.' . $tExt;
    if (!move_uploaded_file($t['tmp_name'], $tDest)) {
        @unlink($dest);
        delete_upload_dir($id);
        http_response_code(500);
        echo json_encode(['error' => 'could not save thumbnail']);
        exit;
    }
    @chmod($tDest, 0644);
    $thumbUrl = SITE_BASE . VIDEO_URL . '/' . $hash . '.' . $tExt;
}

$unlisted = filter_var($_POST['unlisted'] ?? false, FILTER_VALIDATE_BOOLEAN);
set_unlisted($hash, $unlisted);

delete_upload_dir($id);

echo json_encode([
    'hash'      => $hash,
    'url'       => SITE_BASE . '/video/' . $hash,
    'embed'     => SITE_BASE . '/video/' . $hash . '/embed',
    'file'      => SITE_BASE . VIDEO_URL . '/' . $hash . '.' . $ext,
    'thumbnail' => $thumbUrl,
    'unlisted'  => $unlisted,
]);