entities_note.js.html 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>JSDoc: Source: entities/note.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: entities/note.js</h1>
  17. <section>
  18. <article>
  19. <pre class="prettyprint source linenums"><code>"use strict";
  20. const Entity = require('./entity');
  21. const Attribute = require('./attribute');
  22. const protectedSessionService = require('../services/protected_session');
  23. const repository = require('../services/repository');
  24. const sql = require('../services/sql');
  25. const utils = require('../services/utils');
  26. const dateUtils = require('../services/date_utils');
  27. const syncTableService = require('../services/sync_table');
  28. const LABEL = 'label';
  29. const LABEL_DEFINITION = 'label-definition';
  30. const RELATION = 'relation';
  31. const RELATION_DEFINITION = 'relation-definition';
  32. /**
  33. * This represents a Note which is a central object in the Trilium Notes project.
  34. *
  35. * @property {string} noteId - primary key
  36. * @property {string} type - one of "text", "code", "file" or "render"
  37. * @property {string} mime - MIME type, e.g. "text/html"
  38. * @property {string} title - note title
  39. * @property {int} contentLength - length of content
  40. * @property {boolean} isProtected - true if note is protected
  41. * @property {boolean} isDeleted - true if note is deleted
  42. * @property {string|null} deleteId - ID identifying delete transaction
  43. * @property {boolean} isErased - true if note's content is erased after it has been deleted
  44. * @property {string} dateCreated - local date time (with offset)
  45. * @property {string} dateModified - local date time (with offset)
  46. * @property {string} utcDateCreated
  47. * @property {string} utcDateModified
  48. *
  49. * @extends Entity
  50. */
  51. class Note extends Entity {
  52. static get entityName() { return "notes"; }
  53. static get primaryKeyName() { return "noteId"; }
  54. static get hashedProperties() { return ["noteId", "title", "type", "mime", "isProtected", "isDeleted", "deleteId"]; }
  55. /**
  56. * @param row - object containing database row from "notes" table
  57. */
  58. constructor(row) {
  59. super(row);
  60. this.isProtected = !!this.isProtected;
  61. /* true if content is either not encrypted
  62. * or encrypted, but with available protected session (so effectively decrypted) */
  63. this.isContentAvailable = true;
  64. // check if there's noteId, otherwise this is a new entity which wasn't encrypted yet
  65. if (this.isProtected &amp;&amp; this.noteId) {
  66. this.isContentAvailable = protectedSessionService.isProtectedSessionAvailable();
  67. if (this.isContentAvailable) {
  68. this.title = protectedSessionService.decryptString(this.title);
  69. }
  70. else {
  71. this.title = "[protected]";
  72. }
  73. }
  74. }
  75. /*
  76. * Note content has quite special handling - it's not a separate entity, but a lazily loaded
  77. * part of Note entity with it's own sync. Reasons behind this hybrid design has been:
  78. *
  79. * - content can be quite large and it's not necessary to load it / fill memory for any note access even if we don't need a content, especially for bulk operations like search
  80. * - changes in the note metadata or title should not trigger note content sync (so we keep separate utcDateModified and sync rows)
  81. * - but to the user note content and title changes are one and the same - single dateModified (so all changes must go through Note and content is not a separate entity)
  82. */
  83. /** @returns {Promise&lt;*>} */
  84. async getContent(silentNotFoundError = false) {
  85. if (this.content === undefined) {
  86. const res = await sql.getRow(`SELECT content, hash FROM note_contents WHERE noteId = ?`, [this.noteId]);
  87. if (!res) {
  88. if (silentNotFoundError) {
  89. return undefined;
  90. }
  91. else {
  92. throw new Error("Cannot find note content for noteId=" + this.noteId);
  93. }
  94. }
  95. this.content = res.content;
  96. if (this.isProtected) {
  97. if (this.isContentAvailable) {
  98. this.content = this.content === null ? null : protectedSessionService.decrypt(this.content);
  99. }
  100. else {
  101. this.content = "";
  102. }
  103. }
  104. }
  105. if (this.isStringNote()) {
  106. return this.content === null
  107. ? ""
  108. : this.content.toString("UTF-8");
  109. }
  110. else {
  111. return this.content;
  112. }
  113. }
  114. /** @returns {Promise&lt;*>} */
  115. async getJsonContent() {
  116. const content = await this.getContent();
  117. if (!content || !content.trim()) {
  118. return null;
  119. }
  120. return JSON.parse(content);
  121. }
  122. /** @returns {Promise} */
  123. async setContent(content) {
  124. if (content === null || content === undefined) {
  125. throw new Error(`Cannot set null content to note ${this.noteId}`);
  126. }
  127. content = Buffer.isBuffer(content) ? content : Buffer.from(content);
  128. // force updating note itself so that dateModified is represented correctly even for the content
  129. this.forcedChange = true;
  130. this.contentLength = content.byteLength;
  131. await this.save();
  132. this.content = content;
  133. const pojo = {
  134. noteId: this.noteId,
  135. content: content,
  136. utcDateModified: dateUtils.utcNowDateTime(),
  137. hash: utils.hash(this.noteId + "|" + content.toString())
  138. };
  139. if (this.isProtected) {
  140. if (this.isContentAvailable) {
  141. pojo.content = protectedSessionService.encrypt(pojo.content);
  142. }
  143. else {
  144. throw new Error(`Cannot update content of noteId=${this.noteId} since we're out of protected session.`);
  145. }
  146. }
  147. await sql.upsert("note_contents", "noteId", pojo);
  148. await syncTableService.addNoteContentSync(this.noteId);
  149. }
  150. /** @returns {Promise} */
  151. async setJsonContent(content) {
  152. await this.setContent(JSON.stringify(content, null, '\t'));
  153. }
  154. /** @returns {boolean} true if this note is the root of the note tree. Root note has "root" noteId */
  155. isRoot() {
  156. return this.noteId === 'root';
  157. }
  158. /** @returns {boolean} true if this note is of application/json content type */
  159. isJson() {
  160. return this.mime === "application/json";
  161. }
  162. /** @returns {boolean} true if this note is JavaScript (code or attachment) */
  163. isJavaScript() {
  164. return (this.type === "code" || this.type === "file")
  165. &amp;&amp; (this.mime.startsWith("application/javascript")
  166. || this.mime === "application/x-javascript"
  167. || this.mime === "text/javascript");
  168. }
  169. /** @returns {boolean} true if this note is HTML */
  170. isHtml() {
  171. return (this.type === "code" || this.type === "file" || this.type === "render") &amp;&amp; this.mime === "text/html";
  172. }
  173. /** @returns {boolean} true if the note has string content (not binary) */
  174. isStringNote() {
  175. return utils.isStringNote(this.type, this.mime);
  176. }
  177. /** @returns {string} JS script environment - either "frontend" or "backend" */
  178. getScriptEnv() {
  179. if (this.isHtml() || (this.isJavaScript() &amp;&amp; this.mime.endsWith('env=frontend'))) {
  180. return "frontend";
  181. }
  182. if (this.type === 'render') {
  183. return "frontend";
  184. }
  185. if (this.isJavaScript() &amp;&amp; this.mime.endsWith('env=backend')) {
  186. return "backend";
  187. }
  188. return null;
  189. }
  190. async loadOwnedAttributesToCache() {
  191. this.__ownedAttributeCache = await repository.getEntities(`SELECT * FROM attributes WHERE isDeleted = 0 AND noteId = ?`, [this.noteId]);
  192. return this.__ownedAttributeCache;
  193. }
  194. /**
  195. * This method is a faster variant of getAttributes() which looks for only owned attributes.
  196. * Use when inheritance is not needed and/or in batch/performance sensitive operations.
  197. *
  198. * @param {string} [type] - (optional) attribute type to filter
  199. * @param {string} [name] - (optional) attribute name to filter
  200. * @returns {Promise&lt;Attribute[]>} note's "owned" attributes - excluding inherited ones
  201. */
  202. async getOwnedAttributes(type, name) {
  203. if (!this.__ownedAttributeCache) {
  204. await this.loadOwnedAttributesToCache();
  205. }
  206. if (type &amp;&amp; name) {
  207. return this.__ownedAttributeCache.filter(attr => attr.type === type &amp;&amp; attr.name === name);
  208. }
  209. else if (type) {
  210. return this.__ownedAttributeCache.filter(attr => attr.type === type);
  211. }
  212. else if (name) {
  213. return this.__ownedAttributeCache.filter(attr => attr.name === name);
  214. }
  215. else {
  216. return this.__ownedAttributeCache.slice();
  217. }
  218. }
  219. /**
  220. * @returns {Promise&lt;Attribute>} attribute belonging to this specific note (excludes inherited attributes)
  221. *
  222. * This method can be significantly faster than the getAttribute()
  223. */
  224. async getOwnedAttribute(type, name) {
  225. const attrs = await this.getOwnedAttributes(type, name);
  226. return attrs.length > 0 ? attrs[0] : null;
  227. }
  228. /**
  229. * @returns {Promise&lt;Attribute[]>} relations targetting this specific note
  230. */
  231. async getTargetRelations() {
  232. return await repository.getEntities("SELECT * FROM attributes WHERE type = 'relation' AND isDeleted = 0 AND value = ?", [this.noteId]);
  233. }
  234. /**
  235. * @param {string} [type] - (optional) attribute type to filter
  236. * @param {string} [name] - (optional) attribute name to filter
  237. * @returns {Promise&lt;Attribute[]>} all note's attributes, including inherited ones
  238. */
  239. async getAttributes(type, name) {
  240. if (!this.__attributeCache) {
  241. await this.loadAttributesToCache();
  242. }
  243. if (type &amp;&amp; name) {
  244. return this.__attributeCache.filter(attr => attr.type === type &amp;&amp; attr.name === name);
  245. }
  246. else if (type) {
  247. return this.__attributeCache.filter(attr => attr.type === type);
  248. }
  249. else if (name) {
  250. return this.__attributeCache.filter(attr => attr.name === name);
  251. }
  252. else {
  253. return this.__attributeCache.slice();
  254. }
  255. }
  256. /**
  257. * @param {string} [name] - label name to filter
  258. * @returns {Promise&lt;Attribute[]>} all note's labels (attributes with type label), including inherited ones
  259. */
  260. async getLabels(name) {
  261. return await this.getAttributes(LABEL, name);
  262. }
  263. /**
  264. * @param {string} [name] - label name to filter
  265. * @returns {Promise&lt;Attribute[]>} all note's labels (attributes with type label), excluding inherited ones
  266. */
  267. async getOwnedLabels(name) {
  268. return await this.getOwnedAttributes(LABEL, name);
  269. }
  270. /**
  271. * @param {string} [name] - label name to filter
  272. * @returns {Promise&lt;Attribute[]>} all note's label definitions, including inherited ones
  273. */
  274. async getLabelDefinitions(name) {
  275. return await this.getAttributes(LABEL_DEFINITION, name);
  276. }
  277. /**
  278. * @param {string} [name] - relation name to filter
  279. * @returns {Promise&lt;Attribute[]>} all note's relations (attributes with type relation), including inherited ones
  280. */
  281. async getRelations(name) {
  282. return await this.getAttributes(RELATION, name);
  283. }
  284. /**
  285. * @param {string} [name] - relation name to filter
  286. * @returns {Promise&lt;Attribute[]>} all note's relations (attributes with type relation), excluding inherited ones
  287. */
  288. async getOwnedRelations(name) {
  289. return await this.getOwnedAttributes(RELATION, name);
  290. }
  291. /**
  292. * @param {string} [name] - relation name to filter
  293. * @returns {Promise&lt;Note[]>}
  294. */
  295. async getRelationTargets(name) {
  296. const relations = await this.getRelations(name);
  297. const targets = [];
  298. for (const relation of relations) {
  299. targets.push(await relation.getTargetNote());
  300. }
  301. return targets;
  302. }
  303. /**
  304. * @param {string} [name] - relation name to filter
  305. * @returns {Promise&lt;Attribute[]>} all note's relation definitions including inherited ones
  306. */
  307. async getRelationDefinitions(name) {
  308. return await this.getAttributes(RELATION_DEFINITION, name);
  309. }
  310. /**
  311. * Clear note's attributes cache to force fresh reload for next attribute request.
  312. * Cache is note instance scoped.
  313. */
  314. invalidateAttributeCache() {
  315. this.__attributeCache = null;
  316. this.__ownedAttributeCache = null;
  317. }
  318. /** @returns {Promise&lt;void>} */
  319. async loadAttributesToCache() {
  320. const attributes = await repository.getEntities(`
  321. WITH RECURSIVE
  322. tree(noteId, level) AS (
  323. SELECT ?, 0
  324. UNION
  325. SELECT branches.parentNoteId, tree.level + 1
  326. FROM branches
  327. JOIN tree ON branches.noteId = tree.noteId
  328. WHERE branches.isDeleted = 0
  329. ),
  330. treeWithAttrs(noteId, level) AS (
  331. SELECT * FROM tree
  332. UNION
  333. SELECT attributes.value, treeWithAttrs.level FROM attributes
  334. JOIN treeWithAttrs ON treeWithAttrs.noteId = attributes.noteId
  335. WHERE attributes.isDeleted = 0
  336. AND attributes.type = 'relation'
  337. AND attributes.name = 'template'
  338. AND (treeWithAttrs.level = 0 OR attributes.isInheritable = 1)
  339. )
  340. SELECT attributes.* FROM attributes JOIN treeWithAttrs ON attributes.noteId = treeWithAttrs.noteId
  341. WHERE attributes.isDeleted = 0 AND (attributes.isInheritable = 1 OR treeWithAttrs.level = 0)
  342. ORDER BY level, noteId, position`, [this.noteId]);
  343. // attributes are ordered so that "closest" attributes are first
  344. // we order by noteId so that attributes from same note stay together. Actual noteId ordering doesn't matter.
  345. const filteredAttributes = attributes.filter((attr, index) => {
  346. // if this exact attribute already appears then don't include it (can happen via cloning)
  347. if (attributes.findIndex(it => it.attributeId === attr.attributeId) !== index) {
  348. return false;
  349. }
  350. if (attr.isDefinition()) {
  351. const firstDefinitionIndex = attributes.findIndex(el => el.type === attr.type &amp;&amp; el.name === attr.name);
  352. // keep only if this element is the first definition for this type &amp; name
  353. return firstDefinitionIndex === index;
  354. }
  355. else {
  356. const definitionAttr = attributes.find(el => el.type === attr.type + '-definition' &amp;&amp; el.name === attr.name);
  357. if (!definitionAttr) {
  358. return true;
  359. }
  360. const definition = definitionAttr.value;
  361. if (definition.multiplicityType === 'multivalue') {
  362. return true;
  363. }
  364. else {
  365. const firstAttrIndex = attributes.findIndex(el => el.type === attr.type &amp;&amp; el.name === attr.name);
  366. // in case of single-valued attribute we'll keep it only if it's first (closest)
  367. return firstAttrIndex === index;
  368. }
  369. }
  370. });
  371. for (const attr of filteredAttributes) {
  372. attr.isOwned = attr.noteId === this.noteId;
  373. }
  374. this.__attributeCache = filteredAttributes;
  375. }
  376. /**
  377. * @param {string} type - attribute type (label, relation, etc.)
  378. * @param {string} name - attribute name
  379. * @returns {Promise&lt;boolean>} true if note has an attribute with given type and name (including inherited)
  380. */
  381. async hasAttribute(type, name) {
  382. return !!await this.getAttribute(type, name);
  383. }
  384. /**
  385. * @param {string} type - attribute type (label, relation, etc.)
  386. * @param {string} name - attribute name
  387. * @returns {Promise&lt;boolean>} true if note has an attribute with given type and name (excluding inherited)
  388. */
  389. async hasOwnedAttribute(type, name) {
  390. return !!await this.getOwnedAttribute(type, name);
  391. }
  392. /**
  393. * @param {string} type - attribute type (label, relation, etc.)
  394. * @param {string} name - attribute name
  395. * @returns {Promise&lt;Attribute>} attribute of given type and name. If there's more such attributes, first is returned. Returns null if there's no such attribute belonging to this note.
  396. */
  397. async getAttribute(type, name) {
  398. const attributes = await this.getAttributes();
  399. return attributes.find(attr => attr.type === type &amp;&amp; attr.name === name);
  400. }
  401. /**
  402. * @param {string} type - attribute type (label, relation, etc.)
  403. * @param {string} name - attribute name
  404. * @returns {Promise&lt;string|null>} attribute value of given type and name or null if no such attribute exists.
  405. */
  406. async getAttributeValue(type, name) {
  407. const attr = await this.getAttribute(type, name);
  408. return attr ? attr.value : null;
  409. }
  410. /**
  411. * @param {string} type - attribute type (label, relation, etc.)
  412. * @param {string} name - attribute name
  413. * @returns {Promise&lt;string|null>} attribute value of given type and name or null if no such attribute exists.
  414. */
  415. async getOwnedAttributeValue(type, name) {
  416. const attr = await this.getOwnedAttribute(type, name);
  417. return attr ? attr.value : null;
  418. }
  419. /**
  420. * Based on enabled, attribute is either set or removed.
  421. *
  422. * @param {string} type - attribute type ('relation', 'label' etc.)
  423. * @param {boolean} enabled - toggle On or Off
  424. * @param {string} name - attribute name
  425. * @param {string} [value] - attribute value (optional)
  426. * @returns {Promise&lt;void>}
  427. */
  428. async toggleAttribute(type, enabled, name, value) {
  429. if (enabled) {
  430. await this.setAttribute(type, name, value);
  431. }
  432. else {
  433. await this.removeAttribute(type, name, value);
  434. }
  435. }
  436. /**
  437. * Update's given attribute's value or creates it if it doesn't exist
  438. *
  439. * @param {string} type - attribute type (label, relation, etc.)
  440. * @param {string} name - attribute name
  441. * @param {string} [value] - attribute value (optional)
  442. * @returns {Promise&lt;void>}
  443. */
  444. async setAttribute(type, name, value) {
  445. const attributes = await this.loadOwnedAttributesToCache();
  446. let attr = attributes.find(attr => attr.type === type &amp;&amp; attr.name === name);
  447. if (attr) {
  448. if (attr.value !== value) {
  449. attr.value = value;
  450. await attr.save();
  451. this.invalidateAttributeCache();
  452. }
  453. }
  454. else {
  455. attr = new Attribute({
  456. noteId: this.noteId,
  457. type: type,
  458. name: name,
  459. value: value !== undefined ? value : ""
  460. });
  461. await attr.save();
  462. this.invalidateAttributeCache();
  463. }
  464. }
  465. /**
  466. * Removes given attribute name-value pair if it exists.
  467. *
  468. * @param {string} type - attribute type (label, relation, etc.)
  469. * @param {string} name - attribute name
  470. * @param {string} [value] - attribute value (optional)
  471. * @returns {Promise&lt;void>}
  472. */
  473. async removeAttribute(type, name, value) {
  474. const attributes = await this.loadOwnedAttributesToCache();
  475. for (const attribute of attributes) {
  476. if (attribute.type === type &amp;&amp; attribute.name === name &amp;&amp; (value === undefined || value === attribute.value)) {
  477. attribute.isDeleted = true;
  478. await attribute.save();
  479. this.invalidateAttributeCache();
  480. }
  481. }
  482. }
  483. /**
  484. * @return {Promise&lt;Attribute>}
  485. */
  486. async addAttribute(type, name, value = "") {
  487. const attr = new Attribute({
  488. noteId: this.noteId,
  489. type: type,
  490. name: name,
  491. value: value
  492. });
  493. await attr.save();
  494. this.invalidateAttributeCache();
  495. return attr;
  496. }
  497. async addLabel(name, value = "") {
  498. return await this.addAttribute(LABEL, name, value);
  499. }
  500. async addRelation(name, targetNoteId) {
  501. return await this.addAttribute(RELATION, name, targetNoteId);
  502. }
  503. /**
  504. * @param {string} name - label name
  505. * @returns {Promise&lt;boolean>} true if label exists (including inherited)
  506. */
  507. async hasLabel(name) { return await this.hasAttribute(LABEL, name); }
  508. /**
  509. * @param {string} name - label name
  510. * @returns {Promise&lt;boolean>} true if label exists (excluding inherited)
  511. */
  512. async hasOwnedLabel(name) { return await this.hasOwnedAttribute(LABEL, name); }
  513. /**
  514. * @param {string} name - relation name
  515. * @returns {Promise&lt;boolean>} true if relation exists (including inherited)
  516. */
  517. async hasRelation(name) { return await this.hasAttribute(RELATION, name); }
  518. /**
  519. * @param {string} name - relation name
  520. * @returns {Promise&lt;boolean>} true if relation exists (excluding inherited)
  521. */
  522. async hasOwnedRelation(name) { return await this.hasOwnedAttribute(RELATION, name); }
  523. /**
  524. * @param {string} name - label name
  525. * @returns {Promise&lt;Attribute|null>} label if it exists, null otherwise
  526. */
  527. async getLabel(name) { return await this.getAttribute(LABEL, name); }
  528. /**
  529. * @param {string} name - label name
  530. * @returns {Promise&lt;Attribute|null>} label if it exists, null otherwise
  531. */
  532. async getOwnedLabel(name) { return await this.getOwnedAttribute(LABEL, name); }
  533. /**
  534. * @param {string} name - relation name
  535. * @returns {Promise&lt;Attribute|null>} relation if it exists, null otherwise
  536. */
  537. async getRelation(name) { return await this.getAttribute(RELATION, name); }
  538. /**
  539. * @param {string} name - relation name
  540. * @returns {Promise&lt;Attribute|null>} relation if it exists, null otherwise
  541. */
  542. async getOwnedRelation(name) { return await this.getOwnedAttribute(RELATION, name); }
  543. /**
  544. * @param {string} name - label name
  545. * @returns {Promise&lt;string|null>} label value if label exists, null otherwise
  546. */
  547. async getLabelValue(name) { return await this.getAttributeValue(LABEL, name); }
  548. /**
  549. * @param {string} name - label name
  550. * @returns {Promise&lt;string|null>} label value if label exists, null otherwise
  551. */
  552. async getOwnedLabelValue(name) { return await this.getOwnedAttributeValue(LABEL, name); }
  553. /**
  554. * @param {string} name - relation name
  555. * @returns {Promise&lt;string|null>} relation value if relation exists, null otherwise
  556. */
  557. async getRelationValue(name) { return await this.getAttributeValue(RELATION, name); }
  558. /**
  559. * @param {string} name - relation name
  560. * @returns {Promise&lt;string|null>} relation value if relation exists, null otherwise
  561. */
  562. async getOwnedRelationValue(name) { return await this.getOwnedAttributeValue(RELATION, name); }
  563. /**
  564. * @param {string} name
  565. * @returns {Promise&lt;Note>|null} target note of the relation or null (if target is empty or note was not found)
  566. */
  567. async getRelationTarget(name) {
  568. const relation = await this.getRelation(name);
  569. return relation ? await repository.getNote(relation.value) : null;
  570. }
  571. /**
  572. * @param {string} name
  573. * @returns {Promise&lt;Note>|null} target note of the relation or null (if target is empty or note was not found)
  574. */
  575. async getOwnedRelationTarget(name) {
  576. const relation = await this.getOwnedRelation(name);
  577. return relation ? await repository.getNote(relation.value) : null;
  578. }
  579. /**
  580. * Based on enabled, label is either set or removed.
  581. *
  582. * @param {boolean} enabled - toggle On or Off
  583. * @param {string} name - label name
  584. * @param {string} [value] - label value (optional)
  585. * @returns {Promise&lt;void>}
  586. */
  587. async toggleLabel(enabled, name, value) { return await this.toggleAttribute(LABEL, enabled, name, value); }
  588. /**
  589. * Based on enabled, relation is either set or removed.
  590. *
  591. * @param {boolean} enabled - toggle On or Off
  592. * @param {string} name - relation name
  593. * @param {string} [value] - relation value (noteId)
  594. * @returns {Promise&lt;void>}
  595. */
  596. async toggleRelation(enabled, name, value) { return await this.toggleAttribute(RELATION, enabled, name, value); }
  597. /**
  598. * Update's given label's value or creates it if it doesn't exist
  599. *
  600. * @param {string} name - label name
  601. * @param {string} [value] - label value
  602. * @returns {Promise&lt;void>}
  603. */
  604. async setLabel(name, value) { return await this.setAttribute(LABEL, name, value); }
  605. /**
  606. * Update's given relation's value or creates it if it doesn't exist
  607. *
  608. * @param {string} name - relation name
  609. * @param {string} [value] - relation value (noteId)
  610. * @returns {Promise&lt;void>}
  611. */
  612. async setRelation(name, value) { return await this.setAttribute(RELATION, name, value); }
  613. /**
  614. * Remove label name-value pair, if it exists.
  615. *
  616. * @param {string} name - label name
  617. * @param {string} [value] - label value
  618. * @returns {Promise&lt;void>}
  619. */
  620. async removeLabel(name, value) { return await this.removeAttribute(LABEL, name, value); }
  621. /**
  622. * Remove relation name-value pair, if it exists.
  623. *
  624. * @param {string} name - relation name
  625. * @param {string} [value] - relation value (noteId)
  626. * @returns {Promise&lt;void>}
  627. */
  628. async removeRelation(name, value) { return await this.removeAttribute(RELATION, name, value); }
  629. /**
  630. * @return {Promise&lt;string[]>} return list of all descendant noteIds of this note. Returning just noteIds because number of notes can be huge. Includes also this note's noteId
  631. */
  632. async getDescendantNoteIds() {
  633. return await sql.getColumn(`
  634. WITH RECURSIVE
  635. tree(noteId) AS (
  636. SELECT ?
  637. UNION
  638. SELECT branches.noteId FROM branches
  639. JOIN tree ON branches.parentNoteId = tree.noteId
  640. JOIN notes ON notes.noteId = branches.noteId
  641. WHERE notes.isDeleted = 0
  642. AND branches.isDeleted = 0
  643. )
  644. SELECT noteId FROM tree`, [this.noteId]);
  645. }
  646. /**
  647. * Finds descendant notes with given attribute name and value. Only own attributes are considered, not inherited ones
  648. *
  649. * @param {string} type - attribute type (label, relation, etc.)
  650. * @param {string} name - attribute name
  651. * @param {string} [value] - attribute value
  652. * @returns {Promise&lt;Note[]>}
  653. */
  654. async getDescendantNotesWithAttribute(type, name, value) {
  655. const params = [this.noteId, name];
  656. let valueCondition = "";
  657. if (value !== undefined) {
  658. params.push(value);
  659. valueCondition = " AND attributes.value = ?";
  660. }
  661. const notes = await repository.getEntities(`
  662. WITH RECURSIVE
  663. tree(noteId) AS (
  664. SELECT ?
  665. UNION
  666. SELECT branches.noteId FROM branches
  667. JOIN tree ON branches.parentNoteId = tree.noteId
  668. JOIN notes ON notes.noteId = branches.noteId
  669. WHERE notes.isDeleted = 0
  670. AND branches.isDeleted = 0
  671. )
  672. SELECT notes.* FROM notes
  673. JOIN tree ON tree.noteId = notes.noteId
  674. JOIN attributes ON attributes.noteId = notes.noteId
  675. WHERE attributes.isDeleted = 0
  676. AND attributes.name = ?
  677. ${valueCondition}
  678. ORDER BY noteId, position`, params);
  679. return notes;
  680. }
  681. /**
  682. * Finds descendant notes with given label name and value. Only own labels are considered, not inherited ones
  683. *
  684. * @param {string} name - label name
  685. * @param {string} [value] - label value
  686. * @returns {Promise&lt;Note[]>}
  687. */
  688. async getDescendantNotesWithLabel(name, value) { return await this.getDescendantNotesWithAttribute(LABEL, name, value); }
  689. /**
  690. * Finds descendant notes with given relation name and value. Only own relations are considered, not inherited ones
  691. *
  692. * @param {string} name - relation name
  693. * @param {string} [value] - relation value
  694. * @returns {Promise&lt;Note[]>}
  695. */
  696. async getDescendantNotesWithRelation(name, value) { return await this.getDescendantNotesWithAttribute(RELATION, name, value); }
  697. /**
  698. * Returns note revisions of this note.
  699. *
  700. * @returns {Promise&lt;NoteRevision[]>}
  701. */
  702. async getRevisions() {
  703. return await repository.getEntities("SELECT * FROM note_revisions WHERE noteId = ?", [this.noteId]);
  704. }
  705. /**
  706. * Get list of links coming out of this note.
  707. *
  708. * @deprecated - not intended for general use
  709. * @returns {Promise&lt;Attribute[]>}
  710. */
  711. async getLinks() {
  712. return await repository.getEntities(`
  713. SELECT *
  714. FROM attributes
  715. WHERE noteId = ? AND
  716. isDeleted = 0 AND
  717. type = 'relation' AND
  718. name IN ('internalLink', 'imageLink', 'relationMapLink', 'includeNoteLink')`, [this.noteId]);
  719. }
  720. /**
  721. * @returns {Promise&lt;Branch[]>}
  722. */
  723. async getBranches() {
  724. return await repository.getEntities("SELECT * FROM branches WHERE isDeleted = 0 AND noteId = ?", [this.noteId]);
  725. }
  726. /**
  727. * @returns {boolean} - true if note has children
  728. */
  729. async hasChildren() {
  730. return (await this.getChildNotes()).length > 0;
  731. }
  732. /**
  733. * @returns {Promise&lt;Note[]>} child notes of this note
  734. */
  735. async getChildNotes() {
  736. return await repository.getEntities(`
  737. SELECT notes.*
  738. FROM branches
  739. JOIN notes USING(noteId)
  740. WHERE notes.isDeleted = 0
  741. AND branches.isDeleted = 0
  742. AND branches.parentNoteId = ?
  743. ORDER BY branches.notePosition`, [this.noteId]);
  744. }
  745. /**
  746. * @returns {Promise&lt;Branch[]>} child branches of this note
  747. */
  748. async getChildBranches() {
  749. return await repository.getEntities(`
  750. SELECT branches.*
  751. FROM branches
  752. WHERE branches.isDeleted = 0
  753. AND branches.parentNoteId = ?
  754. ORDER BY branches.notePosition`, [this.noteId]);
  755. }
  756. /**
  757. * @returns {Promise&lt;Note[]>} parent notes of this note (note can have multiple parents because of cloning)
  758. */
  759. async getParentNotes() {
  760. return await repository.getEntities(`
  761. SELECT parent_notes.*
  762. FROM
  763. branches AS child_tree
  764. JOIN notes AS parent_notes ON parent_notes.noteId = child_tree.parentNoteId
  765. WHERE child_tree.noteId = ?
  766. AND child_tree.isDeleted = 0
  767. AND parent_notes.isDeleted = 0`, [this.noteId]);
  768. }
  769. /**
  770. * @return {Promise&lt;string[][]>} - array of notePaths (each represented by array of noteIds constituting the particular note path)
  771. */
  772. async getAllNotePaths() {
  773. if (this.noteId === 'root') {
  774. return [['root']];
  775. }
  776. const notePaths = [];
  777. for (const parentNote of await this.getParentNotes()) {
  778. for (const parentPath of await parentNote.getAllNotePaths()) {
  779. parentPath.push(this.noteId);
  780. notePaths.push(parentPath);
  781. }
  782. }
  783. return notePaths;
  784. }
  785. /**
  786. * @param ancestorNoteId
  787. * @return {Promise&lt;boolean>} - true if ancestorNoteId occurs in at least one of the note's paths
  788. */
  789. async isDescendantOfNote(ancestorNoteId) {
  790. const notePaths = await this.getAllNotePaths();
  791. return notePaths.some(path => path.includes(ancestorNoteId));
  792. }
  793. beforeSaving() {
  794. if (!this.isDeleted) {
  795. this.isDeleted = false;
  796. }
  797. if (!this.dateCreated) {
  798. this.dateCreated = dateUtils.localNowDateTime();
  799. }
  800. if (!this.utcDateCreated) {
  801. this.utcDateCreated = dateUtils.utcNowDateTime();
  802. }
  803. if (this.contentLength === undefined) {
  804. this.contentLength = -1;
  805. }
  806. super.beforeSaving();
  807. if (this.isChanged) {
  808. this.dateModified = dateUtils.localNowDateTime();
  809. this.utcDateModified = dateUtils.utcNowDateTime();
  810. }
  811. }
  812. // cannot be static!
  813. updatePojo(pojo) {
  814. if (pojo.isProtected) {
  815. if (this.isContentAvailable) {
  816. pojo.title = protectedSessionService.encrypt(pojo.title);
  817. }
  818. else {
  819. // updating protected note outside of protected session means we will keep original ciphertexts
  820. delete pojo.title;
  821. }
  822. }
  823. delete pojo.isContentAvailable;
  824. delete pojo.__attributeCache;
  825. delete pojo.__ownedAttributeCache;
  826. delete pojo.content;
  827. /** zero references to contentHash, probably can be removed */
  828. delete pojo.contentHash;
  829. }
  830. }
  831. module.exports = Note;</code></pre>
  832. </article>
  833. </section>
  834. </div>
  835. <nav>
  836. <h2><a href="index.html">Home</a></h2><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="Entity.html">Entity</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>
  837. </nav>
  838. <br class="clear">
  839. <footer>
  840. Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 3.6.4</a>
  841. </footer>
  842. <script> prettyPrint(); </script>
  843. <script src="scripts/linenumber.js"> </script>
  844. </body>
  845. </html>