services_backend_script_api.js.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>JSDoc: Source: services/backend_script_api.js</title>
  6. <script src="scripts/prettify/prettify.js"> </script>
  7. <script src="scripts/prettify/lang-css.js"> </script>
  8. <!--[if lt IE 9]>
  9. <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  10. <![endif]-->
  11. <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
  12. <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
  13. </head>
  14. <body>
  15. <div id="main">
  16. <h1 class="page-title">Source: services/backend_script_api.js</h1>
  17. <section>
  18. <article>
  19. <pre class="prettyprint source linenums"><code>const log = require('./log');
  20. const noteService = require('./notes');
  21. const sql = require('./sql');
  22. const utils = require('./utils');
  23. const attributeService = require('./attributes');
  24. const dateNoteService = require('./date_notes');
  25. const treeService = require('./tree');
  26. const config = require('./config');
  27. const axios = require('axios');
  28. const dayjs = require('dayjs');
  29. const xml2js = require('xml2js');
  30. const cloningService = require('./cloning');
  31. const appInfo = require('./app_info');
  32. const searchService = require('./search/services/search');
  33. const SearchContext = require("./search/search_context");
  34. const becca = require("../becca/becca");
  35. /**
  36. * This is the main backend API interface for scripts. It's published in the local "api" object.
  37. *
  38. * @constructor
  39. * @hideconstructor
  40. */
  41. function BackendScriptApi(currentNote, apiParams) {
  42. /** @property {Note} note where script started executing */
  43. this.startNote = apiParams.startNote;
  44. /** @property {Note} note where script is currently executing. Don't mix this up with concept of active note */
  45. this.currentNote = currentNote;
  46. /** @property {Entity} entity whose event triggered this executions */
  47. this.originEntity = apiParams.originEntity;
  48. for (const key in apiParams) {
  49. this[key] = apiParams[key];
  50. }
  51. /** @property {axios} Axios library for HTTP requests. See https://axios-http.com/ for documentation */
  52. this.axios = axios;
  53. /** @property {dayjs} day.js library for date manipulation. See https://day.js.org/ for documentation */
  54. this.dayjs = dayjs;
  55. /** @property {axios} xml2js library for XML parsing. See https://github.com/Leonidas-from-XIV/node-xml2js for documentation */
  56. this.xml2js = xml2js;
  57. // DEPRECATED - use direct api.unescapeHtml
  58. this.utils = {
  59. unescapeHtml: utils.unescapeHtml
  60. };
  61. /**
  62. * Instance name identifies particular Trilium instance. It can be useful for scripts
  63. * if some action needs to happen on only one specific instance.
  64. *
  65. * @returns {string|null}
  66. */
  67. this.getInstanceName = () => config.General ? config.General.instanceName : null;
  68. /**
  69. * @method
  70. * @param {string} noteId
  71. * @returns {Note|null}
  72. */
  73. this.getNote = noteId => becca.getNote(noteId);
  74. /**
  75. * @method
  76. * @param {string} branchId
  77. * @returns {Branch|null}
  78. */
  79. this.getBranch = branchId => becca.getBranch(branchId);
  80. /**
  81. * @method
  82. * @param {string} attributeId
  83. * @returns {Attribute|null}
  84. */
  85. this.getAttribute = attributeId => becca.getAttribute(attributeId);
  86. /**
  87. * This is a powerful search method - you can search by attributes and their values, e.g.:
  88. * "#dateModified =* MONTH AND #log". See full documentation for all options at: https://github.com/zadam/trilium/wiki/Search
  89. *
  90. * @method
  91. * @param {string} query
  92. * @param {Object} [searchParams]
  93. * @returns {Note[]}
  94. */
  95. this.searchForNotes = (query, searchParams = {}) => {
  96. if (searchParams.includeArchivedNotes === undefined) {
  97. searchParams.includeArchivedNotes = true;
  98. }
  99. if (searchParams.ignoreHoistedNote === undefined) {
  100. searchParams.ignoreHoistedNote = true;
  101. }
  102. const noteIds = searchService.findResultsWithQuery(query, new SearchContext(searchParams))
  103. .map(sr => sr.noteId);
  104. return becca.getNotes(noteIds);
  105. };
  106. /**
  107. * This is a powerful search method - you can search by attributes and their values, e.g.:
  108. * "#dateModified =* MONTH AND #log". See full documentation for all options at: https://github.com/zadam/trilium/wiki/Search
  109. *
  110. * @method
  111. * @param {string} query
  112. * @param {Object} [searchParams]
  113. * @returns {Note|null}
  114. */
  115. this.searchForNote = (query, searchParams = {}) => {
  116. const notes = this.searchForNotes(query, searchParams);
  117. return notes.length > 0 ? notes[0] : null;
  118. };
  119. /**
  120. * Retrieves notes with given label name &amp; value
  121. *
  122. * @method
  123. * @param {string} name - attribute name
  124. * @param {string} [value] - attribute value
  125. * @returns {Note[]}
  126. */
  127. this.getNotesWithLabel = attributeService.getNotesWithLabel;
  128. /**
  129. * Retrieves first note with given label name &amp; value
  130. *
  131. * @method
  132. * @param {string} name - attribute name
  133. * @param {string} [value] - attribute value
  134. * @returns {Note|null}
  135. */
  136. this.getNoteWithLabel = attributeService.getNoteWithLabel;
  137. /**
  138. * If there's no branch between note and parent note, create one. Otherwise do nothing.
  139. *
  140. * @method
  141. * @param {string} noteId
  142. * @param {string} parentNoteId
  143. * @param {string} prefix - if branch will be create between note and parent note, set this prefix
  144. * @returns {void}
  145. */
  146. this.ensureNoteIsPresentInParent = cloningService.ensureNoteIsPresentInParent;
  147. /**
  148. * If there's a branch between note and parent note, remove it. Otherwise do nothing.
  149. *
  150. * @method
  151. * @param {string} noteId
  152. * @param {string} parentNoteId
  153. * @returns {void}
  154. */
  155. this.ensureNoteIsAbsentFromParent = cloningService.ensureNoteIsAbsentFromParent;
  156. /**
  157. * Based on the value, either create or remove branch between note and parent note.
  158. *
  159. * @method
  160. * @param {boolean} present - true if we want the branch to exist, false if we want it gone
  161. * @param {string} noteId
  162. * @param {string} parentNoteId
  163. * @param {string} prefix - if branch will be create between note and parent note, set this prefix
  164. * @returns {void}
  165. */
  166. this.toggleNoteInParent = cloningService.toggleNoteInParent;
  167. /**
  168. * @typedef {object} CreateNoteAttribute
  169. * @property {string} type - attribute type - label, relation etc.
  170. * @property {string} name - attribute name
  171. * @property {string} [value] - attribute value
  172. */
  173. /**
  174. * Create text note. See also createNewNote() for more options.
  175. *
  176. * @param {string} parentNoteId
  177. * @param {string} title
  178. * @param {string} content
  179. * @return {{note: Note, branch: Branch}} - object having "note" and "branch" keys representing respective objects
  180. */
  181. this.createTextNote = (parentNoteId, title, content = '') => noteService.createNewNote({
  182. parentNoteId,
  183. title,
  184. content,
  185. type: 'text'
  186. });
  187. /**
  188. * Create data note - data in this context means object serializable to JSON. Created note will be of type 'code' and
  189. * JSON MIME type. See also createNewNote() for more options.
  190. *
  191. * @param {string} parentNoteId
  192. * @param {string} title
  193. * @param {object} content
  194. * @return {{note: Note, branch: Branch}} object having "note" and "branch" keys representing respective objects
  195. */
  196. this.createDataNote = (parentNoteId, title, content = {}) => noteService.createNewNote({
  197. parentNoteId,
  198. title,
  199. content: JSON.stringify(content, null, '\t'),
  200. type: 'code',
  201. mime: 'application/json'
  202. });
  203. /**
  204. * @typedef {object} CreateNewNoteParams
  205. * @property {string} parentNoteId - MANDATORY
  206. * @property {string} title - MANDATORY
  207. * @property {string|buffer} content - MANDATORY
  208. * @property {string} type - text, code, file, image, search, book, relation-map - MANDATORY
  209. * @property {string} mime - value is derived from default mimes for type
  210. * @property {boolean} isProtected - default is false
  211. * @property {boolean} isExpanded - default is false
  212. * @property {string} prefix - default is empty string
  213. * @property {int} notePosition - default is last existing notePosition in a parent + 10
  214. */
  215. /**
  216. * @method
  217. *
  218. * @param {CreateNewNoteParams} [params]
  219. * @returns {{note: Note, branch: Branch}} object contains newly created entities note and branch
  220. */
  221. this.createNewNote = noteService.createNewNote;
  222. /**
  223. * @typedef {object} CreateNoteAttribute
  224. * @property {string} type - attribute type - label, relation etc.
  225. * @property {string} name - attribute name
  226. * @property {string} [value] - attribute value
  227. */
  228. /**
  229. * @typedef {object} CreateNoteExtraOptions
  230. * @property {boolean} [json=false] - should the note be JSON
  231. * @property {boolean} [isProtected=false] - should the note be protected
  232. * @property {string} [type='text'] - note type
  233. * @property {string} [mime='text/html'] - MIME type of the note
  234. * @property {CreateNoteAttribute[]} [attributes=[]] - attributes to be created for this note
  235. */
  236. /**
  237. * @method
  238. * @deprecated please use createTextNote() with similar API for simpler use cases or createNewNote() for more complex needs
  239. *
  240. * @param {string} parentNoteId - create new note under this parent
  241. * @param {string} title
  242. * @param {string} [content=""]
  243. * @param {CreateNoteExtraOptions} [extraOptions={}]
  244. * @returns {{note: Note, branch: Branch}} object contains newly created entities note and branch
  245. */
  246. this.createNote = (parentNoteId, title, content = "", extraOptions= {}) => {
  247. extraOptions.parentNoteId = parentNoteId;
  248. extraOptions.title = title;
  249. const parentNote = becca.getNote(parentNoteId);
  250. // code note type can be inherited, otherwise text is default
  251. extraOptions.type = parentNote.type === 'code' ? 'code' : 'text';
  252. extraOptions.mime = parentNote.type === 'code' ? parentNote.mime : 'text/html';
  253. if (extraOptions.json) {
  254. extraOptions.content = JSON.stringify(content || {}, null, '\t');
  255. extraOptions.type = 'code';
  256. extraOptions.mime = 'application/json';
  257. }
  258. else {
  259. extraOptions.content = content;
  260. }
  261. return sql.transactional(() => {
  262. const {note, branch} = noteService.createNewNote(extraOptions);
  263. for (const attr of extraOptions.attributes || []) {
  264. attributeService.createAttribute({
  265. noteId: note.noteId,
  266. type: attr.type,
  267. name: attr.name,
  268. value: attr.value,
  269. isInheritable: !!attr.isInheritable
  270. });
  271. }
  272. return {note, branch};
  273. });
  274. };
  275. /**
  276. * Log given message to trilium logs.
  277. *
  278. * @param message
  279. */
  280. this.log = message => log.info(`Script "${currentNote.title}" (${currentNote.noteId}): ${message}`);
  281. /**
  282. * Returns root note of the calendar.
  283. *
  284. * @method
  285. * @returns {Note|null}
  286. */
  287. this.getRootCalendarNote = dateNoteService.getRootCalendarNote;
  288. /**
  289. * Returns day note for given date. If such note doesn't exist, it is created.
  290. *
  291. * @method
  292. * @param {string} date in YYYY-MM-DD format
  293. * @returns {Note|null}
  294. */
  295. this.getDateNote = dateNoteService.getDateNote;
  296. /**
  297. * Returns today's day note. If such note doesn't exist, it is created.
  298. *
  299. * @method
  300. * @returns {Note|null}
  301. */
  302. this.getTodayNote = dateNoteService.getTodayNote;
  303. /**
  304. * Returns note for the first date of the week of the given date.
  305. *
  306. * @method
  307. * @param {string} date in YYYY-MM-DD format
  308. * @param {object} options - "startOfTheWeek" - either "monday" (default) or "sunday"
  309. * @returns {Note|null}
  310. */
  311. this.getWeekNote = dateNoteService.getWeekNote;
  312. /**
  313. * Returns month note for given date. If such note doesn't exist, it is created.
  314. *
  315. * @method
  316. * @param {string} date in YYYY-MM format
  317. * @returns {Note|null}
  318. */
  319. this.getMonthNote = dateNoteService.getMonthNote;
  320. /**
  321. * Returns year note for given year. If such note doesn't exist, it is created.
  322. *
  323. * @method
  324. * @param {string} year in YYYY format
  325. * @returns {Note|null}
  326. */
  327. this.getYearNote = dateNoteService.getYearNote;
  328. /**
  329. * @method
  330. * @param {string} parentNoteId - this note's child notes will be sorted
  331. */
  332. this.sortNotesByTitle = parentNoteId => treeService.sortNotes(parentNoteId);
  333. /**
  334. * This method finds note by its noteId and prefix and either sets it to the given parentNoteId
  335. * or removes the branch (if parentNoteId is not given).
  336. *
  337. * This method looks similar to toggleNoteInParent() but differs because we're looking up branch by prefix.
  338. *
  339. * @method
  340. * @deprecated - this method is pretty confusing and serves specialized purpose only
  341. * @param {string} noteId
  342. * @param {string} prefix
  343. * @param {string|null} parentNoteId
  344. */
  345. this.setNoteToParent = treeService.setNoteToParent;
  346. /**
  347. * This functions wraps code which is supposed to be running in transaction. If transaction already
  348. * exists, then we'll use that transaction.
  349. *
  350. * @method
  351. * @param {function} func
  352. * @returns {?} result of func callback
  353. */
  354. this.transactional = sql.transactional;
  355. /**
  356. * Return randomly generated string of given length. This random string generation is NOT cryptographically secure.
  357. *
  358. * @method
  359. * @param {number} length of the string
  360. * @returns {string} random string
  361. */
  362. this.randomString = utils.randomString;
  363. /**
  364. * @method
  365. * @param {string} string to escape
  366. * @returns {string} escaped string
  367. */
  368. this.escapeHtml = utils.escapeHtml;
  369. /**
  370. * @method
  371. * @param {string} string to unescape
  372. * @returns {string} unescaped string
  373. */
  374. this.unescapeHtml = utils.unescapeHtml;
  375. /**
  376. * @property {module:sql} sql
  377. */
  378. this.sql = sql;
  379. /**
  380. * @method
  381. * @deprecated - this is now no-op since all the changes should be gracefully handled per widget
  382. */
  383. this.refreshTree = () => {};
  384. /**
  385. * @return {{syncVersion, appVersion, buildRevision, dbVersion, dataDirectory, buildDate}|*} - object representing basic info about running Trilium version
  386. */
  387. this.getAppInfo = () => appInfo
  388. }
  389. module.exports = BackendScriptApi;
  390. </code></pre>
  391. </article>
  392. </section>
  393. </div>
  394. <nav>
  395. <h2><a href="index.html">Home</a></h2><h3>Modules</h3><ul><li><a href="module-sql.html">sql</a></li></ul><h3>Classes</h3><ul><li><a href="ApiToken.html">ApiToken</a></li><li><a href="Attribute.html">Attribute</a></li><li><a href="BackendScriptApi.html">BackendScriptApi</a></li><li><a href="Branch.html">Branch</a></li><li><a href="Note.html">Note</a></li><li><a href="NoteRevision.html">NoteRevision</a></li><li><a href="Option.html">Option</a></li><li><a href="RecentNote.html">RecentNote</a></li></ul><h3><a href="global.html">Global</a></h3>
  396. </nav>
  397. <br class="clear">
  398. <footer>
  399. Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 3.6.7</a>
  400. </footer>
  401. <script> prettyPrint(); </script>
  402. <script src="scripts/linenumber.js"> </script>
  403. </body>
  404. </html>