OnlyOffice + FastAPI microservizio¶
Questo documento raccoglie i passaggi 1→4 richiesti nella sequenza: (1) ambiente, (2) avvio, (3) template SafeOps/iframe, (4) verifica callback/Minio.
1. Preparare le variabili d’ambiente¶
- Copia
onlyoffice_service/.env.exampleinonlyoffice_service/.enved imposta i valori reali: ONLYOFFICE_URL=http://onlyofficeONLYOFFICE_SECRET(deve essere uguale a quello configurato in OnlyOffice e nell’URL del documento).MINIO_*secondo la macchina che ospita MinIO; per un MinIO già attivo sul nodo10.50.0.200basta settare:MINIO_ENDPOINT=10.50.0.200:9000 MINIO_ACCESS_KEY=minioadmin MINIO_SECRET_KEY=Zaq12wsx-234 MINIO_BUCKET=safeops MINIO_SECURE=trueJWT_EXP_SECONDSpuò restare300.- Il microservizio legge prima
.envall’interno dionlyoffice_service/, quindi eventuali.envesterni vengono comunque considerati come fallback. - Se il portale gira in HTTPS, non usare
localhostper il browser. Pubblica OnlyOffice via reverse proxy e imposta nel.envprincipale:Il template nginx di riferimento èONLYOFFICE_SERVICE_URL=http://127.0.0.1:8000 ONLYOFFICE_DOCSERVER_URL=https://besant.nxt-sense.eu/onlyoffice-docs ONLYOFFICE_CALLBACK_URL=https://besant.nxt-sense.eu/onlyoffice-service/v1/editor/callbackdeploy/nginx/safeops.conf.examplee include già i path/onlyoffice-docs/e/onlyoffice-service/.
2. Avviare i container (FastAPI, OnlyOffice, Minio)¶
docker-compose -f docker-compose.onlyoffice.yml up --build- I servizi esposti siano raggiungibili in locale su:
http://localhost:9000for MinIO (console:9001).http://localhost:9082for OnlyOffice Document Server.-
http://localhost:8000/v1/editor/openfor il microservizio FastAPI. -
Se servono i bucket, crea
safeopsconmc:
docker exec safeops-minio mc alias set local http://localhost:9000 minioadmin minioadminpassword
docker exec safeops-minio mc mb --ignore-existing local/safeops
Se MinIO è già collegato a SafeOps, i file migrati riusciranno a essere recuperati durante open.
3. Template SafeOps / iframe¶
3.1. Chiamata open¶
Vai a open con un payload JSON (l’esempio usa fetch sul microservizio FastAPI):
const openPayload = {
document_id: 123,
file_key: "documenti/verbali/verbale.docx",
file_name: "Verbale.docx",
file_type: "docx",
bucket: "safeops",
callback_url: "http://localhost:8000/v1/editor/callback",
permissions: 4
};
const response = await fetch("http://localhost:8000/v1/editor/open", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(openPayload)
});
const editorPayload = await response.json();
3.2. Embed DocEditor¶
Nel template SafeOps puoi inserire:
<script src="http://localhost:9082/web-apps/apps/api/documents/api.js"></script>
<div id="onlyoffice-editor" style="height:100vh;width:100%"></div>
<script>
async function openOnlyOffice() {
const resp = await fetch("/api/proxy-to-onlyoffice-open", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ document_id: 123, file_key: "...", ... })
});
const { document, editorConfig, onlyofficeUrl, jwt } = await resp.json();
new window.DocEditor("onlyoffice-editor", {
width: "100%",
height: "100%",
document,
documentType: document.fileType,
token: jwt,
editorConfig: {
...editorConfig,
callbackUrl: editorConfig.callbackUrl
},
key: document.key,
});
}
openOnlyOffice();
</script>
Nota: window.DocEditor è fornito dal file api.js del Document Server. L’oggetto document contiene il key serializzato (bucket+object) che you can store to call /v1/editor/callback if needed.
4. Verifica/callback/Minio¶
- When OnlyOffice calls
callbackUrl, the FastAPI microservice checksstatusand writes back to MinIO. Puoi controllare i log disafeops-onlyoffice-serviceper confermare che ilPUTsu MinIO (bucket+key) vada a buon fine. - Per controllare manualmente che MinIO contenga l’oggetto aggiornato:
docker exec safeops-minio mc cp local/safeops/documenti/verbali/verbale.docx /tmp/verbale.docx
docker exec safeops-minio ls local/safeops/documenti/verbali/
-
Se l’URL di callback deve essere pubblico, esponi
http://localhost:8000/v1/editor/callbackvia reverse proxy (nginx, Traefik) oppure usa un tunnel (es.ngrok). -
Per testare il flusso end-to-end:
- Apri l’editor nel frontend e modifica un documento.
- Attendi che OnlyOffice chiami
/v1/editor/callbackcon status2o6. - Controlla in MinIO che il file aggiornato sia presente tramite
mc.
Questo schema può essere esteso a più servizi SafeOps/gestionali: basta chiamare la stessa API /v1/editor/open e usare il medesimo callback per ricevere il file ritornato da OnlyOffice.
Helper backend per SafeOps¶
Se preferisci evitare chiamate dirette a /v1/editor/open dal browser, puoi utilizzare l’helper Python in app/helpers/onlyoffice.py.
- Importa
open_documente passa i metadati:
from app.helpers.onlyoffice import open_document
payload = open_document(
document_id=123,
file_key="documenti/verbali/verbale.docx",
file_name="Verbale.docx",
file_type="docx",
callback_url="http://localhost:8000/v1/editor/callback",
)
open_documentritorna il JSON completo (document,editorConfig,jwt). Puoi restituirlo da un endpoint protetto del tuo backend e lasciare al browser il solo compito di istanziareDocEditor.- L’helper legge
ONLYOFFICE_SERVICE_URLdalla variabile d’ambiente (impostata in.env) e sollevaOnlyOfficeHelperErrorin caso di fallimento.
View pronta all’uso¶
Se vuoi bypassare del tutto l’iframe manuale, puoi chiamare la nuova view protetta che fa tutto lo stesso lavoro:
GET /onlyoffice/editor?document_id=123&file_key=documenti/verbali/verbale.docx
La view:
- chiama
open_documentpassandodocument_id,file_key,file_name(derivata dal path se manca) ecallback_url(leggeONLYOFFICE_CALLBACK_URL). - monta
DocEditorusando il templateonlyoffice/editor.htmle importaapi.jsdal Document Server (URL soggetto aONLYOFFICE_DOCSERVER_URL). - richiede che l’utente sia autenticato (
login_required), quindi può essere inserita in una scheda sicura di SafeOps.
Puoi includere questa view nel menu SafeOps registrando una voce personalizzata o incapsularla in un’iframe all’interno di un portale esistente.
Creazione guidata documento¶
La view /onlyoffice/create permette di creare un stub DOCX, salvarlo in MinIO e aprirlo subito nell’editor. Basta:
- Accedere alla voce “Crea documento” nel menu
Documenti(richiede login). - Compilare titolo e formato (al momento supportiamo solo DOCX).
- Submit genera il file tramite
upload_bytes(payload docx vuoto), registra il metadata sustored_filese reindirizza l’utente su/onlyoffice/editor.
Questo è utile per partire da un documento nuovo senza dover caricare template manualmente.
Sincronizzazione menu per tenant¶
Se alcuni tenant (es. besant, safecondo) usano policy menu custom e non vedono ancora le voci, esegui lo script tools/onlyoffice_menu_sync.py:
python tools/onlyoffice_menu_sync.py --tenants besant safecondo
In alternativa (dopo aver installato dipendenze e caricato l’app) puoi usare il comando Flask:
FLASK_APP=app flask sync_onlyoffice_menu --tenants besant safecondo
Il tool inserisce o abilita in tabella menu_policy le record OnlyOffice Editor / Crea documento per ciascun tenant indicato. Puoi aggiungere altri tenant passandoli con --tenants.