becca_entities_abstract_becca_entity.js.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>JSDoc: Source: becca/entities/abstract_becca_entity.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: becca/entities/abstract_becca_entity.js</h1>
  17. <section>
  18. <article>
  19. <pre class="prettyprint source linenums"><code>"use strict";
  20. const utils = require('../../services/utils');
  21. const sql = require('../../services/sql');
  22. const entityChangesService = require('../../services/entity_changes');
  23. const eventService = require("../../services/events");
  24. const dateUtils = require("../../services/date_utils");
  25. const cls = require("../../services/cls");
  26. const log = require("../../services/log");
  27. const protectedSessionService = require("../../services/protected_session");
  28. const blobService = require("../../services/blob");
  29. let becca = null;
  30. /**
  31. * Base class for all backend entities.
  32. */
  33. class AbstractBeccaEntity {
  34. /** @protected */
  35. beforeSaving() {
  36. if (!this[this.constructor.primaryKeyName]) {
  37. this[this.constructor.primaryKeyName] = utils.newEntityId();
  38. }
  39. }
  40. /** @protected */
  41. getUtcDateChanged() {
  42. return this.utcDateModified || this.utcDateCreated;
  43. }
  44. /**
  45. * @protected
  46. * @returns {Becca}
  47. */
  48. get becca() {
  49. if (!becca) {
  50. becca = require('../becca');
  51. }
  52. return becca;
  53. }
  54. /** @protected */
  55. putEntityChange(isDeleted) {
  56. entityChangesService.putEntityChange({
  57. entityName: this.constructor.entityName,
  58. entityId: this[this.constructor.primaryKeyName],
  59. hash: this.generateHash(isDeleted),
  60. isErased: false,
  61. utcDateChanged: this.getUtcDateChanged(),
  62. isSynced: this.constructor.entityName !== 'options' || !!this.isSynced
  63. });
  64. }
  65. /**
  66. * @protected
  67. * @returns {string}
  68. */
  69. generateHash(isDeleted) {
  70. let contentToHash = "";
  71. for (const propertyName of this.constructor.hashedProperties) {
  72. contentToHash += `|${this[propertyName]}`;
  73. }
  74. if (isDeleted) {
  75. contentToHash += "|deleted";
  76. }
  77. return utils.hash(contentToHash).substr(0, 10);
  78. }
  79. /** @protected */
  80. getPojoToSave() {
  81. return this.getPojo();
  82. }
  83. /**
  84. * @protected
  85. * @abstract
  86. */
  87. getPojo() {
  88. throw new Error(`Unimplemented getPojo() for entity '${this.constructor.name}'`)
  89. }
  90. /**
  91. * Saves entity - executes SQL, but doesn't commit the transaction on its own
  92. *
  93. * @returns {this}
  94. */
  95. save(opts = {}) {
  96. const entityName = this.constructor.entityName;
  97. const primaryKeyName = this.constructor.primaryKeyName;
  98. const isNewEntity = !this[primaryKeyName];
  99. this.beforeSaving(opts);
  100. const pojo = this.getPojoToSave();
  101. sql.transactional(() => {
  102. sql.upsert(entityName, primaryKeyName, pojo);
  103. if (entityName === 'recent_notes') {
  104. return;
  105. }
  106. this.putEntityChange(!!this.isDeleted);
  107. if (!cls.isEntityEventsDisabled()) {
  108. const eventPayload = {
  109. entityName,
  110. entity: this
  111. };
  112. if (isNewEntity) {
  113. eventService.emit(eventService.ENTITY_CREATED, eventPayload);
  114. }
  115. eventService.emit(eventService.ENTITY_CHANGED, eventPayload);
  116. }
  117. });
  118. return this;
  119. }
  120. /** @protected */
  121. _setContent(content, opts = {}) {
  122. // client code asks to save entity even if blobId didn't change (something else was changed)
  123. opts.forceSave = !!opts.forceSave;
  124. opts.forceFrontendReload = !!opts.forceFrontendReload;
  125. if (content === null || content === undefined) {
  126. throw new Error(`Cannot set null content to ${this.constructor.primaryKeyName} '${this[this.constructor.primaryKeyName]}'`);
  127. }
  128. if (this.hasStringContent()) {
  129. content = content.toString();
  130. } else {
  131. content = Buffer.isBuffer(content) ? content : Buffer.from(content);
  132. }
  133. const unencryptedContentForHashCalculation = this.#getUnencryptedContentForHashCalculation(content);
  134. if (this.isProtected) {
  135. if (protectedSessionService.isProtectedSessionAvailable()) {
  136. content = protectedSessionService.encrypt(content);
  137. } else {
  138. throw new Error(`Cannot update content of blob since protected session is not available.`);
  139. }
  140. }
  141. sql.transactional(() => {
  142. const newBlobId = this.#saveBlob(content, unencryptedContentForHashCalculation, opts);
  143. const oldBlobId = this.blobId;
  144. if (newBlobId !== oldBlobId || opts.forceSave) {
  145. this.blobId = newBlobId;
  146. this.save();
  147. if (newBlobId !== oldBlobId) {
  148. this.#deleteBlobIfNotUsed(oldBlobId);
  149. }
  150. }
  151. });
  152. }
  153. #deleteBlobIfNotUsed(oldBlobId) {
  154. if (sql.getValue("SELECT 1 FROM notes WHERE blobId = ? LIMIT 1", [oldBlobId])) {
  155. return;
  156. }
  157. if (sql.getValue("SELECT 1 FROM attachments WHERE blobId = ? LIMIT 1", [oldBlobId])) {
  158. return;
  159. }
  160. if (sql.getValue("SELECT 1 FROM revisions WHERE blobId = ? LIMIT 1", [oldBlobId])) {
  161. return;
  162. }
  163. sql.execute("DELETE FROM blobs WHERE blobId = ?", [oldBlobId]);
  164. // blobs are not marked as erased in entity_changes, they are just purged completely
  165. // this is because technically every keystroke can create a new blob, and there would be just too many
  166. sql.execute("DELETE FROM entity_changes WHERE entityName = 'blobs' AND entityId = ?", [oldBlobId]);
  167. }
  168. #getUnencryptedContentForHashCalculation(unencryptedContent) {
  169. if (this.isProtected) {
  170. // a "random" prefix makes sure that the calculated hash/blobId is different for a decrypted/encrypted content
  171. const encryptedPrefixSuffix = "t$[nvQg7q)&amp;_ENCRYPTED_?M:Bf&amp;j3jr_";
  172. return Buffer.isBuffer(unencryptedContent)
  173. ? Buffer.concat([Buffer.from(encryptedPrefixSuffix), unencryptedContent])
  174. : `${encryptedPrefixSuffix}${unencryptedContent}`;
  175. } else {
  176. return unencryptedContent;
  177. }
  178. }
  179. #saveBlob(content, unencryptedContentForHashCalculation, opts = {}) {
  180. /*
  181. * We're using the unencrypted blob for the hash calculation, because otherwise the random IV would
  182. * cause every content blob to be unique which would balloon the database size (esp. with revisioning).
  183. * This has minor security implications (it's easy to infer that given content is shared between different
  184. * notes/attachments), but the trade-off comes out clearly positive.
  185. */
  186. const newBlobId = utils.hashedBlobId(unencryptedContentForHashCalculation);
  187. const blobNeedsInsert = !sql.getValue('SELECT 1 FROM blobs WHERE blobId = ?', [newBlobId]);
  188. if (!blobNeedsInsert) {
  189. return newBlobId;
  190. }
  191. const pojo = {
  192. blobId: newBlobId,
  193. content: content,
  194. dateModified: dateUtils.localNowDateTime(),
  195. utcDateModified: dateUtils.utcNowDateTime()
  196. };
  197. sql.upsert("blobs", "blobId", pojo);
  198. // we can't reuse blobId as an entity_changes hash, because this one has to be calculatable without having
  199. // access to the decrypted content
  200. const hash = blobService.calculateContentHash(pojo);
  201. entityChangesService.putEntityChange({
  202. entityName: 'blobs',
  203. entityId: newBlobId,
  204. hash: hash,
  205. isErased: false,
  206. utcDateChanged: pojo.utcDateModified,
  207. isSynced: true,
  208. // overriding componentId will cause the frontend to think the change is coming from a different component
  209. // and thus reload
  210. componentId: opts.forceFrontendReload ? utils.randomString(10) : null
  211. });
  212. eventService.emit(eventService.ENTITY_CHANGED, {
  213. entityName: 'blobs',
  214. entity: this
  215. });
  216. return newBlobId;
  217. }
  218. /**
  219. * @protected
  220. * @returns {string|Buffer}
  221. */
  222. _getContent() {
  223. const row = sql.getRow(`SELECT content FROM blobs WHERE blobId = ?`, [this.blobId]);
  224. if (!row) {
  225. throw new Error(`Cannot find content for ${this.constructor.primaryKeyName} '${this[this.constructor.primaryKeyName]}', blobId '${this.blobId}'`);
  226. }
  227. return blobService.processContent(row.content, this.isProtected, this.hasStringContent());
  228. }
  229. /**
  230. * Mark the entity as (soft) deleted. It will be completely erased later.
  231. *
  232. * This is a low-level method, for notes and branches use `note.deleteNote()` and 'branch.deleteBranch()` instead.
  233. *
  234. * @param [deleteId=null]
  235. */
  236. markAsDeleted(deleteId = null) {
  237. const entityId = this[this.constructor.primaryKeyName];
  238. const entityName = this.constructor.entityName;
  239. this.utcDateModified = dateUtils.utcNowDateTime();
  240. sql.execute(`UPDATE ${entityName} SET isDeleted = 1, deleteId = ?, utcDateModified = ?
  241. WHERE ${this.constructor.primaryKeyName} = ?`,
  242. [deleteId, this.utcDateModified, entityId]);
  243. if (this.dateModified) {
  244. this.dateModified = dateUtils.localNowDateTime();
  245. sql.execute(`UPDATE ${entityName} SET dateModified = ? WHERE ${this.constructor.primaryKeyName} = ?`,
  246. [this.dateModified, entityId]);
  247. }
  248. log.info(`Marking ${entityName} ${entityId} as deleted`);
  249. this.putEntityChange(true);
  250. eventService.emit(eventService.ENTITY_DELETED, { entityName, entityId, entity: this });
  251. }
  252. markAsDeletedSimple() {
  253. const entityId = this[this.constructor.primaryKeyName];
  254. const entityName = this.constructor.entityName;
  255. this.utcDateModified = dateUtils.utcNowDateTime();
  256. sql.execute(`UPDATE ${entityName} SET isDeleted = 1, utcDateModified = ?
  257. WHERE ${this.constructor.primaryKeyName} = ?`,
  258. [this.utcDateModified, entityId]);
  259. log.info(`Marking ${entityName} ${entityId} as deleted`);
  260. this.putEntityChange(true);
  261. eventService.emit(eventService.ENTITY_DELETED, { entityName, entityId, entity: this });
  262. }
  263. }
  264. module.exports = AbstractBeccaEntity;
  265. </code></pre>
  266. </article>
  267. </section>
  268. </div>
  269. <nav>
  270. <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="AbstractBeccaEntity.html">AbstractBeccaEntity</a></li><li><a href="BAttachment.html">BAttachment</a></li><li><a href="BAttribute.html">BAttribute</a></li><li><a href="BBranch.html">BBranch</a></li><li><a href="BEtapiToken.html">BEtapiToken</a></li><li><a href="BNote.html">BNote</a></li><li><a href="BOption.html">BOption</a></li><li><a href="BRecentNote.html">BRecentNote</a></li><li><a href="BRevision.html">BRevision</a></li><li><a href="BackendScriptApi.html">BackendScriptApi</a></li></ul><h3>Global</h3><ul><li><a href="global.html#api">api</a></li></ul>
  271. </nav>
  272. <br class="clear">
  273. <footer>
  274. Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 4.0.2</a>
  275. </footer>
  276. <script> prettyPrint(); </script>
  277. <script src="scripts/linenumber.js"> </script>
  278. </body>
  279. </html>