agi.office.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  1. package agi
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "crypto/sha1"
  6. "encoding/base64"
  7. "encoding/hex"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "net/url"
  12. "os"
  13. "path/filepath"
  14. "strings"
  15. "github.com/robertkrimen/otto"
  16. "imuslab.com/arozos/mod/agi/static"
  17. "imuslab.com/arozos/mod/info/logger"
  18. "imuslab.com/arozos/mod/office"
  19. "imuslab.com/arozos/mod/office/doc"
  20. "imuslab.com/arozos/mod/office/docx"
  21. "imuslab.com/arozos/mod/office/model"
  22. "imuslab.com/arozos/mod/office/odf"
  23. "imuslab.com/arozos/mod/office/pdf"
  24. "imuslab.com/arozos/mod/office/ppt"
  25. "imuslab.com/arozos/mod/office/pptx"
  26. "imuslab.com/arozos/mod/office/xls"
  27. "imuslab.com/arozos/mod/office/xlsx"
  28. "imuslab.com/arozos/mod/user"
  29. )
  30. /*
  31. AGI Office Document Library
  32. Converters between the ArozOS Office suite webapps (Docs / Sheets /
  33. Slides, src/web/Office/) and common office file formats. The heavy
  34. lifting lives in mod/office; this file only wires it into the AGI VM
  35. with per-user permission and virtual-path handling.
  36. The suite's own documents ARE .docx / .xlsx / .pptx (mod/office
  37. native.go): the OOXML plus the editor's envelope embedded in the package.
  38. office.saveDocument(envelopeJson, destVpath) => write the envelope as the Office
  39. file its extension names; media?file=
  40. links are read server side
  41. office.loadDocument(srcVpath, workdirBase) => envelope JSON string: the embedded
  42. copy when current, else an import;
  43. media extracted to a per-document
  44. working dir and linked. Also opens
  45. the legacy .doc / .xls / .ppt files
  46. (converted to OOXML first)
  47. office.readPayload(vpath) => the text of an uploaded payload file,
  48. gunzipped when it is gzip
  49. office.touchWorkdir(vpath, ...) => keep an editor window's working
  50. folders under tmp:/.appdata/Office/
  51. from the nightly tmp sweep
  52. office.releaseWorkdir(vpath [, olderThanSec]) => delete such a folder (or only
  53. its entries older than that)
  54. Format conversions:
  55. office.pptxToPresentation(srcVpath) => JSON body string (Slides schema)
  56. office.presentationToPptx(jsonStr, destVpath) => true on success; when the deck
  57. has video/audio, their files are
  58. written to <dest>.zip and that
  59. vpath (string) is returned instead
  60. office.xlsxToWorkbook(srcVpath) => JSON body string (Sheets schema)
  61. office.workbookToXlsx(jsonStr, destVpath) => true on success
  62. office.docxToDocument(srcVpath) => JSON body string (Docs schema)
  63. office.documentToDocx(jsonStr, destVpath) => true on success
  64. office.packToFile(envelopeJson, destVpath) => write a session snapshot container
  65. office.unpackToWorkdir(srcVpath, workdirBase) => envelope JSON of a snapshot (assets
  66. extracted to a per-document working dir,
  67. referenced by media?file= links)
  68. office.odtToDocument(srcVpath) => JSON body string (Docs schema)
  69. office.documentToOdt(jsonStr, destVpath) => true on success
  70. office.odsToWorkbook(srcVpath) => JSON body string (Sheets schema)
  71. office.workbookToOds(jsonStr, destVpath) => true on success
  72. office.odpToPresentation(srcVpath) => JSON body string (Slides schema)
  73. office.presentationToOdp(jsonStr, destVpath) => true on success
  74. office.documentToPdf(jsonStr, destVpath) => true on success (real-text PDF)
  75. office.workbookPrintToPdf(printJson, destVpath) => true on success (client print model)
  76. Legacy binary formats (Office 97-2003), import only - mod/office/doc,
  77. xls and ppt convert them into OOXML:
  78. office.docToDocument(srcVpath) => JSON body string (Docs schema)
  79. office.xlsToWorkbook(srcVpath) => JSON body string (Sheets schema)
  80. office.pptToPresentation(srcVpath) => JSON body string (Slides schema)
  81. office.convertLegacy(srcVpath, destVpath) => true on success: writes the .doc /
  82. .xls / .ppt as the .docx / .xlsx /
  83. .pptx destVpath names
  84. Author: tobychui
  85. */
  86. func (g *Gateway) OfficeLibRegister() {
  87. err := g.RegisterLib("office", g.injectOfficeLibFunctions)
  88. if err != nil {
  89. logger.PrintAndLog("Agi", fmt.Sprint(err), nil)
  90. os.Exit(1)
  91. }
  92. }
  93. // officeVpathReader resolves the media?file= links a document carries,
  94. // through the same read permission the user has everywhere else
  95. func officeVpathReader(u *user.User) func(string) ([]byte, error) {
  96. return func(vp string) ([]byte, error) {
  97. if !u.CanRead(vp) {
  98. return nil, errors.New("read access denied")
  99. }
  100. fsh, rp, err := static.VirtualPathToRealPath(vp, u)
  101. if err != nil {
  102. return nil, err
  103. }
  104. f, err := fsh.FileSystemAbstraction.ReadStream(rp)
  105. if err != nil {
  106. return nil, err
  107. }
  108. defer f.Close()
  109. return io.ReadAll(f)
  110. }
  111. }
  112. // officeMaxPayload caps an uploaded (and possibly gzipped) request payload
  113. const officeMaxPayload = 512 << 20
  114. func (g *Gateway) injectOfficeLibFunctions(payload *static.AgiLibInjectionPayload) {
  115. vm := payload.VM
  116. u := payload.User
  117. scriptFsh := payload.ScriptFsh
  118. readVpath := officeVpathReader(u)
  119. g.injectOfficeWorkdirFunctions(vm, u, scriptFsh)
  120. // writeOut writes bytes to a checked, already rewritten vpath
  121. writeOut := func(destVpath string, data []byte) error {
  122. destFsh, destRpath, err := static.VirtualPathToRealPath(destVpath, u)
  123. if err != nil {
  124. return err
  125. }
  126. if err := destFsh.FileSystemAbstraction.WriteStream(destRpath, bytes.NewReader(data), 0755); err != nil {
  127. return err
  128. }
  129. u.SetOwnerOfFile(destFsh, destVpath)
  130. return nil
  131. }
  132. // readIn reads a checked, already rewritten vpath
  133. readIn := func(srcVpath string) ([]byte, error) {
  134. srcFsh, srcRpath, err := static.VirtualPathToRealPath(srcVpath, u)
  135. if err != nil {
  136. return nil, err
  137. }
  138. f, err := srcFsh.FileSystemAbstraction.ReadStream(srcRpath)
  139. if err != nil {
  140. return nil, err
  141. }
  142. defer f.Close()
  143. return io.ReadAll(f)
  144. }
  145. // saveDocument(envelopeJson, destVpath) => true: the suite's own save.
  146. // The extension decides the format (.docx / .xlsx / .pptx) and must
  147. // match the envelope's app.
  148. vm.Set("_office_saveDocument", func(call otto.FunctionCall) otto.Value {
  149. envelope, err := call.Argument(0).ToString()
  150. if err != nil {
  151. g.RaiseError(err)
  152. return otto.FalseValue()
  153. }
  154. destVpath, err := call.Argument(1).ToString()
  155. if err != nil {
  156. g.RaiseError(err)
  157. return otto.FalseValue()
  158. }
  159. destVpath = static.RelativeVpathRewrite(scriptFsh, destVpath, vm, u)
  160. if !u.CanWrite(destVpath) {
  161. panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+destVpath))
  162. }
  163. app := office.AppForExt(filepath.Ext(destVpath))
  164. if app == "" {
  165. panic(vm.MakeCustomError("UnsupportedFormat", "Office documents are saved as .docx, .xlsx or .pptx: "+destVpath))
  166. }
  167. // a picture whose working copy has gone (the nightly tmp sweep, an
  168. // editor left open for days) would be left out of the file without
  169. // a word: refuse the save instead, so nothing is lost
  170. var expired []string
  171. read := func(vp string) ([]byte, error) {
  172. b, err := readVpath(vp)
  173. if err != nil && isOfficeWorkdir(vp) {
  174. expired = append(expired, vp)
  175. }
  176. return b, err
  177. }
  178. data, err := office.BuildNativeFile(app, envelope, read)
  179. if err != nil {
  180. g.RaiseError(err)
  181. return otto.FalseValue()
  182. }
  183. if len(expired) > 0 {
  184. panic(vm.MakeCustomError("MediaExpired", fmt.Sprintf(
  185. "%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",
  186. len(expired))))
  187. }
  188. if err := writeOut(destVpath, data); err != nil {
  189. g.RaiseError(err)
  190. return otto.FalseValue()
  191. }
  192. return otto.TrueValue()
  193. })
  194. // loadDocument(srcVpath, workdirBase) => envelope JSON string. Media is
  195. // written into <workdirBase>/<doc-hash>/ and linked by media?file=, so
  196. // the browser streams pictures instead of receiving them as base64.
  197. vm.Set("_office_loadDocument", func(call otto.FunctionCall) otto.Value {
  198. srcVpath, err := call.Argument(0).ToString()
  199. if err != nil {
  200. g.RaiseError(err)
  201. return otto.NullValue()
  202. }
  203. workdirBase, err := call.Argument(1).ToString()
  204. if err != nil {
  205. g.RaiseError(err)
  206. return otto.NullValue()
  207. }
  208. srcVpath = static.RelativeVpathRewrite(scriptFsh, srcVpath, vm, u)
  209. workdirBase = strings.TrimSuffix(static.RelativeVpathRewrite(scriptFsh, workdirBase, vm, u), "/")
  210. if !u.CanRead(srcVpath) {
  211. panic(vm.MakeCustomError("PermissionDenied", "Read access denied: "+srcVpath))
  212. }
  213. if !u.CanWrite(workdirBase) {
  214. panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+workdirBase))
  215. }
  216. // the app's own format, or its Office 97-2003 one (converted on read)
  217. app := office.AppForFile(filepath.Ext(srcVpath))
  218. if app == "" {
  219. panic(vm.MakeCustomError("UnsupportedFormat", "not a Word, Excel or PowerPoint file: "+srcVpath))
  220. }
  221. data, err := readIn(srcVpath)
  222. if err != nil {
  223. g.RaiseError(err)
  224. return otto.NullValue()
  225. }
  226. h := sha1.Sum([]byte(srcVpath))
  227. docDirV := workdirBase + "/" + hex.EncodeToString(h[:])[:12]
  228. wdFsh, docDirR, err := static.VirtualPathToRealPath(docDirV, u)
  229. if err != nil {
  230. g.RaiseError(err)
  231. return otto.NullValue()
  232. }
  233. sink := func(name string, content []byte) (string, error) {
  234. name = filepath.Base(name)
  235. link := "../../media?file=" + url.QueryEscape(docDirV+"/"+name)
  236. target := filepath.Join(docDirR, name)
  237. // asset names are content hashes, so a file already in the cache
  238. // under this name is this picture: reopening a document does not
  239. // write its media out again
  240. fsa := wdFsh.FileSystemAbstraction
  241. if fsa.FileExists(target) && fsa.GetFileSize(target) == int64(len(content)) {
  242. return link, nil
  243. }
  244. if err := fsa.MkdirAll(docDirR, 0755); err != nil {
  245. return "", err
  246. }
  247. if err := fsa.WriteStream(target, bytes.NewReader(content), 0755); err != nil {
  248. return "", err
  249. }
  250. return link, nil
  251. }
  252. envelope, err := office.ReadNativeFile(app, data, sink)
  253. if err != nil {
  254. g.RaiseError(err)
  255. return otto.NullValue()
  256. }
  257. reply, _ := vm.ToValue(envelope)
  258. return reply
  259. })
  260. // readPayload(vpath) => string: a request payload the front end uploaded
  261. // as a file instead of posting it (OfficeApp.agirunLarge), gzipped when
  262. // the browser could compress it. The caller deletes the file.
  263. vm.Set("_office_readPayload", func(call otto.FunctionCall) otto.Value {
  264. vp, err := call.Argument(0).ToString()
  265. if err != nil {
  266. g.RaiseError(err)
  267. return otto.NullValue()
  268. }
  269. vp = static.RelativeVpathRewrite(scriptFsh, vp, vm, u)
  270. if !u.CanRead(vp) {
  271. panic(vm.MakeCustomError("PermissionDenied", "Read access denied: "+vp))
  272. }
  273. data, err := readIn(vp)
  274. if err != nil {
  275. g.RaiseError(err)
  276. return otto.NullValue()
  277. }
  278. if len(data) >= 2 && data[0] == 0x1f && data[1] == 0x8b {
  279. zr, err := gzip.NewReader(bytes.NewReader(data))
  280. if err != nil {
  281. g.RaiseError(err)
  282. return otto.NullValue()
  283. }
  284. plain, err := io.ReadAll(io.LimitReader(zr, officeMaxPayload+1))
  285. zr.Close()
  286. if err != nil {
  287. g.RaiseError(err)
  288. return otto.NullValue()
  289. }
  290. if len(plain) > officeMaxPayload {
  291. g.RaiseError(errors.New("payload is too large"))
  292. return otto.NullValue()
  293. }
  294. data = plain
  295. }
  296. reply, _ := vm.ToValue(string(data))
  297. return reply
  298. })
  299. // pptxToPresentation(srcVpath) => JSON string of the Slides body schema
  300. vm.Set("_office_pptxToPresentation", func(call otto.FunctionCall) otto.Value {
  301. srcVpath, err := call.Argument(0).ToString()
  302. if err != nil {
  303. g.RaiseError(err)
  304. return otto.NullValue()
  305. }
  306. srcVpath = static.RelativeVpathRewrite(scriptFsh, srcVpath, vm, u)
  307. if !u.CanRead(srcVpath) {
  308. panic(vm.MakeCustomError("PermissionDenied", "Read access denied: "+srcVpath))
  309. }
  310. srcFsh, srcRpath, err := static.VirtualPathToRealPath(srcVpath, u)
  311. if err != nil {
  312. g.RaiseError(err)
  313. return otto.NullValue()
  314. }
  315. // read the whole pptx into memory (zip needs random access)
  316. f, err := srcFsh.FileSystemAbstraction.ReadStream(srcRpath)
  317. if err != nil {
  318. g.RaiseError(err)
  319. return otto.NullValue()
  320. }
  321. data, err := io.ReadAll(f)
  322. f.Close()
  323. if err != nil {
  324. g.RaiseError(err)
  325. return otto.NullValue()
  326. }
  327. pres, err := pptx.Parse(data)
  328. if err != nil {
  329. g.RaiseError(err)
  330. return otto.NullValue()
  331. }
  332. jsonBody, err := model.PresentationToJSON(pres)
  333. if err != nil {
  334. g.RaiseError(err)
  335. return otto.NullValue()
  336. }
  337. reply, _ := vm.ToValue(jsonBody)
  338. return reply
  339. })
  340. // presentationToPptx(jsonStr, destVpath) => build a pptx and write it
  341. vm.Set("_office_presentationToPptx", func(call otto.FunctionCall) otto.Value {
  342. jsonStr, err := call.Argument(0).ToString()
  343. if err != nil {
  344. g.RaiseError(err)
  345. return otto.FalseValue()
  346. }
  347. destVpath, err := call.Argument(1).ToString()
  348. if err != nil {
  349. g.RaiseError(err)
  350. return otto.FalseValue()
  351. }
  352. destVpath = static.RelativeVpathRewrite(scriptFsh, destVpath, vm, u)
  353. if !u.CanWrite(destVpath) {
  354. panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+destVpath))
  355. }
  356. pres, err := model.ParsePresentationJSON(jsonStr)
  357. if err != nil {
  358. g.RaiseError(err)
  359. return otto.FalseValue()
  360. }
  361. // media?file= links (pictures, video, audio) are read here, so their
  362. // bytes never ride the JSON payload
  363. data, mediaZip, err := pptx.BuildMedia(pres, readVpath)
  364. if err != nil {
  365. g.RaiseError(err)
  366. return otto.FalseValue()
  367. }
  368. destFsh, destRpath, err := static.VirtualPathToRealPath(destVpath, u)
  369. if err != nil {
  370. g.RaiseError(err)
  371. return otto.FalseValue()
  372. }
  373. err = destFsh.FileSystemAbstraction.WriteStream(destRpath, bytes.NewReader(data), 0755)
  374. if err != nil {
  375. g.RaiseError(err)
  376. return otto.FalseValue()
  377. }
  378. u.SetOwnerOfFile(destFsh, destVpath)
  379. // video/audio files ship in a sidecar zip next to the pptx
  380. // (media is not embedded - playback support is unreliable);
  381. // returns the zip vpath (string) instead of true when written
  382. if len(mediaZip) > 0 {
  383. zipVpath := strings.TrimSuffix(destVpath, filepath.Ext(destVpath)) + ".zip"
  384. if !u.CanWrite(zipVpath) {
  385. panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+zipVpath))
  386. }
  387. zipFsh, zipRpath, err := static.VirtualPathToRealPath(zipVpath, u)
  388. if err != nil {
  389. g.RaiseError(err)
  390. return otto.FalseValue()
  391. }
  392. err = zipFsh.FileSystemAbstraction.WriteStream(zipRpath, bytes.NewReader(mediaZip), 0755)
  393. if err != nil {
  394. g.RaiseError(err)
  395. return otto.FalseValue()
  396. }
  397. u.SetOwnerOfFile(zipFsh, zipVpath)
  398. reply, _ := vm.ToValue(zipVpath)
  399. return reply
  400. }
  401. reply, _ := vm.ToValue(true)
  402. return reply
  403. })
  404. // xlsxToWorkbook(srcVpath) => JSON string of the Sheets body schema
  405. vm.Set("_office_xlsxToWorkbook", func(call otto.FunctionCall) otto.Value {
  406. srcVpath, err := call.Argument(0).ToString()
  407. if err != nil {
  408. g.RaiseError(err)
  409. return otto.NullValue()
  410. }
  411. srcVpath = static.RelativeVpathRewrite(scriptFsh, srcVpath, vm, u)
  412. if !u.CanRead(srcVpath) {
  413. panic(vm.MakeCustomError("PermissionDenied", "Read access denied: "+srcVpath))
  414. }
  415. srcFsh, srcRpath, err := static.VirtualPathToRealPath(srcVpath, u)
  416. if err != nil {
  417. g.RaiseError(err)
  418. return otto.NullValue()
  419. }
  420. f, err := srcFsh.FileSystemAbstraction.ReadStream(srcRpath)
  421. if err != nil {
  422. g.RaiseError(err)
  423. return otto.NullValue()
  424. }
  425. data, err := io.ReadAll(f)
  426. f.Close()
  427. if err != nil {
  428. g.RaiseError(err)
  429. return otto.NullValue()
  430. }
  431. wb, err := xlsx.Parse(data)
  432. if err != nil {
  433. g.RaiseError(err)
  434. return otto.NullValue()
  435. }
  436. jsonBody, err := model.WorkbookToJSON(wb)
  437. if err != nil {
  438. g.RaiseError(err)
  439. return otto.NullValue()
  440. }
  441. reply, _ := vm.ToValue(jsonBody)
  442. return reply
  443. })
  444. // workbookToXlsx(jsonStr, destVpath) => build an xlsx and write it
  445. vm.Set("_office_workbookToXlsx", func(call otto.FunctionCall) otto.Value {
  446. jsonStr, err := call.Argument(0).ToString()
  447. if err != nil {
  448. g.RaiseError(err)
  449. return otto.FalseValue()
  450. }
  451. destVpath, err := call.Argument(1).ToString()
  452. if err != nil {
  453. g.RaiseError(err)
  454. return otto.FalseValue()
  455. }
  456. destVpath = static.RelativeVpathRewrite(scriptFsh, destVpath, vm, u)
  457. if !u.CanWrite(destVpath) {
  458. panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+destVpath))
  459. }
  460. wb, err := model.ParseWorkbookJSON(jsonStr)
  461. if err != nil {
  462. g.RaiseError(err)
  463. return otto.FalseValue()
  464. }
  465. data, err := xlsx.Build(wb)
  466. if err != nil {
  467. g.RaiseError(err)
  468. return otto.FalseValue()
  469. }
  470. destFsh, destRpath, err := static.VirtualPathToRealPath(destVpath, u)
  471. if err != nil {
  472. g.RaiseError(err)
  473. return otto.FalseValue()
  474. }
  475. err = destFsh.FileSystemAbstraction.WriteStream(destRpath, bytes.NewReader(data), 0755)
  476. if err != nil {
  477. g.RaiseError(err)
  478. return otto.FalseValue()
  479. }
  480. u.SetOwnerOfFile(destFsh, destVpath)
  481. reply, _ := vm.ToValue(true)
  482. return reply
  483. })
  484. // docxToDocument(srcVpath) => JSON string of the Docs body schema
  485. vm.Set("_office_docxToDocument", func(call otto.FunctionCall) otto.Value {
  486. srcVpath, err := call.Argument(0).ToString()
  487. if err != nil {
  488. g.RaiseError(err)
  489. return otto.NullValue()
  490. }
  491. srcVpath = static.RelativeVpathRewrite(scriptFsh, srcVpath, vm, u)
  492. if !u.CanRead(srcVpath) {
  493. panic(vm.MakeCustomError("PermissionDenied", "Read access denied: "+srcVpath))
  494. }
  495. srcFsh, srcRpath, err := static.VirtualPathToRealPath(srcVpath, u)
  496. if err != nil {
  497. g.RaiseError(err)
  498. return otto.NullValue()
  499. }
  500. f, err := srcFsh.FileSystemAbstraction.ReadStream(srcRpath)
  501. if err != nil {
  502. g.RaiseError(err)
  503. return otto.NullValue()
  504. }
  505. data, err := io.ReadAll(f)
  506. f.Close()
  507. if err != nil {
  508. g.RaiseError(err)
  509. return otto.NullValue()
  510. }
  511. doc, err := docx.Parse(data)
  512. if err != nil {
  513. g.RaiseError(err)
  514. return otto.NullValue()
  515. }
  516. jsonBody, err := model.DocumentToJSON(doc)
  517. if err != nil {
  518. g.RaiseError(err)
  519. return otto.NullValue()
  520. }
  521. reply, _ := vm.ToValue(jsonBody)
  522. return reply
  523. })
  524. // documentToDocx(jsonStr, destVpath) => build a docx and write it
  525. vm.Set("_office_documentToDocx", func(call otto.FunctionCall) otto.Value {
  526. jsonStr, err := call.Argument(0).ToString()
  527. if err != nil {
  528. g.RaiseError(err)
  529. return otto.FalseValue()
  530. }
  531. destVpath, err := call.Argument(1).ToString()
  532. if err != nil {
  533. g.RaiseError(err)
  534. return otto.FalseValue()
  535. }
  536. destVpath = static.RelativeVpathRewrite(scriptFsh, destVpath, vm, u)
  537. if !u.CanWrite(destVpath) {
  538. panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+destVpath))
  539. }
  540. doc, err := model.ParseDocumentJSON(jsonStr)
  541. if err != nil {
  542. g.RaiseError(err)
  543. return otto.FalseValue()
  544. }
  545. data, err := docx.BuildMedia(doc, readVpath)
  546. if err != nil {
  547. g.RaiseError(err)
  548. return otto.FalseValue()
  549. }
  550. destFsh, destRpath, err := static.VirtualPathToRealPath(destVpath, u)
  551. if err != nil {
  552. g.RaiseError(err)
  553. return otto.FalseValue()
  554. }
  555. err = destFsh.FileSystemAbstraction.WriteStream(destRpath, bytes.NewReader(data), 0755)
  556. if err != nil {
  557. g.RaiseError(err)
  558. return otto.FalseValue()
  559. }
  560. u.SetOwnerOfFile(destFsh, destVpath)
  561. reply, _ := vm.ToValue(true)
  562. return reply
  563. })
  564. // packToFile(envelopeJson, destVpath) => write the native zip container
  565. // (media data URLs and legacy media?file= links become embedded assets)
  566. vm.Set("_office_packToFile", func(call otto.FunctionCall) otto.Value {
  567. envelope, err := call.Argument(0).ToString()
  568. if err != nil {
  569. g.RaiseError(err)
  570. return otto.FalseValue()
  571. }
  572. destVpath, err := call.Argument(1).ToString()
  573. if err != nil {
  574. g.RaiseError(err)
  575. return otto.FalseValue()
  576. }
  577. destVpath = static.RelativeVpathRewrite(scriptFsh, destVpath, vm, u)
  578. if !u.CanWrite(destVpath) {
  579. panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+destVpath))
  580. }
  581. // media?file= links inside the document become embedded assets
  582. data, err := office.PackEnvelope(envelope, readVpath)
  583. if err != nil {
  584. g.RaiseError(err)
  585. return otto.FalseValue()
  586. }
  587. destFsh, destRpath, err := static.VirtualPathToRealPath(destVpath, u)
  588. if err != nil {
  589. g.RaiseError(err)
  590. return otto.FalseValue()
  591. }
  592. err = destFsh.FileSystemAbstraction.WriteStream(destRpath, bytes.NewReader(data), 0755)
  593. if err != nil {
  594. g.RaiseError(err)
  595. return otto.FalseValue()
  596. }
  597. u.SetOwnerOfFile(destFsh, destVpath)
  598. reply, _ := vm.ToValue(true)
  599. return reply
  600. })
  601. // unpackToWorkdir(srcVpath, workdirBase) => envelope JSON string with
  602. // assets extracted into <workdirBase>/<doc-hash>/ and referenced by
  603. // media?file= links, so large media never rides inside the JSON
  604. vm.Set("_office_unpackToWorkdir", func(call otto.FunctionCall) otto.Value {
  605. srcVpath, err := call.Argument(0).ToString()
  606. if err != nil {
  607. g.RaiseError(err)
  608. return otto.NullValue()
  609. }
  610. workdirBase, err := call.Argument(1).ToString()
  611. if err != nil {
  612. g.RaiseError(err)
  613. return otto.NullValue()
  614. }
  615. srcVpath = static.RelativeVpathRewrite(scriptFsh, srcVpath, vm, u)
  616. workdirBase = strings.TrimSuffix(static.RelativeVpathRewrite(scriptFsh, workdirBase, vm, u), "/")
  617. if !u.CanRead(srcVpath) {
  618. panic(vm.MakeCustomError("PermissionDenied", "Read access denied: "+srcVpath))
  619. }
  620. if !u.CanWrite(workdirBase) {
  621. panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+workdirBase))
  622. }
  623. srcFsh, srcRpath, err := static.VirtualPathToRealPath(srcVpath, u)
  624. if err != nil {
  625. g.RaiseError(err)
  626. return otto.NullValue()
  627. }
  628. f, err := srcFsh.FileSystemAbstraction.ReadStream(srcRpath)
  629. if err != nil {
  630. g.RaiseError(err)
  631. return otto.NullValue()
  632. }
  633. data, err := io.ReadAll(f)
  634. f.Close()
  635. if err != nil {
  636. g.RaiseError(err)
  637. return otto.NullValue()
  638. }
  639. // per-document cache dir keyed by the source path
  640. h := sha1.Sum([]byte(srcVpath))
  641. docDirV := workdirBase + "/" + hex.EncodeToString(h[:])[:12]
  642. wdFsh, docDirR, err := static.VirtualPathToRealPath(docDirV, u)
  643. if err != nil {
  644. g.RaiseError(err)
  645. return otto.NullValue()
  646. }
  647. envelope, err := office.UnpackEnvelopeToLinks(data,
  648. func(name string, content []byte) error {
  649. if err := wdFsh.FileSystemAbstraction.MkdirAll(docDirR, 0755); err != nil {
  650. return err
  651. }
  652. return wdFsh.FileSystemAbstraction.WriteStream(
  653. filepath.Join(docDirR, filepath.Base(name)), bytes.NewReader(content), 0755)
  654. },
  655. func(name string) string {
  656. return "../../media?file=" + url.QueryEscape(docDirV+"/"+name)
  657. })
  658. if err != nil {
  659. g.RaiseError(err)
  660. return otto.NullValue()
  661. }
  662. reply, _ := vm.ToValue(envelope)
  663. return reply
  664. })
  665. /* ---------- OpenDocument (odt / ods / odp) ----------
  666. Same permission / vpath handling as the OOXML converters, factored
  667. through two generic closures since all six calls share their shape. */
  668. // importFn(srcVpath) => JSON body string
  669. registerOdfImport := func(fnName string, convert func([]byte) (string, error)) {
  670. vm.Set(fnName, func(call otto.FunctionCall) otto.Value {
  671. srcVpath, err := call.Argument(0).ToString()
  672. if err != nil {
  673. g.RaiseError(err)
  674. return otto.NullValue()
  675. }
  676. srcVpath = static.RelativeVpathRewrite(scriptFsh, srcVpath, vm, u)
  677. if !u.CanRead(srcVpath) {
  678. panic(vm.MakeCustomError("PermissionDenied", "Read access denied: "+srcVpath))
  679. }
  680. srcFsh, srcRpath, err := static.VirtualPathToRealPath(srcVpath, u)
  681. if err != nil {
  682. g.RaiseError(err)
  683. return otto.NullValue()
  684. }
  685. f, err := srcFsh.FileSystemAbstraction.ReadStream(srcRpath)
  686. if err != nil {
  687. g.RaiseError(err)
  688. return otto.NullValue()
  689. }
  690. data, err := io.ReadAll(f)
  691. f.Close()
  692. if err != nil {
  693. g.RaiseError(err)
  694. return otto.NullValue()
  695. }
  696. jsonBody, err := convert(data)
  697. if err != nil {
  698. g.RaiseError(err)
  699. return otto.NullValue()
  700. }
  701. reply, _ := vm.ToValue(jsonBody)
  702. return reply
  703. })
  704. }
  705. // exportFn(jsonStr, destVpath) => true on success
  706. registerOdfExport := func(fnName string, convert func(string) ([]byte, error)) {
  707. vm.Set(fnName, func(call otto.FunctionCall) otto.Value {
  708. jsonStr, err := call.Argument(0).ToString()
  709. if err != nil {
  710. g.RaiseError(err)
  711. return otto.FalseValue()
  712. }
  713. destVpath, err := call.Argument(1).ToString()
  714. if err != nil {
  715. g.RaiseError(err)
  716. return otto.FalseValue()
  717. }
  718. destVpath = static.RelativeVpathRewrite(scriptFsh, destVpath, vm, u)
  719. if !u.CanWrite(destVpath) {
  720. panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+destVpath))
  721. }
  722. data, err := convert(jsonStr)
  723. if err != nil {
  724. g.RaiseError(err)
  725. return otto.FalseValue()
  726. }
  727. destFsh, destRpath, err := static.VirtualPathToRealPath(destVpath, u)
  728. if err != nil {
  729. g.RaiseError(err)
  730. return otto.FalseValue()
  731. }
  732. err = destFsh.FileSystemAbstraction.WriteStream(destRpath, bytes.NewReader(data), 0755)
  733. if err != nil {
  734. g.RaiseError(err)
  735. return otto.FalseValue()
  736. }
  737. u.SetOwnerOfFile(destFsh, destVpath)
  738. reply, _ := vm.ToValue(true)
  739. return reply
  740. })
  741. }
  742. /* ---------- Office 97-2003 imports (mod/office/doc, xls, ppt) ----------
  743. Each converts the legacy file into OOXML and reads that, so the body
  744. is what the matching .docx / .xlsx / .pptx import would give. */
  745. registerOdfImport("_office_docToDocument", func(data []byte) (string, error) {
  746. d, err := doc.Parse(data)
  747. if err != nil {
  748. return "", err
  749. }
  750. return model.DocumentToJSON(d)
  751. })
  752. registerOdfImport("_office_xlsToWorkbook", func(data []byte) (string, error) {
  753. wb, err := xls.Parse(data)
  754. if err != nil {
  755. return "", err
  756. }
  757. return model.WorkbookToJSON(wb)
  758. })
  759. registerOdfImport("_office_pptToPresentation", func(data []byte) (string, error) {
  760. p, err := ppt.Parse(data)
  761. if err != nil {
  762. return "", err
  763. }
  764. return model.PresentationToJSON(p)
  765. })
  766. // convertLegacy(srcVpath, destVpath) => true: the legacy file written as
  767. // the OOXML file of its kind; destVpath must carry that extension
  768. vm.Set("_office_convertLegacy", func(call otto.FunctionCall) otto.Value {
  769. srcVpath, err := call.Argument(0).ToString()
  770. if err != nil {
  771. g.RaiseError(err)
  772. return otto.FalseValue()
  773. }
  774. destVpath, err := call.Argument(1).ToString()
  775. if err != nil {
  776. g.RaiseError(err)
  777. return otto.FalseValue()
  778. }
  779. srcVpath = static.RelativeVpathRewrite(scriptFsh, srcVpath, vm, u)
  780. destVpath = static.RelativeVpathRewrite(scriptFsh, destVpath, vm, u)
  781. if !u.CanRead(srcVpath) {
  782. panic(vm.MakeCustomError("PermissionDenied", "Read access denied: "+srcVpath))
  783. }
  784. if !u.CanWrite(destVpath) {
  785. panic(vm.MakeCustomError("PermissionDenied", "Write access denied: "+destVpath))
  786. }
  787. data, err := readIn(srcVpath)
  788. if err != nil {
  789. g.RaiseError(err)
  790. return otto.FalseValue()
  791. }
  792. app, converted, err := office.ConvertLegacy(data)
  793. if err != nil {
  794. g.RaiseError(err)
  795. return otto.FalseValue()
  796. }
  797. if office.AppForExt(filepath.Ext(destVpath)) != app {
  798. panic(vm.MakeCustomError("UnsupportedFormat", "this file converts to "+office.ExtForApp(app)+": "+destVpath))
  799. }
  800. destFsh, destRpath, err := static.VirtualPathToRealPath(destVpath, u)
  801. if err != nil {
  802. g.RaiseError(err)
  803. return otto.FalseValue()
  804. }
  805. if err := destFsh.FileSystemAbstraction.WriteStream(destRpath, bytes.NewReader(converted), 0755); err != nil {
  806. g.RaiseError(err)
  807. return otto.FalseValue()
  808. }
  809. u.SetOwnerOfFile(destFsh, destVpath)
  810. return otto.TrueValue()
  811. })
  812. registerOdfImport("_office_odtToDocument", func(data []byte) (string, error) {
  813. doc, err := odf.ParseOdt(data)
  814. if err != nil {
  815. return "", err
  816. }
  817. return model.DocumentToJSON(doc)
  818. })
  819. registerOdfExport("_office_documentToOdt", func(jsonStr string) ([]byte, error) {
  820. // the ODF writers take inline pictures only: read the links here
  821. jsonStr, err := office.InlineMediaLinks(jsonStr, readVpath)
  822. if err != nil {
  823. return nil, err
  824. }
  825. doc, err := model.ParseDocumentJSON(jsonStr)
  826. if err != nil {
  827. return nil, err
  828. }
  829. return odf.BuildOdt(doc)
  830. })
  831. registerOdfImport("_office_odsToWorkbook", func(data []byte) (string, error) {
  832. wb, err := odf.ParseOds(data)
  833. if err != nil {
  834. return "", err
  835. }
  836. return model.WorkbookToJSON(wb)
  837. })
  838. registerOdfExport("_office_workbookToOds", func(jsonStr string) ([]byte, error) {
  839. wb, err := model.ParseWorkbookJSON(jsonStr)
  840. if err != nil {
  841. return nil, err
  842. }
  843. return odf.BuildOds(wb)
  844. })
  845. registerOdfImport("_office_odpToPresentation", func(data []byte) (string, error) {
  846. pres, err := odf.ParseOdp(data)
  847. if err != nil {
  848. return "", err
  849. }
  850. return model.PresentationToJSON(pres)
  851. })
  852. registerOdfExport("_office_presentationToOdp", func(jsonStr string) ([]byte, error) {
  853. jsonStr, err := office.InlineMediaLinks(jsonStr, readVpath)
  854. if err != nil {
  855. return nil, err
  856. }
  857. pres, err := model.ParsePresentationJSON(jsonStr)
  858. if err != nil {
  859. return nil, err
  860. }
  861. return odf.BuildOdp(pres)
  862. })
  863. /* ---------- PDF export (real text, mod/office/pdf) ----------
  864. Same (jsonStr, destVpath) shape as the ODF exporters. The Sheets
  865. variant takes the client-computed print model (formatted display
  866. strings + styles) instead of the raw workbook, since formula
  867. evaluation lives in the web client. */
  868. registerOdfExport("_office_documentToPdf", func(jsonStr string) ([]byte, error) {
  869. jsonStr, err := office.InlineMediaLinks(jsonStr, readVpath)
  870. if err != nil {
  871. return nil, err
  872. }
  873. doc, err := model.ParseDocumentJSON(jsonStr)
  874. if err != nil {
  875. return nil, err
  876. }
  877. return pdf.BuildDoc(doc)
  878. })
  879. registerOdfExport("_office_workbookPrintToPdf", func(jsonStr string) ([]byte, error) {
  880. m, err := pdf.ParseSheetPrintJSON(jsonStr)
  881. if err != nil {
  882. return nil, err
  883. }
  884. return pdf.BuildSheet(m)
  885. })
  886. /* ---------- write a file the web client produced ----------
  887. Slides builds its PDF in the browser (only the browser knows how the
  888. text actually laid out), so it needs a way to put those bytes on the
  889. file system. Same (payload, destVpath) shape and the same write
  890. permission check as every exporter above. */
  891. registerOdfExport("_office_writeBinaryFile", func(b64 string) ([]byte, error) {
  892. data, err := base64.StdEncoding.DecodeString(strings.TrimSpace(b64))
  893. if err != nil {
  894. return nil, errors.New("payload is not valid base64: " + err.Error())
  895. }
  896. return data, nil
  897. })
  898. vm.Run(`
  899. var office = {};
  900. office.pptxToPresentation = _office_pptxToPresentation; // pptx file -> Slides body JSON string
  901. office.presentationToPptx = _office_presentationToPptx; // Slides body JSON string -> pptx file (+ media sidecar zip; returns its vpath)
  902. office.xlsxToWorkbook = _office_xlsxToWorkbook; // xlsx file -> Sheets body JSON string
  903. office.workbookToXlsx = _office_workbookToXlsx; // Sheets body JSON string -> xlsx file
  904. office.docxToDocument = _office_docxToDocument; // docx file -> Docs body JSON string
  905. office.documentToDocx = _office_documentToDocx; // Docs body JSON string -> docx file
  906. office.saveDocument = _office_saveDocument; // envelope JSON -> .docx / .xlsx / .pptx (the suite's own save)
  907. office.loadDocument = _office_loadDocument; // .docx / .xlsx / .pptx (or .doc / .xls / .ppt) -> envelope JSON, media extracted to a workdir
  908. office.readPayload = _office_readPayload; // uploaded payload file -> string (gunzipped)
  909. office.touchWorkdir = _office_touchWorkdir; // keep an editor window's tmp:/.appdata/Office folders fresh
  910. office.releaseWorkdir = _office_releaseWorkdir; // delete an editor window's working folder (or its stale entries)
  911. office.packToFile = _office_packToFile; // envelope JSON -> session snapshot container file
  912. office.unpackToWorkdir = _office_unpackToWorkdir; // session snapshot -> envelope JSON, assets extracted to a workdir
  913. office.odtToDocument = _office_odtToDocument; // odt file -> Docs body JSON string
  914. office.documentToOdt = _office_documentToOdt; // Docs body JSON string -> odt file
  915. office.odsToWorkbook = _office_odsToWorkbook; // ods file -> Sheets body JSON string
  916. office.workbookToOds = _office_workbookToOds; // Sheets body JSON string -> ods file
  917. office.odpToPresentation = _office_odpToPresentation; // odp file -> Slides body JSON string
  918. office.presentationToOdp = _office_presentationToOdp; // Slides body JSON string -> odp file
  919. office.docToDocument = _office_docToDocument; // Word 97-2003 .doc file -> Docs body JSON string
  920. office.xlsToWorkbook = _office_xlsToWorkbook; // Excel 97-2003 .xls file -> Sheets body JSON string
  921. office.pptToPresentation = _office_pptToPresentation; // PowerPoint 97-2003 .ppt file -> Slides body JSON string
  922. office.convertLegacy = _office_convertLegacy; // .doc / .xls / .ppt file -> .docx / .xlsx / .pptx file
  923. office.documentToPdf = _office_documentToPdf; // Docs body JSON string -> pdf file (real text)
  924. office.workbookPrintToPdf = _office_workbookPrintToPdf; // Sheets print-model JSON -> pdf file (real text)
  925. office.writeBinaryFile = _office_writeBinaryFile; // base64 string -> binary file (client-produced exports)
  926. `)
  927. }
  928. /*
  929. Example Usages
  930. // Import: convert a .pptx into the Slides editor body schema
  931. if (requirelib("office")) {
  932. var bodyJson = office.pptxToPresentation("user:/Desktop/deck.pptx");
  933. sendJSONResp('{"body":' + bodyJson + '}');
  934. }
  935. // Export: build a .pptx from a serialized Slides body
  936. if (requirelib("office")) {
  937. var ok = office.presentationToPptx(bodyJsonString, "user:/Desktop/out.pptx");
  938. if (ok) { sendResp("OK"); }
  939. }
  940. // The suite's own save / open (envelope in, envelope out)
  941. if (requirelib("office")) {
  942. office.saveDocument(envelopeJson, "user:/Documents/report.docx");
  943. var env = office.loadDocument("user:/Documents/report.docx", "user:/.appdata/Office/cache");
  944. }
  945. */