Commit 306ef5ce authored by jan.koester's avatar jan.koester
Browse files

upload to media modul editor added

parent c9bb9138
Loading
Loading
Loading
Loading
+137 −12
Changes for data/template/default/editor.html: 137 added lines, 12 removed lines.
Original line number Diff line number Diff line
@@ -2845,12 +2845,25 @@
            const nav = document.getElementById('media-browser-nav');
            if (nav) nav.innerHTML = '';

            if (!albums.length) {
                content.innerHTML = '<p style="color:#6b7280;">No albums found. Create albums in Settings &rarr; Media.</p>';
                return;
            }
            let html = '';

            // Create Album form
            html += `<div style="margin-bottom:12px; padding:10px; background:#f0f9ff; border:1px solid #bae6fd; border-radius:8px;">
                <div style="font-weight:600; color:#0369a1; margin-bottom:6px; font-size:0.9rem;">Create New Album</div>
                <div style="display:flex; gap:6px; align-items:center;">
                    <select id="media-browser-new-album-store" style="padding:6px 8px; border:1px solid #d1d5db; border-radius:6px; font-size:0.85rem;">
                        <option value="">Store...</option>
                    </select>
                    <input type="text" id="media-browser-new-album-name" placeholder="Album name" style="flex:1; padding:6px 8px; border:1px solid #d1d5db; border-radius:6px; font-size:0.85rem;">
                    <button type="button" onclick="createAlbumFromBrowser()" style="padding:6px 12px; background:#0284c7; color:#fff; border:none; border-radius:6px; cursor:pointer; font-size:0.85rem; white-space:nowrap;">Create</button>
                </div>
                <div id="media-browser-create-status" style="margin-top:4px; font-size:0.8rem;"></div>
            </div>`;

            let html = '<div style="display:flex; flex-direction:column; gap:4px;">';
            if (!albums.length) {
                html += '<p style="color:#6b7280;">No albums found.</p>';
            } else {
                html += '<div style="display:flex; flex-direction:column; gap:4px;">';
                for (const a of albums) {
                    html += `<button type="button" onclick="loadAlbumMedia('${escapeHtml(a.id)}', '${escapeHtml(a.name)}')" 
                        style="display:flex; justify-content:space-between; align-items:center; padding:10px 14px; background:#e5e7eb; border:1px solid #d1d5db; border-radius:8px; cursor:pointer; transition:background 0.15s;">
@@ -2859,10 +2872,66 @@
                    </button>`;
                }
                html += '</div>';
            }
            content.innerHTML = html;

            // Populate store dropdown
            loadStoresForBrowser();
        }

        async function loadStoresForBrowser() {
            try {
                const resp = await sendApiRequest([{ command: 'media_list_stores' }]);
                const result = resp.find(r => r.stores);
                if (result && result.stores) {
                    const sel = document.getElementById('media-browser-new-album-store');
                    if (sel) {
                        sel.innerHTML = '<option value="">Store...</option>';
                        for (const s of result.stores) {
                            sel.innerHTML += `<option value="${escapeHtml(s)}">${escapeHtml(s)}</option>`;
                        }
                    }
                }
            } catch (e) {
                console.error('Failed to load stores:', e);
            }
        }

        async function createAlbumFromBrowser() {
            const storeEl = document.getElementById('media-browser-new-album-store');
            const nameEl = document.getElementById('media-browser-new-album-name');
            const statusEl = document.getElementById('media-browser-create-status');
            if (!storeEl || !nameEl) return;
            const storeName = storeEl.value.trim();
            const albumName = nameEl.value.trim();
            if (!storeName || !albumName) {
                if (statusEl) { statusEl.textContent = 'Please select a store and enter a name.'; statusEl.style.color = '#dc2626'; }
                return;
            }
            if (statusEl) { statusEl.textContent = 'Creating...'; statusEl.style.color = '#6b7280'; }
            try {
                const resp = await sendApiRequest([{ command: 'media_create_album', store_name: storeName, album_name: albumName }]);
                const result = resp.find(r => r.album || (r.status === 'error'));
                if (result && result.status === 'error') {
                    if (statusEl) { statusEl.textContent = result.message || 'Error'; statusEl.style.color = '#dc2626'; }
                    return;
                }
                // Reload album list
                nameEl.value = '';
                const resp2 = await sendApiRequest([{ command: 'media_list_albums' }]);
                const result2 = resp2.find(r => r.albums);
                if (result2 && result2.albums) renderAlbumList(result2.albums);
            } catch (e) {
                if (statusEl) { statusEl.textContent = e.message; statusEl.style.color = '#dc2626'; }
            }
        }

        let _currentBrowserAlbumId = null;
        let _currentBrowserAlbumName = null;

        async function loadAlbumMedia(albumId, albumName) {
            _currentBrowserAlbumId = albumId;
            _currentBrowserAlbumName = albumName;
            const content = document.getElementById('media-browser-content');
            const nav = document.getElementById('media-browser-nav');

@@ -2882,21 +2951,29 @@
                    content.innerHTML = '<p style="color:#dc2626;">Failed to load media.</p>';
                    return;
                }
                renderMediaGrid(result.media);
                renderMediaGrid(result.media, albumId);
            } catch (e) {
                content.innerHTML = `<p style="color:#dc2626;">Error: ${e.message}</p>`;
            }
        }

        function renderMediaGrid(mediaList) {
        function renderMediaGrid(mediaList, albumId) {
            const content = document.getElementById('media-browser-content');

            if (!mediaList.length) {
                content.innerHTML = '<p style="color:#6b7280;">Album is empty.</p>';
                return;
            }
            // Upload form
            let html = `<div style="margin-bottom:12px; padding:10px; background:#f0fdf4; border:1px solid #bbf7d0; border-radius:8px;">
                <div style="font-weight:600; color:#15803d; margin-bottom:6px; font-size:0.9rem;">Upload Media</div>
                <div style="display:flex; gap:6px; align-items:center;">
                    <input type="file" id="media-browser-upload-file" multiple style="flex:1; font-size:0.85rem;">
                    <button type="button" onclick="uploadMediaFromBrowser()" style="padding:6px 12px; background:#16a34a; color:#fff; border:none; border-radius:6px; cursor:pointer; font-size:0.85rem; white-space:nowrap;">Upload</button>
                </div>
                <div id="media-browser-upload-status" style="margin-top:4px; font-size:0.8rem;"></div>
            </div>`;

            let html = '<div style="display:grid; grid-template-columns:repeat(auto-fill, minmax(120px, 1fr)); gap:8px;">';
            if (!mediaList.length) {
                html += '<p style="color:#6b7280;">Album is empty.</p>';
            } else {
                html += '<div style="display:grid; grid-template-columns:repeat(auto-fill, minmax(120px, 1fr)); gap:8px;">';
                for (const m of mediaList) {
                    const thumbUrl = m.url;
                    const ext = m.filename.includes('.') ? m.filename.split('.').pop() : 'webp';
@@ -2917,9 +2994,57 @@
                    }
                }
                html += '</div>';
            }
            content.innerHTML = html;
        }

        async function uploadMediaFromBrowser() {
            const fileInput = document.getElementById('media-browser-upload-file');
            const statusEl = document.getElementById('media-browser-upload-status');
            if (!fileInput || !fileInput.files.length) {
                if (statusEl) { statusEl.textContent = 'Please select a file.'; statusEl.style.color = '#dc2626'; }
                return;
            }
            if (!_currentBrowserAlbumId) {
                if (statusEl) { statusEl.textContent = 'No album selected.'; statusEl.style.color = '#dc2626'; }
                return;
            }

            const files = Array.from(fileInput.files);
            if (statusEl) { statusEl.textContent = `Uploading ${files.length} file(s)...`; statusEl.style.color = '#6b7280'; }

            try {
                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    if (statusEl) statusEl.textContent = `Uploading ${i + 1}/${files.length}: ${file.name}...`;
                    const b64 = await fileToBase64(file);
                    await sendApiRequest([{
                        command: 'media_upload',
                        album_id: _currentBrowserAlbumId,
                        filename: file.name,
                        data: b64
                    }]);
                }
                if (statusEl) { statusEl.textContent = 'Upload complete!'; statusEl.style.color = '#16a34a'; }
                // Reload media list
                loadAlbumMedia(_currentBrowserAlbumId, _currentBrowserAlbumName);
            } catch (e) {
                if (statusEl) { statusEl.textContent = e.message; statusEl.style.color = '#dc2626'; }
            }
        }

        function fileToBase64(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = () => {
                    // result is "data:mime;base64,XXXXXX"
                    resolve(reader.result);
                };
                reader.onerror = () => reject(new Error('Failed to read file'));
                reader.readAsDataURL(file);
            });
        }

        // --- Aspect ratio auto-calculation for Image ---
        let _imageNaturalWidth = 0;
        let _imageNaturalHeight = 0;
+94 −0
Changes for plugins/media/media.cpp: 94 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -1064,6 +1064,100 @@ namespace blogi {
                }
                json_object_object_add(response, "status", json_object_new_string("success"));
                json_object_object_add(response, "stores", jarr);
            } else if(strcmp(command, "media_create_album") == 0){
                json_object *jsn = nullptr, *jan = nullptr;
                if(!json_object_object_get_ex(request, "store_name", &jsn) ||
                   !json_object_object_get_ex(request, "album_name", &jan)){
                    json_object_object_add(response, "status", json_object_new_string("error"));
                    json_object_object_add(response, "message", json_object_new_string("store_name and album_name required"));
                    return;
                }
                const char *storeName = json_object_get_string(jsn);
                const char *albumName = json_object_get_string(jan);
                if(!storeName || !albumName || storeName[0]=='\0' || albumName[0]=='\0'){
                    json_object_object_add(response, "status", json_object_new_string("error"));
                    json_object_object_add(response, "message", json_object_new_string("store_name and album_name must not be empty"));
                    return;
                }
                try {
                    _ensureMdbReady(tid, token);
                    std::string storeId = _getStoreId(tid, storeName);
                    auto album = _mdb[tid]->create_album(storeId, albumName);
                    json_object_object_add(response, "status", json_object_new_string("success"));
                    json_object *jal = json_object_new_object();
                    json_object_object_add(jal, "id", json_object_new_string(album.id.c_str()));
                    json_object_object_add(jal, "name", json_object_new_string(album.name.c_str()));
                    json_object_object_add(jal, "store", json_object_new_string(storeName));
                    json_object_object_add(jal, "media_count", json_object_new_int(album.media_count));
                    json_object_object_add(response, "album", jal);
                } catch(std::exception &e) {
                    json_object_object_add(response, "status", json_object_new_string("error"));
                    json_object_object_add(response, "message", json_object_new_string(e.what()));
                } catch(...) {
                    json_object_object_add(response, "status", json_object_new_string("error"));
                    json_object_object_add(response, "message", json_object_new_string("Unknown error"));
                }
            } else if(strcmp(command, "media_upload") == 0){
                json_object *jaid = nullptr, *jfn = nullptr, *jdata = nullptr;
                if(!json_object_object_get_ex(request, "album_id", &jaid) ||
                   !json_object_object_get_ex(request, "filename", &jfn) ||
                   !json_object_object_get_ex(request, "data", &jdata)){
                    json_object_object_add(response, "status", json_object_new_string("error"));
                    json_object_object_add(response, "message", json_object_new_string("album_id, filename, and data required"));
                    return;
                }
                const char *albumId = json_object_get_string(jaid);
                const char *filename = json_object_get_string(jfn);
                const char *b64data = json_object_get_string(jdata);
                if(!albumId || !filename || !b64data){
                    json_object_object_add(response, "status", json_object_new_string("error"));
                    json_object_object_add(response, "message", json_object_new_string("invalid parameters"));
                    return;
                }
                try {
                    // Base64 decode
                    static const std::string chars =
                        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
                    int T[256];
                    std::fill(T, T + 256, -1);
                    for(int i = 0; i < 64; i++) T[(unsigned char)chars[i]] = i;
                    std::vector<std::uint8_t> payload;
                    std::string encoded(b64data);
                    // Strip data URI prefix if present
                    size_t commaPos = encoded.find(',');
                    if(commaPos != std::string::npos && commaPos < 100)
                        encoded = encoded.substr(commaPos + 1);
                    payload.reserve(encoded.size() * 3 / 4);
                    int val = 0, valb = -8;
                    for(unsigned char c : encoded){
                        if(T[c] == -1) continue;
                        val = (val << 6) + T[c];
                        valb += 6;
                        if(valb >= 0){ payload.push_back(static_cast<std::uint8_t>((val >> valb) & 0xFF)); valb -= 8; }
                    }

                    _ensureMdbReady(tid, token);
                    auto mi = _mdb[tid]->upload(albumId, filename, payload);
                    std::string ext = "webp";
                    size_t dp = mi.filename.rfind('.');
                    if(dp != std::string::npos) ext = mi.filename.substr(dp + 1);
                    std::string url = Args->config->buildurl("media/getimage/") + mi.id + "." + ext;

                    json_object_object_add(response, "status", json_object_new_string("success"));
                    json_object *jm = json_object_new_object();
                    json_object_object_add(jm, "id", json_object_new_string(mi.id.c_str()));
                    json_object_object_add(jm, "filename", json_object_new_string(mi.filename.c_str()));
                    json_object_object_add(jm, "kind", json_object_new_string(mi.kind.c_str()));
                    json_object_object_add(jm, "content_type", json_object_new_string(mi.content_type.c_str()));
                    json_object_object_add(jm, "url", json_object_new_string(url.c_str()));
                    json_object_object_add(response, "media", jm);
                } catch(std::exception &e) {
                    json_object_object_add(response, "status", json_object_new_string("error"));
                    json_object_object_add(response, "message", json_object_new_string(e.what()));
                } catch(...) {
                    json_object_object_add(response, "status", json_object_new_string("error"));
                    json_object_object_add(response, "message", json_object_new_string("Unknown error"));
                }
            }
        }