| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020 |
- package agi
- import (
- "bytes"
- "compress/gzip"
- "crypto/sha1"
- "encoding/base64"
- "encoding/hex"
- "errors"
- "fmt"
- "io"
- "net/url"
- "os"
- "path/filepath"
- "strings"
- "github.com/robertkrimen/otto"
- "imuslab.com/arozos/mod/agi/static"
- "imuslab.com/arozos/mod/info/logger"
- "imuslab.com/arozos/mod/office"
- "imuslab.com/arozos/mod/office/doc"
- "imuslab.com/arozos/mod/office/docx"
- "imuslab.com/arozos/mod/office/model"
- "imuslab.com/arozos/mod/office/odf"
- "imuslab.com/arozos/mod/office/pdf"
- "imuslab.com/arozos/mod/office/ppt"
- "imuslab.com/arozos/mod/office/pptx"
- "imuslab.com/arozos/mod/office/xls"
- "imuslab.com/arozos/mod/office/xlsx"
- "imuslab.com/arozos/mod/user"
- )
- /*
- AGI Office Document Library
- Converters between the ArozOS Office suite webapps (Docs / Sheets /
- Slides, src/web/Office/) and common office file formats. The heavy
- lifting lives in mod/office; this file only wires it into the AGI VM
- with per-user permission and virtual-path handling.
- The suite's own documents ARE .docx / .xlsx / .pptx (mod/office
- native.go): the OOXML plus the editor's envelope embedded in the package.
- office.saveDocument(envelopeJson, destVpath) => write the envelope as the Office
- file its extension names; media?file=
- links are read server side
- office.loadDocument(srcVpath, workdirBase) => envelope JSON string: the embedded
- copy when current, else an import;
- media extracted to a per-document
- working dir and linked. Also opens
- the legacy .doc / .xls / .ppt files
- (converted to OOXML first)
- office.readPayload(vpath) => the text of an uploaded payload file,
- gunzipped when it is gzip
- office.touchWorkdir(vpath, ...) => keep an editor window's working
- folders under tmp:/.appdata/Office/
- from the nightly tmp sweep
- office.releaseWorkdir(vpath [, olderThanSec]) => delete such a folder (or only
- its entries older than that)
- Format conversions:
- office.pptxToPresentation(srcVpath) => JSON body string (Slides schema)
- office.presentationToPptx(jsonStr, destVpath) => true on success; when the deck
- has video/audio, their files are
- written to <dest>.zip and that
- vpath (string) is returned instead
- office.xlsxToWorkbook(srcVpath) => JSON body string (Sheets schema)
- office.workbookToXlsx(jsonStr, destVpath) => true on success
- office.docxToDocument(srcVpath) => JSON body string (Docs schema)
- office.documentToDocx(jsonStr, destVpath) => true on success
- office.packToFile(envelopeJson, destVpath) => write a session snapshot container
- office.unpackToWorkdir(srcVpath, workdirBase) => envelope JSON of a snapshot (assets
- extracted to a per-document working dir,
- referenced by media?file= links)
- office.odtToDocument(srcVpath) => JSON body string (Docs schema)
- office.documentToOdt(jsonStr, destVpath) => true on success
- office.odsToWorkbook(srcVpath) => JSON body string (Sheets schema)
- office.workbookToOds(jsonStr, destVpath) => true on success
- office.odpToPresentation(srcVpath) => JSON body string (Slides schema)
- office.presentationToOdp(jsonStr, destVpath) => true on success
- office.documentToPdf(jsonStr, destVpath) => true on success (real-text PDF)
- office.workbookPrintToPdf(printJson, destVpath) => true on success (client print model)
- Legacy binary formats (Office 97-2003), import only - mod/office/doc,
- xls and ppt convert them into OOXML:
- office.docToDocument(srcVpath) => JSON body string (Docs schema)
- office.xlsToWorkbook(srcVpath) => JSON body string (Sheets schema)
- office.pptToPresentation(srcVpath) => JSON body string (Slides schema)
- office.convertLegacy(srcVpath, destVpath) => true on success: writes the .doc /
- .xls / .ppt as the .docx / .xlsx /
- .pptx destVpath names
- Author: tobychui
- */
- func (g *Gateway) OfficeLibRegister() {
- err := g.RegisterLib("office", g.injectOfficeLibFunctions)
- if err != nil {
- logger.PrintAndLog("Agi", fmt.Sprint(err), nil)
- os.Exit(1)
- }
- }
- // officeVpathReader resolves the media?file= links a document carries,
- // through the same read permission the user has everywhere else
- func officeVpathReader(u *user.User) func(string) ([]byte, error) {
- return func(vp string) ([]byte, error) {
- if !u.CanRead(vp) {
- return nil, errors.New("read access denied")
- }
- fsh, rp, err := static.VirtualPathToRealPath(vp, u)
- if err != nil {
- return nil, err
- }
- f, err := fsh.FileSystemAbstraction.ReadStream(rp)
- if err != nil {
- return nil, err
- }
- defer f.Close()
- return io.ReadAll(f)
- }
- }
- // officeMaxPayload caps an uploaded (and possibly gzipped) request payload
- const officeMaxPayload = 512 << 20
- func (g *Gateway) injectOfficeLibFunctions(payload *static.AgiLibInjectionPayload) {
- vm := payload.VM
- u := payload.User
- scriptFsh := payload.ScriptFsh
- readVpath := officeVpathReader(u)
- g.injectOfficeWorkdirFunctions(vm, u, scriptFsh)
- // writeOut writes bytes to a checked, already rewritten vpath
- writeOut := func(destVpath string, data []byte) error {
- destFsh, destRpath, err := static.VirtualPathToRealPath(destVpath, u)
- if err != nil {
- return err
- }
- if err := destFsh.FileSystemAbstraction.WriteStream(destRpath, bytes.NewReader(data), 0755); err != nil {
- return err
- }
- u.SetOwnerOfFile(destFsh, destVpath)
- return nil
- }
- // readIn reads a checked, already rewritten vpath
- readIn := func(srcVpath string) ([]byte, error) {
- srcFsh, srcRpath, err := static.VirtualPathToRealPath(srcVpath, u)
- if err != nil {
- return nil, err
- }
- f, err := srcFsh.FileSystemAbstraction.ReadStream(srcRpath)
- if err != nil {
- return nil, err
- }
- defer f.Close()
- return io.ReadAll(f)
- }
- // saveDocument(envelopeJson, destVpath) => true: the suite's own save.
- // The extension decides the format (.docx / .xlsx / .pptx) and must
- // match the envelope's app.
- vm.Set("_office_saveDocument", func(call otto.FunctionCall) otto.Value {
- envelope, err := call.Argument(0).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- destVpath, err := call.Argument(1).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- destVpath = static.RelativeVpathRewrite(scriptFsh, destVpath, vm, u)
- if !u.CanWrite(destVpath) {
- panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+destVpath))
- }
- app := office.AppForExt(filepath.Ext(destVpath))
- if app == "" {
- panic(vm.MakeCustomError("UnsupportedFormat", "Office documents are saved as .docx, .xlsx or .pptx: "+destVpath))
- }
- // a picture whose working copy has gone (the nightly tmp sweep, an
- // editor left open for days) would be left out of the file without
- // a word: refuse the save instead, so nothing is lost
- var expired []string
- read := func(vp string) ([]byte, error) {
- b, err := readVpath(vp)
- if err != nil && isOfficeWorkdir(vp) {
- expired = append(expired, vp)
- }
- return b, err
- }
- data, err := office.BuildNativeFile(app, envelope, read)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- if len(expired) > 0 {
- panic(vm.MakeCustomError("MediaExpired", fmt.Sprintf(
- "%d picture(s) of this document are no longer on the server (their temporary copy expired) - reopen the document before saving, or they would be lost",
- len(expired))))
- }
- if err := writeOut(destVpath, data); err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- return otto.TrueValue()
- })
- // loadDocument(srcVpath, workdirBase) => envelope JSON string. Media is
- // written into <workdirBase>/<doc-hash>/ and linked by media?file=, so
- // the browser streams pictures instead of receiving them as base64.
- vm.Set("_office_loadDocument", func(call otto.FunctionCall) otto.Value {
- srcVpath, err := call.Argument(0).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- workdirBase, err := call.Argument(1).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- srcVpath = static.RelativeVpathRewrite(scriptFsh, srcVpath, vm, u)
- workdirBase = strings.TrimSuffix(static.RelativeVpathRewrite(scriptFsh, workdirBase, vm, u), "/")
- if !u.CanRead(srcVpath) {
- panic(vm.MakeCustomError("PermissionDenied", "Read access denied: "+srcVpath))
- }
- if !u.CanWrite(workdirBase) {
- panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+workdirBase))
- }
- // the app's own format, or its Office 97-2003 one (converted on read)
- app := office.AppForFile(filepath.Ext(srcVpath))
- if app == "" {
- panic(vm.MakeCustomError("UnsupportedFormat", "not a Word, Excel or PowerPoint file: "+srcVpath))
- }
- data, err := readIn(srcVpath)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- h := sha1.Sum([]byte(srcVpath))
- docDirV := workdirBase + "/" + hex.EncodeToString(h[:])[:12]
- wdFsh, docDirR, err := static.VirtualPathToRealPath(docDirV, u)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- sink := func(name string, content []byte) (string, error) {
- name = filepath.Base(name)
- link := "../../media?file=" + url.QueryEscape(docDirV+"/"+name)
- target := filepath.Join(docDirR, name)
- // asset names are content hashes, so a file already in the cache
- // under this name is this picture: reopening a document does not
- // write its media out again
- fsa := wdFsh.FileSystemAbstraction
- if fsa.FileExists(target) && fsa.GetFileSize(target) == int64(len(content)) {
- return link, nil
- }
- if err := fsa.MkdirAll(docDirR, 0755); err != nil {
- return "", err
- }
- if err := fsa.WriteStream(target, bytes.NewReader(content), 0755); err != nil {
- return "", err
- }
- return link, nil
- }
- envelope, err := office.ReadNativeFile(app, data, sink)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- reply, _ := vm.ToValue(envelope)
- return reply
- })
- // readPayload(vpath) => string: a request payload the front end uploaded
- // as a file instead of posting it (OfficeApp.agirunLarge), gzipped when
- // the browser could compress it. The caller deletes the file.
- vm.Set("_office_readPayload", func(call otto.FunctionCall) otto.Value {
- vp, err := call.Argument(0).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- vp = static.RelativeVpathRewrite(scriptFsh, vp, vm, u)
- if !u.CanRead(vp) {
- panic(vm.MakeCustomError("PermissionDenied", "Read access denied: "+vp))
- }
- data, err := readIn(vp)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- if len(data) >= 2 && data[0] == 0x1f && data[1] == 0x8b {
- zr, err := gzip.NewReader(bytes.NewReader(data))
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- plain, err := io.ReadAll(io.LimitReader(zr, officeMaxPayload+1))
- zr.Close()
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- if len(plain) > officeMaxPayload {
- g.RaiseError(errors.New("payload is too large"))
- return otto.NullValue()
- }
- data = plain
- }
- reply, _ := vm.ToValue(string(data))
- return reply
- })
- // pptxToPresentation(srcVpath) => JSON string of the Slides body schema
- vm.Set("_office_pptxToPresentation", func(call otto.FunctionCall) otto.Value {
- srcVpath, err := call.Argument(0).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- srcVpath = static.RelativeVpathRewrite(scriptFsh, srcVpath, vm, u)
- if !u.CanRead(srcVpath) {
- panic(vm.MakeCustomError("PermissionDenied", "Read access denied: "+srcVpath))
- }
- srcFsh, srcRpath, err := static.VirtualPathToRealPath(srcVpath, u)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- // read the whole pptx into memory (zip needs random access)
- f, err := srcFsh.FileSystemAbstraction.ReadStream(srcRpath)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- data, err := io.ReadAll(f)
- f.Close()
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- pres, err := pptx.Parse(data)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- jsonBody, err := model.PresentationToJSON(pres)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- reply, _ := vm.ToValue(jsonBody)
- return reply
- })
- // presentationToPptx(jsonStr, destVpath) => build a pptx and write it
- vm.Set("_office_presentationToPptx", func(call otto.FunctionCall) otto.Value {
- jsonStr, err := call.Argument(0).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- destVpath, err := call.Argument(1).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- destVpath = static.RelativeVpathRewrite(scriptFsh, destVpath, vm, u)
- if !u.CanWrite(destVpath) {
- panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+destVpath))
- }
- pres, err := model.ParsePresentationJSON(jsonStr)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- // media?file= links (pictures, video, audio) are read here, so their
- // bytes never ride the JSON payload
- data, mediaZip, err := pptx.BuildMedia(pres, readVpath)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- destFsh, destRpath, err := static.VirtualPathToRealPath(destVpath, u)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- err = destFsh.FileSystemAbstraction.WriteStream(destRpath, bytes.NewReader(data), 0755)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- u.SetOwnerOfFile(destFsh, destVpath)
- // video/audio files ship in a sidecar zip next to the pptx
- // (media is not embedded - playback support is unreliable);
- // returns the zip vpath (string) instead of true when written
- if len(mediaZip) > 0 {
- zipVpath := strings.TrimSuffix(destVpath, filepath.Ext(destVpath)) + ".zip"
- if !u.CanWrite(zipVpath) {
- panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+zipVpath))
- }
- zipFsh, zipRpath, err := static.VirtualPathToRealPath(zipVpath, u)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- err = zipFsh.FileSystemAbstraction.WriteStream(zipRpath, bytes.NewReader(mediaZip), 0755)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- u.SetOwnerOfFile(zipFsh, zipVpath)
- reply, _ := vm.ToValue(zipVpath)
- return reply
- }
- reply, _ := vm.ToValue(true)
- return reply
- })
- // xlsxToWorkbook(srcVpath) => JSON string of the Sheets body schema
- vm.Set("_office_xlsxToWorkbook", func(call otto.FunctionCall) otto.Value {
- srcVpath, err := call.Argument(0).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- srcVpath = static.RelativeVpathRewrite(scriptFsh, srcVpath, vm, u)
- if !u.CanRead(srcVpath) {
- panic(vm.MakeCustomError("PermissionDenied", "Read access denied: "+srcVpath))
- }
- srcFsh, srcRpath, err := static.VirtualPathToRealPath(srcVpath, u)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- f, err := srcFsh.FileSystemAbstraction.ReadStream(srcRpath)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- data, err := io.ReadAll(f)
- f.Close()
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- wb, err := xlsx.Parse(data)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- jsonBody, err := model.WorkbookToJSON(wb)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- reply, _ := vm.ToValue(jsonBody)
- return reply
- })
- // workbookToXlsx(jsonStr, destVpath) => build an xlsx and write it
- vm.Set("_office_workbookToXlsx", func(call otto.FunctionCall) otto.Value {
- jsonStr, err := call.Argument(0).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- destVpath, err := call.Argument(1).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- destVpath = static.RelativeVpathRewrite(scriptFsh, destVpath, vm, u)
- if !u.CanWrite(destVpath) {
- panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+destVpath))
- }
- wb, err := model.ParseWorkbookJSON(jsonStr)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- data, err := xlsx.Build(wb)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- destFsh, destRpath, err := static.VirtualPathToRealPath(destVpath, u)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- err = destFsh.FileSystemAbstraction.WriteStream(destRpath, bytes.NewReader(data), 0755)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- u.SetOwnerOfFile(destFsh, destVpath)
- reply, _ := vm.ToValue(true)
- return reply
- })
- // docxToDocument(srcVpath) => JSON string of the Docs body schema
- vm.Set("_office_docxToDocument", func(call otto.FunctionCall) otto.Value {
- srcVpath, err := call.Argument(0).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- srcVpath = static.RelativeVpathRewrite(scriptFsh, srcVpath, vm, u)
- if !u.CanRead(srcVpath) {
- panic(vm.MakeCustomError("PermissionDenied", "Read access denied: "+srcVpath))
- }
- srcFsh, srcRpath, err := static.VirtualPathToRealPath(srcVpath, u)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- f, err := srcFsh.FileSystemAbstraction.ReadStream(srcRpath)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- data, err := io.ReadAll(f)
- f.Close()
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- doc, err := docx.Parse(data)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- jsonBody, err := model.DocumentToJSON(doc)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- reply, _ := vm.ToValue(jsonBody)
- return reply
- })
- // documentToDocx(jsonStr, destVpath) => build a docx and write it
- vm.Set("_office_documentToDocx", func(call otto.FunctionCall) otto.Value {
- jsonStr, err := call.Argument(0).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- destVpath, err := call.Argument(1).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- destVpath = static.RelativeVpathRewrite(scriptFsh, destVpath, vm, u)
- if !u.CanWrite(destVpath) {
- panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+destVpath))
- }
- doc, err := model.ParseDocumentJSON(jsonStr)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- data, err := docx.BuildMedia(doc, readVpath)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- destFsh, destRpath, err := static.VirtualPathToRealPath(destVpath, u)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- err = destFsh.FileSystemAbstraction.WriteStream(destRpath, bytes.NewReader(data), 0755)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- u.SetOwnerOfFile(destFsh, destVpath)
- reply, _ := vm.ToValue(true)
- return reply
- })
- // packToFile(envelopeJson, destVpath) => write the native zip container
- // (media data URLs and legacy media?file= links become embedded assets)
- vm.Set("_office_packToFile", func(call otto.FunctionCall) otto.Value {
- envelope, err := call.Argument(0).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- destVpath, err := call.Argument(1).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- destVpath = static.RelativeVpathRewrite(scriptFsh, destVpath, vm, u)
- if !u.CanWrite(destVpath) {
- panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+destVpath))
- }
- // media?file= links inside the document become embedded assets
- data, err := office.PackEnvelope(envelope, readVpath)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- destFsh, destRpath, err := static.VirtualPathToRealPath(destVpath, u)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- err = destFsh.FileSystemAbstraction.WriteStream(destRpath, bytes.NewReader(data), 0755)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- u.SetOwnerOfFile(destFsh, destVpath)
- reply, _ := vm.ToValue(true)
- return reply
- })
- // unpackToWorkdir(srcVpath, workdirBase) => envelope JSON string with
- // assets extracted into <workdirBase>/<doc-hash>/ and referenced by
- // media?file= links, so large media never rides inside the JSON
- vm.Set("_office_unpackToWorkdir", func(call otto.FunctionCall) otto.Value {
- srcVpath, err := call.Argument(0).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- workdirBase, err := call.Argument(1).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- srcVpath = static.RelativeVpathRewrite(scriptFsh, srcVpath, vm, u)
- workdirBase = strings.TrimSuffix(static.RelativeVpathRewrite(scriptFsh, workdirBase, vm, u), "/")
- if !u.CanRead(srcVpath) {
- panic(vm.MakeCustomError("PermissionDenied", "Read access denied: "+srcVpath))
- }
- if !u.CanWrite(workdirBase) {
- panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+workdirBase))
- }
- srcFsh, srcRpath, err := static.VirtualPathToRealPath(srcVpath, u)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- f, err := srcFsh.FileSystemAbstraction.ReadStream(srcRpath)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- data, err := io.ReadAll(f)
- f.Close()
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- // per-document cache dir keyed by the source path
- h := sha1.Sum([]byte(srcVpath))
- docDirV := workdirBase + "/" + hex.EncodeToString(h[:])[:12]
- wdFsh, docDirR, err := static.VirtualPathToRealPath(docDirV, u)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- envelope, err := office.UnpackEnvelopeToLinks(data,
- func(name string, content []byte) error {
- if err := wdFsh.FileSystemAbstraction.MkdirAll(docDirR, 0755); err != nil {
- return err
- }
- return wdFsh.FileSystemAbstraction.WriteStream(
- filepath.Join(docDirR, filepath.Base(name)), bytes.NewReader(content), 0755)
- },
- func(name string) string {
- return "../../media?file=" + url.QueryEscape(docDirV+"/"+name)
- })
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- reply, _ := vm.ToValue(envelope)
- return reply
- })
- /* ---------- OpenDocument (odt / ods / odp) ----------
- Same permission / vpath handling as the OOXML converters, factored
- through two generic closures since all six calls share their shape. */
- // importFn(srcVpath) => JSON body string
- registerOdfImport := func(fnName string, convert func([]byte) (string, error)) {
- vm.Set(fnName, func(call otto.FunctionCall) otto.Value {
- srcVpath, err := call.Argument(0).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- srcVpath = static.RelativeVpathRewrite(scriptFsh, srcVpath, vm, u)
- if !u.CanRead(srcVpath) {
- panic(vm.MakeCustomError("PermissionDenied", "Read access denied: "+srcVpath))
- }
- srcFsh, srcRpath, err := static.VirtualPathToRealPath(srcVpath, u)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- f, err := srcFsh.FileSystemAbstraction.ReadStream(srcRpath)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- data, err := io.ReadAll(f)
- f.Close()
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- jsonBody, err := convert(data)
- if err != nil {
- g.RaiseError(err)
- return otto.NullValue()
- }
- reply, _ := vm.ToValue(jsonBody)
- return reply
- })
- }
- // exportFn(jsonStr, destVpath) => true on success
- registerOdfExport := func(fnName string, convert func(string) ([]byte, error)) {
- vm.Set(fnName, func(call otto.FunctionCall) otto.Value {
- jsonStr, err := call.Argument(0).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- destVpath, err := call.Argument(1).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- destVpath = static.RelativeVpathRewrite(scriptFsh, destVpath, vm, u)
- if !u.CanWrite(destVpath) {
- panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+destVpath))
- }
- data, err := convert(jsonStr)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- destFsh, destRpath, err := static.VirtualPathToRealPath(destVpath, u)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- err = destFsh.FileSystemAbstraction.WriteStream(destRpath, bytes.NewReader(data), 0755)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- u.SetOwnerOfFile(destFsh, destVpath)
- reply, _ := vm.ToValue(true)
- return reply
- })
- }
- /* ---------- Office 97-2003 imports (mod/office/doc, xls, ppt) ----------
- Each converts the legacy file into OOXML and reads that, so the body
- is what the matching .docx / .xlsx / .pptx import would give. */
- registerOdfImport("_office_docToDocument", func(data []byte) (string, error) {
- d, err := doc.Parse(data)
- if err != nil {
- return "", err
- }
- return model.DocumentToJSON(d)
- })
- registerOdfImport("_office_xlsToWorkbook", func(data []byte) (string, error) {
- wb, err := xls.Parse(data)
- if err != nil {
- return "", err
- }
- return model.WorkbookToJSON(wb)
- })
- registerOdfImport("_office_pptToPresentation", func(data []byte) (string, error) {
- p, err := ppt.Parse(data)
- if err != nil {
- return "", err
- }
- return model.PresentationToJSON(p)
- })
- // convertLegacy(srcVpath, destVpath) => true: the legacy file written as
- // the OOXML file of its kind; destVpath must carry that extension
- vm.Set("_office_convertLegacy", func(call otto.FunctionCall) otto.Value {
- srcVpath, err := call.Argument(0).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- destVpath, err := call.Argument(1).ToString()
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- srcVpath = static.RelativeVpathRewrite(scriptFsh, srcVpath, vm, u)
- destVpath = static.RelativeVpathRewrite(scriptFsh, destVpath, vm, u)
- if !u.CanRead(srcVpath) {
- panic(vm.MakeCustomError("PermissionDenied", "Read access denied: "+srcVpath))
- }
- if !u.CanWrite(destVpath) {
- panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+destVpath))
- }
- data, err := readIn(srcVpath)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- app, converted, err := office.ConvertLegacy(data)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- if office.AppForExt(filepath.Ext(destVpath)) != app {
- panic(vm.MakeCustomError("UnsupportedFormat", "this file converts to "+office.ExtForApp(app)+": "+destVpath))
- }
- destFsh, destRpath, err := static.VirtualPathToRealPath(destVpath, u)
- if err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- if err := destFsh.FileSystemAbstraction.WriteStream(destRpath, bytes.NewReader(converted), 0755); err != nil {
- g.RaiseError(err)
- return otto.FalseValue()
- }
- u.SetOwnerOfFile(destFsh, destVpath)
- return otto.TrueValue()
- })
- registerOdfImport("_office_odtToDocument", func(data []byte) (string, error) {
- doc, err := odf.ParseOdt(data)
- if err != nil {
- return "", err
- }
- return model.DocumentToJSON(doc)
- })
- registerOdfExport("_office_documentToOdt", func(jsonStr string) ([]byte, error) {
- // the ODF writers take inline pictures only: read the links here
- jsonStr, err := office.InlineMediaLinks(jsonStr, readVpath)
- if err != nil {
- return nil, err
- }
- doc, err := model.ParseDocumentJSON(jsonStr)
- if err != nil {
- return nil, err
- }
- return odf.BuildOdt(doc)
- })
- registerOdfImport("_office_odsToWorkbook", func(data []byte) (string, error) {
- wb, err := odf.ParseOds(data)
- if err != nil {
- return "", err
- }
- return model.WorkbookToJSON(wb)
- })
- registerOdfExport("_office_workbookToOds", func(jsonStr string) ([]byte, error) {
- wb, err := model.ParseWorkbookJSON(jsonStr)
- if err != nil {
- return nil, err
- }
- return odf.BuildOds(wb)
- })
- registerOdfImport("_office_odpToPresentation", func(data []byte) (string, error) {
- pres, err := odf.ParseOdp(data)
- if err != nil {
- return "", err
- }
- return model.PresentationToJSON(pres)
- })
- registerOdfExport("_office_presentationToOdp", func(jsonStr string) ([]byte, error) {
- jsonStr, err := office.InlineMediaLinks(jsonStr, readVpath)
- if err != nil {
- return nil, err
- }
- pres, err := model.ParsePresentationJSON(jsonStr)
- if err != nil {
- return nil, err
- }
- return odf.BuildOdp(pres)
- })
- /* ---------- PDF export (real text, mod/office/pdf) ----------
- Same (jsonStr, destVpath) shape as the ODF exporters. The Sheets
- variant takes the client-computed print model (formatted display
- strings + styles) instead of the raw workbook, since formula
- evaluation lives in the web client. */
- registerOdfExport("_office_documentToPdf", func(jsonStr string) ([]byte, error) {
- jsonStr, err := office.InlineMediaLinks(jsonStr, readVpath)
- if err != nil {
- return nil, err
- }
- doc, err := model.ParseDocumentJSON(jsonStr)
- if err != nil {
- return nil, err
- }
- return pdf.BuildDoc(doc)
- })
- registerOdfExport("_office_workbookPrintToPdf", func(jsonStr string) ([]byte, error) {
- m, err := pdf.ParseSheetPrintJSON(jsonStr)
- if err != nil {
- return nil, err
- }
- return pdf.BuildSheet(m)
- })
- /* ---------- write a file the web client produced ----------
- Slides builds its PDF in the browser (only the browser knows how the
- text actually laid out), so it needs a way to put those bytes on the
- file system. Same (payload, destVpath) shape and the same write
- permission check as every exporter above. */
- registerOdfExport("_office_writeBinaryFile", func(b64 string) ([]byte, error) {
- data, err := base64.StdEncoding.DecodeString(strings.TrimSpace(b64))
- if err != nil {
- return nil, errors.New("payload is not valid base64: " + err.Error())
- }
- return data, nil
- })
- vm.Run(`
- var office = {};
- office.pptxToPresentation = _office_pptxToPresentation; // pptx file -> Slides body JSON string
- office.presentationToPptx = _office_presentationToPptx; // Slides body JSON string -> pptx file (+ media sidecar zip; returns its vpath)
- office.xlsxToWorkbook = _office_xlsxToWorkbook; // xlsx file -> Sheets body JSON string
- office.workbookToXlsx = _office_workbookToXlsx; // Sheets body JSON string -> xlsx file
- office.docxToDocument = _office_docxToDocument; // docx file -> Docs body JSON string
- office.documentToDocx = _office_documentToDocx; // Docs body JSON string -> docx file
- office.saveDocument = _office_saveDocument; // envelope JSON -> .docx / .xlsx / .pptx (the suite's own save)
- office.loadDocument = _office_loadDocument; // .docx / .xlsx / .pptx (or .doc / .xls / .ppt) -> envelope JSON, media extracted to a workdir
- office.readPayload = _office_readPayload; // uploaded payload file -> string (gunzipped)
- office.touchWorkdir = _office_touchWorkdir; // keep an editor window's tmp:/.appdata/Office folders fresh
- office.releaseWorkdir = _office_releaseWorkdir; // delete an editor window's working folder (or its stale entries)
- office.packToFile = _office_packToFile; // envelope JSON -> session snapshot container file
- office.unpackToWorkdir = _office_unpackToWorkdir; // session snapshot -> envelope JSON, assets extracted to a workdir
- office.odtToDocument = _office_odtToDocument; // odt file -> Docs body JSON string
- office.documentToOdt = _office_documentToOdt; // Docs body JSON string -> odt file
- office.odsToWorkbook = _office_odsToWorkbook; // ods file -> Sheets body JSON string
- office.workbookToOds = _office_workbookToOds; // Sheets body JSON string -> ods file
- office.odpToPresentation = _office_odpToPresentation; // odp file -> Slides body JSON string
- office.presentationToOdp = _office_presentationToOdp; // Slides body JSON string -> odp file
- office.docToDocument = _office_docToDocument; // Word 97-2003 .doc file -> Docs body JSON string
- office.xlsToWorkbook = _office_xlsToWorkbook; // Excel 97-2003 .xls file -> Sheets body JSON string
- office.pptToPresentation = _office_pptToPresentation; // PowerPoint 97-2003 .ppt file -> Slides body JSON string
- office.convertLegacy = _office_convertLegacy; // .doc / .xls / .ppt file -> .docx / .xlsx / .pptx file
- office.documentToPdf = _office_documentToPdf; // Docs body JSON string -> pdf file (real text)
- office.workbookPrintToPdf = _office_workbookPrintToPdf; // Sheets print-model JSON -> pdf file (real text)
- office.writeBinaryFile = _office_writeBinaryFile; // base64 string -> binary file (client-produced exports)
- `)
- }
- /*
- Example Usages
- // Import: convert a .pptx into the Slides editor body schema
- if (requirelib("office")) {
- var bodyJson = office.pptxToPresentation("user:/Desktop/deck.pptx");
- sendJSONResp('{"body":' + bodyJson + '}');
- }
- // Export: build a .pptx from a serialized Slides body
- if (requirelib("office")) {
- var ok = office.presentationToPptx(bodyJsonString, "user:/Desktop/out.pptx");
- if (ok) { sendResp("OK"); }
- }
- // The suite's own save / open (envelope in, envelope out)
- if (requirelib("office")) {
- office.saveDocument(envelopeJson, "user:/Documents/report.docx");
- var env = office.loadDocument("user:/Documents/report.docx", "user:/.appdata/Office/cache");
- }
- */
|