mirror of
				https://github.com/zadam/trilium.git
				synced 2025-10-31 10:26:08 +01:00 
			
		
		
		
	Compare commits
	
		
			99 Commits
		
	
	
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
|  | f43f0e10a1 | ||
|  | 6d842a65a2 | ||
|  | 50c4de021c | ||
|  | 936d8449f6 | ||
|  | 462bc0edd5 | ||
|  | 35ef3c8470 | ||
|  | 5117d43e29 | ||
|  | 7c9ac488e8 | ||
|  | fec1574447 | ||
|  | f7587de452 | ||
|  | 41a6e777ea | ||
|  | 8fb0de900b | ||
|  | a40bf71fd4 | ||
|  | 2a53bb03ae | ||
|  | a684879b91 | ||
|  | ddbd4f73c8 | ||
|  | b0ed790edf | ||
|  | 3424406ff1 | ||
|  | ce5c385c15 | ||
|  | cd9eef32b0 | ||
|  | 12d82e3b33 | ||
|  | f071d3f651 | ||
|  | 297b536ebc | ||
|  | 7cca2d9247 | ||
|  | 36dc802d16 | ||
|  | c78ddb70cb | ||
|  | 9fb0599c45 | ||
|  | 13f524fb39 | ||
|  | 27be3b4c90 | ||
|  | af4ea66742 | ||
|  | 0f42c396f3 | ||
|  | 9e96272eb3 | ||
|  | 965dbcbc9a | ||
|  | 7ac109e7f7 | ||
|  | ac25770c0e | ||
|  | 5b15424498 | ||
|  | f1240c26bf | ||
|  | 1c0fd243d1 | ||
|  | 3491235533 | ||
|  | 5f36856571 | ||
|  | d3e44b37e9 | ||
|  | 90e9297ec5 | ||
|  | c568ef2f8a | ||
|  | fcf6141cde | ||
|  | 21551d7b77 | ||
|  | 12031d369f | ||
|  | b44c523845 | ||
|  | 49989695ff | ||
|  | a55d3530e9 | ||
|  | 2aab3ad281 | ||
|  | 194ce4f10f | ||
|  | 2089c32839 | ||
|  | f437be7af0 | ||
|  | 96dc56098d | ||
|  | 61987e46f7 | ||
|  | 509093b755 | ||
|  | 097114c0f2 | ||
|  | 040f9185f8 | ||
|  | 6dc934abbe | ||
|  | 2d24bf81dd | ||
|  | 9452fc236b | ||
|  | 365c37604b | ||
|  | 01c7e58d47 | ||
|  | d3d49923b1 | ||
|  | 263ac299d0 | ||
|  | 3d185a5178 | ||
|  | 2ff7a890bc | ||
|  | 2eb1a9705f | ||
|  | ed1381103a | ||
|  | 170d317589 | ||
|  | ededc063df | ||
|  | 986eace1be | ||
|  | 29086d8dfe | ||
|  | 9b3f3fde05 | ||
|  | 6a50afd952 | ||
|  | 697eee2706 | ||
|  | 8a95afd756 | ||
|  | 4d6eda8fe6 | ||
|  | e4f459fa2b | ||
|  | f578e001b0 | ||
|  | 2a08aef885 | ||
|  | 7564bf388c | ||
|  | 7e4d70259f | ||
|  | 5b98c1c0f3 | ||
|  | 02dc7b199b | ||
|  | d39cdbfada | ||
|  | 50bb4a47ee | ||
|  | a4627f2ddb | ||
|  | c8253caae9 | ||
|  | 0ece9bd1be | ||
|  | b6935abcc9 | ||
|  | 37ab7b4641 | ||
|  | 013714cb5c | ||
|  | 1fe7c62f5a | ||
|  | a06618d851 | ||
|  | e7460ca3a9 | ||
|  | 073300bbcd | ||
|  | a201661ce5 | ||
|  | 6235a3c886 | 
| @@ -1,6 +1,6 @@ | ||||
| <?xml version="1.0" encoding="UTF-8"?> | ||||
| <dataSource name="document.db"> | ||||
|   <database-model serializer="dbm" rdbms="SQLITE" format-version="4.9"> | ||||
|   <database-model serializer="dbm" rdbms="SQLITE" format-version="4.11"> | ||||
|     <root id="1"> | ||||
|       <ServerVersion>3.16.1</ServerVersion> | ||||
|     </root> | ||||
| @@ -12,10 +12,10 @@ | ||||
|     <collation id="4" parent="1" name="NOCASE"/> | ||||
|     <collation id="5" parent="1" name="RTRIM"/> | ||||
|     <table id="6" parent="2" name="api_tokens"/> | ||||
|     <table id="7" parent="2" name="branches"/> | ||||
|     <table id="8" parent="2" name="event_log"/> | ||||
|     <table id="9" parent="2" name="images"/> | ||||
|     <table id="10" parent="2" name="labels"/> | ||||
|     <table id="7" parent="2" name="attributes"/> | ||||
|     <table id="8" parent="2" name="branches"/> | ||||
|     <table id="9" parent="2" name="event_log"/> | ||||
|     <table id="10" parent="2" name="images"/> | ||||
|     <table id="11" parent="2" name="note_images"/> | ||||
|     <table id="12" parent="2" name="note_revisions"/> | ||||
|     <table id="13" parent="2" name="notes"/> | ||||
| @@ -59,7 +59,6 @@ | ||||
|     <index id="25" parent="6" name="sqlite_autoindex_api_tokens_1"> | ||||
|       <NameSurrogate>1</NameSurrogate> | ||||
|       <ColNames>apiTokenId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|       <Unique>1</Unique> | ||||
|     </index> | ||||
|     <key id="26" parent="6"> | ||||
| @@ -67,7 +66,7 @@ | ||||
|       <Primary>1</Primary> | ||||
|       <UnderlyingIndexName>sqlite_autoindex_api_tokens_1</UnderlyingIndexName> | ||||
|     </key> | ||||
|     <column id="27" parent="7" name="branchId"> | ||||
|     <column id="27" parent="7" name="attributeId"> | ||||
|       <Position>1</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
| @@ -77,225 +76,219 @@ | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="29" parent="7" name="parentNoteId"> | ||||
|     <column id="29" parent="7" name="type"> | ||||
|       <Position>3</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="30" parent="7" name="notePosition"> | ||||
|     <column id="30" parent="7" name="name"> | ||||
|       <Position>4</Position> | ||||
|       <DataType>INTEGER|0s</DataType> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="31" parent="7" name="prefix"> | ||||
|     <column id="31" parent="7" name="value"> | ||||
|       <Position>5</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|       <DefaultExpression>''</DefaultExpression> | ||||
|     </column> | ||||
|     <column id="32" parent="7" name="isExpanded"> | ||||
|     <column id="32" parent="7" name="position"> | ||||
|       <Position>6</Position> | ||||
|       <DataType>BOOLEAN|0s</DataType> | ||||
|     </column> | ||||
|     <column id="33" parent="7" name="isDeleted"> | ||||
|       <Position>7</Position> | ||||
|       <DataType>INTEGER|0s</DataType> | ||||
|       <DataType>INT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|       <DefaultExpression>0</DefaultExpression> | ||||
|     </column> | ||||
|     <column id="33" parent="7" name="dateCreated"> | ||||
|       <Position>7</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="34" parent="7" name="dateModified"> | ||||
|       <Position>8</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="35" parent="7" name="hash"> | ||||
|     <column id="35" parent="7" name="isDeleted"> | ||||
|       <Position>9</Position> | ||||
|       <DataType>INT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="36" parent="7" name="hash"> | ||||
|       <Position>10</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|       <DefaultExpression>""</DefaultExpression> | ||||
|     </column> | ||||
|     <column id="37" parent="7" name="isInheritable"> | ||||
|       <Position>11</Position> | ||||
|       <DataType>int|0s</DataType> | ||||
|       <DefaultExpression>0</DefaultExpression> | ||||
|     </column> | ||||
|     <index id="38" parent="7" name="sqlite_autoindex_attributes_1"> | ||||
|       <NameSurrogate>1</NameSurrogate> | ||||
|       <ColNames>attributeId</ColNames> | ||||
|       <Unique>1</Unique> | ||||
|     </index> | ||||
|     <key id="39" parent="7"> | ||||
|       <ColNames>attributeId</ColNames> | ||||
|       <Primary>1</Primary> | ||||
|       <UnderlyingIndexName>sqlite_autoindex_attributes_1</UnderlyingIndexName> | ||||
|     </key> | ||||
|     <column id="40" parent="8" name="branchId"> | ||||
|       <Position>1</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="41" parent="8" name="noteId"> | ||||
|       <Position>2</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="42" parent="8" name="parentNoteId"> | ||||
|       <Position>3</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="43" parent="8" name="notePosition"> | ||||
|       <Position>4</Position> | ||||
|       <DataType>INTEGER|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="44" parent="8" name="prefix"> | ||||
|       <Position>5</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|     </column> | ||||
|     <column id="45" parent="8" name="isExpanded"> | ||||
|       <Position>6</Position> | ||||
|       <DataType>BOOLEAN|0s</DataType> | ||||
|     </column> | ||||
|     <column id="46" parent="8" name="isDeleted"> | ||||
|       <Position>7</Position> | ||||
|       <DataType>INTEGER|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|       <DefaultExpression>0</DefaultExpression> | ||||
|     </column> | ||||
|     <column id="47" parent="8" name="dateModified"> | ||||
|       <Position>8</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="48" parent="8" name="hash"> | ||||
|       <Position>9</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|       <DefaultExpression>""</DefaultExpression> | ||||
|     </column> | ||||
|     <column id="36" parent="7" name="dateCreated"> | ||||
|     <column id="49" parent="8" name="dateCreated"> | ||||
|       <Position>10</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|       <DefaultExpression>'1970-01-01T00:00:00.000Z'</DefaultExpression> | ||||
|     </column> | ||||
|     <index id="37" parent="7" name="sqlite_autoindex_branches_1"> | ||||
|     <index id="50" parent="8" name="sqlite_autoindex_branches_1"> | ||||
|       <NameSurrogate>1</NameSurrogate> | ||||
|       <ColNames>branchId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|       <Unique>1</Unique> | ||||
|     </index> | ||||
|     <index id="38" parent="7" name="IDX_branches_noteId_parentNoteId"> | ||||
|     <index id="51" parent="8" name="IDX_branches_noteId_parentNoteId"> | ||||
|       <ColNames>noteId | ||||
| parentNoteId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|     </index> | ||||
|     <index id="39" parent="7" name="IDX_branches_noteId"> | ||||
|     <index id="52" parent="8" name="IDX_branches_noteId"> | ||||
|       <ColNames>noteId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|     </index> | ||||
|     <index id="40" parent="7" name="IDX_branches_parentNoteId"> | ||||
|     <index id="53" parent="8" name="IDX_branches_parentNoteId"> | ||||
|       <ColNames>parentNoteId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|     </index> | ||||
|     <key id="41" parent="7"> | ||||
|     <key id="54" parent="8"> | ||||
|       <ColNames>branchId</ColNames> | ||||
|       <Primary>1</Primary> | ||||
|       <UnderlyingIndexName>sqlite_autoindex_branches_1</UnderlyingIndexName> | ||||
|     </key> | ||||
|     <column id="42" parent="8" name="eventId"> | ||||
|     <column id="55" parent="9" name="eventId"> | ||||
|       <Position>1</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="43" parent="8" name="noteId"> | ||||
|     <column id="56" parent="9" name="noteId"> | ||||
|       <Position>2</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|     </column> | ||||
|     <column id="44" parent="8" name="comment"> | ||||
|     <column id="57" parent="9" name="comment"> | ||||
|       <Position>3</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|     </column> | ||||
|     <column id="45" parent="8" name="dateCreated"> | ||||
|     <column id="58" parent="9" name="dateCreated"> | ||||
|       <Position>4</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <index id="46" parent="8" name="sqlite_autoindex_event_log_1"> | ||||
|     <index id="59" parent="9" name="sqlite_autoindex_event_log_1"> | ||||
|       <NameSurrogate>1</NameSurrogate> | ||||
|       <ColNames>eventId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|       <Unique>1</Unique> | ||||
|     </index> | ||||
|     <key id="47" parent="8"> | ||||
|     <key id="60" parent="9"> | ||||
|       <ColNames>eventId</ColNames> | ||||
|       <Primary>1</Primary> | ||||
|       <UnderlyingIndexName>sqlite_autoindex_event_log_1</UnderlyingIndexName> | ||||
|     </key> | ||||
|     <column id="48" parent="9" name="imageId"> | ||||
|     <column id="61" parent="10" name="imageId"> | ||||
|       <Position>1</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="49" parent="9" name="format"> | ||||
|     <column id="62" parent="10" name="format"> | ||||
|       <Position>2</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="50" parent="9" name="checksum"> | ||||
|     <column id="63" parent="10" name="checksum"> | ||||
|       <Position>3</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="51" parent="9" name="name"> | ||||
|     <column id="64" parent="10" name="name"> | ||||
|       <Position>4</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="52" parent="9" name="data"> | ||||
|     <column id="65" parent="10" name="data"> | ||||
|       <Position>5</Position> | ||||
|       <DataType>BLOB|0s</DataType> | ||||
|     </column> | ||||
|     <column id="53" parent="9" name="isDeleted"> | ||||
|     <column id="66" parent="10" name="isDeleted"> | ||||
|       <Position>6</Position> | ||||
|       <DataType>INT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|       <DefaultExpression>0</DefaultExpression> | ||||
|     </column> | ||||
|     <column id="54" parent="9" name="dateModified"> | ||||
|     <column id="67" parent="10" name="dateModified"> | ||||
|       <Position>7</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="55" parent="9" name="dateCreated"> | ||||
|     <column id="68" parent="10" name="dateCreated"> | ||||
|       <Position>8</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="56" parent="9" name="hash"> | ||||
|     <column id="69" parent="10" name="hash"> | ||||
|       <Position>9</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|       <DefaultExpression>""</DefaultExpression> | ||||
|     </column> | ||||
|     <index id="57" parent="9" name="sqlite_autoindex_images_1"> | ||||
|     <index id="70" parent="10" name="sqlite_autoindex_images_1"> | ||||
|       <NameSurrogate>1</NameSurrogate> | ||||
|       <ColNames>imageId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|       <Unique>1</Unique> | ||||
|     </index> | ||||
|     <key id="58" parent="9"> | ||||
|     <key id="71" parent="10"> | ||||
|       <ColNames>imageId</ColNames> | ||||
|       <Primary>1</Primary> | ||||
|       <UnderlyingIndexName>sqlite_autoindex_images_1</UnderlyingIndexName> | ||||
|     </key> | ||||
|     <column id="59" parent="10" name="labelId"> | ||||
|       <Position>1</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="60" parent="10" name="noteId"> | ||||
|       <Position>2</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="61" parent="10" name="name"> | ||||
|       <Position>3</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="62" parent="10" name="value"> | ||||
|       <Position>4</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|       <DefaultExpression>''</DefaultExpression> | ||||
|     </column> | ||||
|     <column id="63" parent="10" name="position"> | ||||
|       <Position>5</Position> | ||||
|       <DataType>INT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|       <DefaultExpression>0</DefaultExpression> | ||||
|     </column> | ||||
|     <column id="64" parent="10" name="dateCreated"> | ||||
|       <Position>6</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="65" parent="10" name="dateModified"> | ||||
|       <Position>7</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="66" parent="10" name="isDeleted"> | ||||
|       <Position>8</Position> | ||||
|       <DataType>INT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="67" parent="10" name="hash"> | ||||
|       <Position>9</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|       <DefaultExpression>""</DefaultExpression> | ||||
|     </column> | ||||
|     <index id="68" parent="10" name="sqlite_autoindex_labels_1"> | ||||
|       <NameSurrogate>1</NameSurrogate> | ||||
|       <ColNames>labelId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|       <Unique>1</Unique> | ||||
|     </index> | ||||
|     <index id="69" parent="10" name="IDX_labels_noteId"> | ||||
|       <ColNames>noteId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|     </index> | ||||
|     <index id="70" parent="10" name="IDX_labels_name_value"> | ||||
|       <ColNames>name | ||||
| value</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|     </index> | ||||
|     <key id="71" parent="10"> | ||||
|       <ColNames>labelId</ColNames> | ||||
|       <Primary>1</Primary> | ||||
|       <UnderlyingIndexName>sqlite_autoindex_labels_1</UnderlyingIndexName> | ||||
|     </key> | ||||
|     <column id="72" parent="11" name="noteImageId"> | ||||
|       <Position>1</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
| @@ -336,21 +329,17 @@ value</ColNames> | ||||
|     <index id="79" parent="11" name="sqlite_autoindex_note_images_1"> | ||||
|       <NameSurrogate>1</NameSurrogate> | ||||
|       <ColNames>noteImageId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|       <Unique>1</Unique> | ||||
|     </index> | ||||
|     <index id="80" parent="11" name="IDX_note_images_noteId_imageId"> | ||||
|       <ColNames>noteId | ||||
| imageId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|     </index> | ||||
|     <index id="81" parent="11" name="IDX_note_images_noteId"> | ||||
|       <ColNames>noteId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|     </index> | ||||
|     <index id="82" parent="11" name="IDX_note_images_imageId"> | ||||
|       <ColNames>imageId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|     </index> | ||||
|     <key id="83" parent="11"> | ||||
|       <ColNames>noteImageId</ColNames> | ||||
| @@ -412,20 +401,16 @@ imageId</ColNames> | ||||
|     <index id="94" parent="12" name="sqlite_autoindex_note_revisions_1"> | ||||
|       <NameSurrogate>1</NameSurrogate> | ||||
|       <ColNames>noteRevisionId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|       <Unique>1</Unique> | ||||
|     </index> | ||||
|     <index id="95" parent="12" name="IDX_note_revisions_noteId"> | ||||
|       <ColNames>noteId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|     </index> | ||||
|     <index id="96" parent="12" name="IDX_note_revisions_dateModifiedFrom"> | ||||
|       <ColNames>dateModifiedFrom</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|     </index> | ||||
|     <index id="97" parent="12" name="IDX_note_revisions_dateModifiedTo"> | ||||
|       <ColNames>dateModifiedTo</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|     </index> | ||||
|     <key id="98" parent="12"> | ||||
|       <ColNames>noteRevisionId</ColNames> | ||||
| @@ -492,185 +477,173 @@ imageId</ColNames> | ||||
|     <index id="109" parent="13" name="sqlite_autoindex_notes_1"> | ||||
|       <NameSurrogate>1</NameSurrogate> | ||||
|       <ColNames>noteId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|       <Unique>1</Unique> | ||||
|     </index> | ||||
|     <index id="110" parent="13" name="IDX_notes_type"> | ||||
|       <ColNames>type</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|     </index> | ||||
|     <key id="111" parent="13"> | ||||
|       <ColNames>noteId</ColNames> | ||||
|       <Primary>1</Primary> | ||||
|       <UnderlyingIndexName>sqlite_autoindex_notes_1</UnderlyingIndexName> | ||||
|     </key> | ||||
|     <column id="112" parent="14" name="optionId"> | ||||
|     <column id="112" parent="14" name="name"> | ||||
|       <Position>1</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="113" parent="14" name="name"> | ||||
|     <column id="113" parent="14" name="value"> | ||||
|       <Position>2</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="114" parent="14" name="value"> | ||||
|     <column id="114" parent="14" name="dateModified"> | ||||
|       <Position>3</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|     </column> | ||||
|     <column id="115" parent="14" name="dateModified"> | ||||
|       <Position>4</Position> | ||||
|       <DataType>INT|0s</DataType> | ||||
|     </column> | ||||
|     <column id="116" parent="14" name="isSynced"> | ||||
|       <Position>5</Position> | ||||
|     <column id="115" parent="14" name="isSynced"> | ||||
|       <Position>4</Position> | ||||
|       <DataType>INTEGER|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|       <DefaultExpression>0</DefaultExpression> | ||||
|     </column> | ||||
|     <column id="117" parent="14" name="hash"> | ||||
|       <Position>6</Position> | ||||
|     <column id="116" parent="14" name="hash"> | ||||
|       <Position>5</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|       <DefaultExpression>""</DefaultExpression> | ||||
|     </column> | ||||
|     <column id="118" parent="14" name="dateCreated"> | ||||
|       <Position>7</Position> | ||||
|     <column id="117" parent="14" name="dateCreated"> | ||||
|       <Position>6</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|       <DefaultExpression>'1970-01-01T00:00:00.000Z'</DefaultExpression> | ||||
|     </column> | ||||
|     <index id="119" parent="14" name="sqlite_autoindex_options_1"> | ||||
|     <index id="118" parent="14" name="sqlite_autoindex_options_1"> | ||||
|       <NameSurrogate>1</NameSurrogate> | ||||
|       <ColNames>optionId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|       <ColNames>name</ColNames> | ||||
|       <Unique>1</Unique> | ||||
|     </index> | ||||
|     <key id="120" parent="14"> | ||||
|       <ColNames>optionId</ColNames> | ||||
|     <key id="119" parent="14"> | ||||
|       <ColNames>name</ColNames> | ||||
|       <Primary>1</Primary> | ||||
|       <UnderlyingIndexName>sqlite_autoindex_options_1</UnderlyingIndexName> | ||||
|     </key> | ||||
|     <column id="121" parent="15" name="branchId"> | ||||
|     <column id="120" parent="15" name="branchId"> | ||||
|       <Position>1</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="122" parent="15" name="notePath"> | ||||
|     <column id="121" parent="15" name="notePath"> | ||||
|       <Position>2</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="123" parent="15" name="hash"> | ||||
|     <column id="122" parent="15" name="hash"> | ||||
|       <Position>3</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|       <DefaultExpression>""</DefaultExpression> | ||||
|     </column> | ||||
|     <column id="124" parent="15" name="dateCreated"> | ||||
|     <column id="123" parent="15" name="dateCreated"> | ||||
|       <Position>4</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="125" parent="15" name="isDeleted"> | ||||
|     <column id="124" parent="15" name="isDeleted"> | ||||
|       <Position>5</Position> | ||||
|       <DataType>INT|0s</DataType> | ||||
|     </column> | ||||
|     <index id="126" parent="15" name="sqlite_autoindex_recent_notes_1"> | ||||
|     <index id="125" parent="15" name="sqlite_autoindex_recent_notes_1"> | ||||
|       <NameSurrogate>1</NameSurrogate> | ||||
|       <ColNames>branchId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|       <Unique>1</Unique> | ||||
|     </index> | ||||
|     <key id="127" parent="15"> | ||||
|     <key id="126" parent="15"> | ||||
|       <ColNames>branchId</ColNames> | ||||
|       <Primary>1</Primary> | ||||
|       <UnderlyingIndexName>sqlite_autoindex_recent_notes_1</UnderlyingIndexName> | ||||
|     </key> | ||||
|     <column id="128" parent="16" name="sourceId"> | ||||
|     <column id="127" parent="16" name="sourceId"> | ||||
|       <Position>1</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="129" parent="16" name="dateCreated"> | ||||
|     <column id="128" parent="16" name="dateCreated"> | ||||
|       <Position>2</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <index id="130" parent="16" name="sqlite_autoindex_source_ids_1"> | ||||
|     <index id="129" parent="16" name="sqlite_autoindex_source_ids_1"> | ||||
|       <NameSurrogate>1</NameSurrogate> | ||||
|       <ColNames>sourceId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|       <Unique>1</Unique> | ||||
|     </index> | ||||
|     <key id="131" parent="16"> | ||||
|     <key id="130" parent="16"> | ||||
|       <ColNames>sourceId</ColNames> | ||||
|       <Primary>1</Primary> | ||||
|       <UnderlyingIndexName>sqlite_autoindex_source_ids_1</UnderlyingIndexName> | ||||
|     </key> | ||||
|     <column id="132" parent="17" name="type"> | ||||
|     <column id="131" parent="17" name="type"> | ||||
|       <Position>1</Position> | ||||
|       <DataType>text|0s</DataType> | ||||
|     </column> | ||||
|     <column id="133" parent="17" name="name"> | ||||
|     <column id="132" parent="17" name="name"> | ||||
|       <Position>2</Position> | ||||
|       <DataType>text|0s</DataType> | ||||
|     </column> | ||||
|     <column id="134" parent="17" name="tbl_name"> | ||||
|     <column id="133" parent="17" name="tbl_name"> | ||||
|       <Position>3</Position> | ||||
|       <DataType>text|0s</DataType> | ||||
|     </column> | ||||
|     <column id="135" parent="17" name="rootpage"> | ||||
|     <column id="134" parent="17" name="rootpage"> | ||||
|       <Position>4</Position> | ||||
|       <DataType>integer|0s</DataType> | ||||
|     </column> | ||||
|     <column id="136" parent="17" name="sql"> | ||||
|     <column id="135" parent="17" name="sql"> | ||||
|       <Position>5</Position> | ||||
|       <DataType>text|0s</DataType> | ||||
|     </column> | ||||
|     <column id="137" parent="18" name="name"> | ||||
|     <column id="136" parent="18" name="name"> | ||||
|       <Position>1</Position> | ||||
|     </column> | ||||
|     <column id="138" parent="18" name="seq"> | ||||
|     <column id="137" parent="18" name="seq"> | ||||
|       <Position>2</Position> | ||||
|     </column> | ||||
|     <column id="139" parent="19" name="id"> | ||||
|     <column id="138" parent="19" name="id"> | ||||
|       <Position>1</Position> | ||||
|       <DataType>INTEGER|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|       <SequenceIdentity>1</SequenceIdentity> | ||||
|     </column> | ||||
|     <column id="140" parent="19" name="entityName"> | ||||
|     <column id="139" parent="19" name="entityName"> | ||||
|       <Position>2</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="141" parent="19" name="entityId"> | ||||
|     <column id="140" parent="19" name="entityId"> | ||||
|       <Position>3</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="142" parent="19" name="sourceId"> | ||||
|     <column id="141" parent="19" name="sourceId"> | ||||
|       <Position>4</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <column id="143" parent="19" name="syncDate"> | ||||
|     <column id="142" parent="19" name="syncDate"> | ||||
|       <Position>5</Position> | ||||
|       <DataType>TEXT|0s</DataType> | ||||
|       <NotNull>1</NotNull> | ||||
|     </column> | ||||
|     <index id="144" parent="19" name="IDX_sync_entityName_entityId"> | ||||
|     <index id="143" parent="19" name="IDX_sync_entityName_entityId"> | ||||
|       <ColNames>entityName | ||||
| entityId</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|       <Unique>1</Unique> | ||||
|     </index> | ||||
|     <index id="145" parent="19" name="IDX_sync_syncDate"> | ||||
|     <index id="144" parent="19" name="IDX_sync_syncDate"> | ||||
|       <ColNames>syncDate</ColNames> | ||||
|       <ColumnCollations></ColumnCollations> | ||||
|     </index> | ||||
|     <key id="146" parent="19"> | ||||
|     <key id="145" parent="19"> | ||||
|       <ColNames>id</ColNames> | ||||
|       <Primary>1</Primary> | ||||
|     </key> | ||||
|   | ||||
							
								
								
									
										6
									
								
								.idea/sqldialects.xml
									
									
									
										generated
									
									
									
										Normal file
									
								
							
							
						
						
									
										6
									
								
								.idea/sqldialects.xml
									
									
									
										generated
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,6 @@ | ||||
| <?xml version="1.0" encoding="UTF-8"?> | ||||
| <project version="4"> | ||||
|   <component name="SqlDialectMappings"> | ||||
|     <file url="PROJECT" dialect="SQLite" /> | ||||
|   </component> | ||||
| </project> | ||||
							
								
								
									
										23
									
								
								bin/build-pkg.sh
									
									
									
									
									
										Executable file
									
								
							
							
						
						
									
										23
									
								
								bin/build-pkg.sh
									
									
									
									
									
										Executable file
									
								
							| @@ -0,0 +1,23 @@ | ||||
| #!/usr/bin/env bash | ||||
|  | ||||
| if [[ $# -eq 0 ]] ; then | ||||
|     echo "Missing argument of new version" | ||||
|     exit 1 | ||||
| fi | ||||
|  | ||||
| VERSION=$1 | ||||
|  | ||||
| PKG_DIR=dist/trilium-linux-x64-server | ||||
|  | ||||
| mkdir $PKG_DIR | ||||
|  | ||||
| pkg . --targets node8-linux-x64 --output ${PKG_DIR}/trilium | ||||
|  | ||||
| chmod +x ${PKG_DIR}/trilium | ||||
|  | ||||
| cp node_modules/sqlite3/lib/binding/node-v57-linux-x64/node_sqlite3.node ${PKG_DIR}/ | ||||
| cp node_modules/scrypt/build/Release/scrypt.node ${PKG_DIR}/ | ||||
|  | ||||
| cd dist | ||||
|  | ||||
| 7z a trilium-linux-x64-${VERSION}-server.7z trilium-linux-x64-server | ||||
							
								
								
									
										0
									
								
								bin/push-docker-image.sh
									
									
									
									
									
										
										
										Normal file → Executable file
									
								
							
							
						
						
									
										0
									
								
								bin/push-docker-image.sh
									
									
									
									
									
										
										
										Normal file → Executable file
									
								
							| @@ -47,7 +47,7 @@ bin/package.sh | ||||
| LINUX_X64_BUILD=trilium-linux-x64-$VERSION.7z | ||||
| LINUX_IA32_BUILD=trilium-linux-ia32-$VERSION.7z | ||||
| WINDOWS_X64_BUILD=trilium-windows-x64-$VERSION.7z | ||||
| SERVER_BUILD=trilium-linux-x64-server.elf | ||||
| SERVER_BUILD=trilium-linux-x64-server.7z | ||||
|  | ||||
| echo "Creating release in GitHub" | ||||
|  | ||||
| @@ -78,7 +78,7 @@ github-release upload \ | ||||
|  | ||||
| echo "Packaging server version" | ||||
|  | ||||
| npm run build-pkg | ||||
| bin/build-pkg.sh $VERSION | ||||
|  | ||||
| github-release upload \ | ||||
|     --tag $TAG \ | ||||
|   | ||||
| @@ -3,15 +3,10 @@ | ||||
| instanceName= | ||||
|  | ||||
| [Network] | ||||
| # port setting is relevant only for web deployments, desktop builds run on random free port | ||||
| port=8080 | ||||
| # true for TLS/SSL/HTTPS (secure), false for HTTP (unsecure). | ||||
| https=false | ||||
| # path to certificate (run "bash generate-cert.sh" to generate self-signed certificate). Relevant only if https=true | ||||
| certPath= | ||||
| keyPath= | ||||
|  | ||||
| [Sync] | ||||
| syncServerHost= | ||||
| syncServerTimeout=10000 | ||||
| syncProxy= | ||||
| syncServerCertificate= | ||||
							
								
								
									
										8
									
								
								db/migrations/0101__add_sync_options.sql
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										8
									
								
								db/migrations/0101__add_sync_options.sql
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,8 @@ | ||||
| INSERT INTO options (name, value, dateCreated, dateModified, isSynced) | ||||
| VALUES ('syncServerHost', '', '2018-06-01T03:35:55.041Z', '2018-06-01T03:35:55.041Z', 0); | ||||
|  | ||||
| INSERT INTO options (name, value, dateCreated, dateModified, isSynced) | ||||
| VALUES ('syncServerTimeout', '5000', '2018-06-01T03:35:55.041Z', '2018-06-01T03:35:55.041Z', 0); | ||||
|  | ||||
| INSERT INTO options (name, value, dateCreated, dateModified, isSynced) | ||||
| VALUES ('syncProxy', '', '2018-06-01T03:35:55.041Z', '2018-06-01T03:35:55.041Z', 0); | ||||
							
								
								
									
										2
									
								
								db/migrations/0102__fix_sync_entityIds.sql
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										2
									
								
								db/migrations/0102__fix_sync_entityIds.sql
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,2 @@ | ||||
| DELETE FROM sync WHERE entityName = 'note_tree'; | ||||
| DELETE FROM sync WHERE entityName = 'attributes'; | ||||
							
								
								
									
										2
									
								
								db/migrations/0103__add_initialized_option.sql
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										2
									
								
								db/migrations/0103__add_initialized_option.sql
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,2 @@ | ||||
| INSERT INTO options (name, value, dateCreated, dateModified, isSynced) | ||||
| VALUES ('initialized', 'true', '2018-06-01T03:35:55.041Z', '2018-06-01T03:35:55.041Z', 0); | ||||
							
								
								
									
										4
									
								
								db/migrations/0104__fill_sync_rows_for_options.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										4
									
								
								db/migrations/0104__fill_sync_rows_for_options.js
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,4 @@ | ||||
| const syncTableService = require('../../src/services/sync_table'); | ||||
|  | ||||
| // options has not been filled so far which caused problems with clean-slate sync. | ||||
| module.exports = async () => await syncTableService.fillAllSyncRows(); | ||||
| @@ -0,0 +1,2 @@ | ||||
| UPDATE notes SET content = '' WHERE isDeleted = 1; | ||||
| UPDATE note_revisions SET content = '' WHERE (SELECT isDeleted FROM notes WHERE noteId = note_revisions.noteId) = 1; | ||||
							
								
								
									
										15
									
								
								db/migrations/0106__add_relations_table.sql
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										15
									
								
								db/migrations/0106__add_relations_table.sql
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,15 @@ | ||||
| CREATE TABLE relations | ||||
| ( | ||||
|     relationId  TEXT not null primary key, | ||||
|     sourceNoteId       TEXT not null, | ||||
|     name         TEXT not null, | ||||
|     targetNoteId        TEXT not null, | ||||
|     position     INT  default 0 not null, | ||||
|     dateCreated  TEXT not null, | ||||
|     dateModified TEXT not null, | ||||
|     isDeleted    INT  not null | ||||
|   , hash TEXT DEFAULT "" NOT NULL); | ||||
| CREATE INDEX IDX_relation_sourceNoteId | ||||
|   on relations (sourceNoteId); | ||||
| CREATE INDEX IDX_relation_targetNoteId | ||||
|   on relations (targetNoteId); | ||||
| @@ -0,0 +1 @@ | ||||
| ALTER TABLE relations ADD isInheritable int DEFAULT 0 NULL; | ||||
							
								
								
									
										9
									
								
								db/migrations/0108__new_backup_options.sql
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										9
									
								
								db/migrations/0108__new_backup_options.sql
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,9 @@ | ||||
| UPDATE options SET name = 'lastDailyBackupDate' WHERE name = 'lastBackupDate'; | ||||
|  | ||||
| INSERT INTO options (name, value, dateCreated, dateModified, isSynced) | ||||
| VALUES ('lastWeeklyBackupDate', '2018-07-29T18:31:00.874Z', '2018-07-29T18:31:00.874Z', '2018-07-29T18:31:00.874Z', 0); | ||||
|  | ||||
| INSERT INTO options (name, value, dateCreated, dateModified, isSynced) | ||||
| VALUES ('lastMonthlyBackupDate', '2018-07-29T18:31:00.874Z', '2018-07-29T18:31:00.874Z', '2018-07-29T18:31:00.874Z', 0); | ||||
|  | ||||
| -- these options are not synced so no need to fix sync rows | ||||
							
								
								
									
										27
									
								
								db/migrations/0109__create_attributes.sql
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										27
									
								
								db/migrations/0109__create_attributes.sql
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,27 @@ | ||||
| create table attributes | ||||
| ( | ||||
|   attributeId      TEXT not null primary key, | ||||
|   noteId       TEXT not null, | ||||
|   type         TEXT not null, | ||||
|   name         TEXT not null, | ||||
|   value        TEXT default '' not null, | ||||
|   position     INT  default 0 not null, | ||||
|   dateCreated  TEXT not null, | ||||
|   dateModified TEXT not null, | ||||
|   isDeleted    INT  not null, | ||||
|   hash         TEXT default "" not null); | ||||
|  | ||||
| create index IDX_attributes_name_value | ||||
|   on attributes (name, value); | ||||
|  | ||||
| create index IDX_attributes_value | ||||
|   on attributes (value); | ||||
|  | ||||
| create index IDX_attributes_noteId | ||||
|   on attributes (noteId); | ||||
|  | ||||
| INSERT INTO attributes (attributeId, noteId, type, name, value, position, dateCreated, dateModified, isDeleted, hash) | ||||
| SELECT labelId, noteId, 'label', name, value, position, dateCreated, dateModified, isDeleted, hash FROM labels; | ||||
|  | ||||
| INSERT INTO attributes (attributeId, noteId, type, name, value, position, dateCreated, dateModified, isDeleted, hash) | ||||
| SELECT relationId, sourceNoteId, 'relation', name, targetNoteId, position, dateCreated, dateModified, isDeleted, hash FROM relations; | ||||
							
								
								
									
										1
									
								
								db/migrations/0110__add_isInheritable_to_attributes.sql
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										1
									
								
								db/migrations/0110__add_isInheritable_to_attributes.sql
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1 @@ | ||||
| ALTER TABLE attributes ADD isInheritable int DEFAULT 0 NULL; | ||||
							
								
								
									
										4
									
								
								db/migrations/0111__cleanup_labels_and_relations.sql
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										4
									
								
								db/migrations/0111__cleanup_labels_and_relations.sql
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,4 @@ | ||||
| DROP TABLE relations; | ||||
| DROP TABLE labels; | ||||
|  | ||||
| DELETE FROM sync WHERE entityName = 'relations' OR entityName = 'labels'; | ||||
| @@ -82,21 +82,6 @@ CREATE INDEX `IDX_branches_noteId_parentNoteId` ON `branches` ( | ||||
|   `noteId`, | ||||
|   `parentNoteId` | ||||
| ); | ||||
| CREATE TABLE labels | ||||
| ( | ||||
|   labelId  TEXT not null primary key, | ||||
|   noteId       TEXT not null, | ||||
|   name         TEXT not null, | ||||
|   value        TEXT default '' not null, | ||||
|   position     INT  default 0 not null, | ||||
|   dateCreated  TEXT not null, | ||||
|   dateModified TEXT not null, | ||||
|   isDeleted    INT  not null | ||||
| , hash TEXT DEFAULT "" NOT NULL); | ||||
| CREATE INDEX IDX_labels_name_value | ||||
|   on labels (name, value); | ||||
| CREATE INDEX IDX_labels_noteId | ||||
|   on labels (noteId); | ||||
| CREATE TABLE IF NOT EXISTS "notes" ( | ||||
|   `noteId`	TEXT NOT NULL, | ||||
|   `title`	TEXT NOT NULL DEFAULT "unnamed", | ||||
| @@ -134,3 +119,15 @@ CREATE TABLE IF NOT EXISTS "options" | ||||
|   hash TEXT default "" not null, | ||||
|   dateCreated TEXT default '1970-01-01T00:00:00.000Z' not null | ||||
| ); | ||||
| CREATE TABLE attributes | ||||
| ( | ||||
|   attributeId      TEXT not null primary key, | ||||
|   noteId       TEXT not null, | ||||
|   type         TEXT not null, | ||||
|   name         TEXT not null, | ||||
|   value        TEXT default '' not null, | ||||
|   position     INT  default 0 not null, | ||||
|   dateCreated  TEXT not null, | ||||
|   dateModified TEXT not null, | ||||
|   isDeleted    INT  not null, | ||||
|   hash         TEXT default "" not null, isInheritable int DEFAULT 0 NULL); | ||||
|   | ||||
| @@ -2,9 +2,9 @@ | ||||
|  | ||||
| const electron = require('electron'); | ||||
| const path = require('path'); | ||||
| const config = require('./src/services/config'); | ||||
| const log = require('./src/services/log'); | ||||
| const url = require("url"); | ||||
| const port = require('./src/services/port'); | ||||
|  | ||||
| const app = electron.app; | ||||
| const globalShortcut = electron.globalShortcut; | ||||
| @@ -23,7 +23,7 @@ function onClosed() { | ||||
|     mainWindow = null; | ||||
| } | ||||
|  | ||||
| function createMainWindow() { | ||||
| async function createMainWindow() { | ||||
|     const win = new electron.BrowserWindow({ | ||||
|         width: 1200, | ||||
|         height: 900, | ||||
| @@ -31,10 +31,8 @@ function createMainWindow() { | ||||
|         icon: path.join(__dirname, 'src/public/images/app-icons/png/256x256.png') | ||||
|     }); | ||||
|  | ||||
|     const port = config['Network']['port'] || '3000'; | ||||
|  | ||||
|     win.setMenu(null); | ||||
|     win.loadURL('http://localhost:' + port); | ||||
|     win.loadURL('http://localhost:' + await port); | ||||
|     win.on('closed', onClosed); | ||||
|  | ||||
|     win.webContents.on('new-window', (e, url) => { | ||||
|   | ||||
							
								
								
									
										29
									
								
								package.json
									
									
									
									
									
								
							
							
						
						
									
										29
									
								
								package.json
									
									
									
									
									
								
							| @@ -1,7 +1,7 @@ | ||||
| { | ||||
|   "name": "trilium", | ||||
|   "description": "Trilium Notes", | ||||
|   "version": "0.17.0", | ||||
|   "version": "0.19.1", | ||||
|   "license": "AGPL-3.0-only", | ||||
|   "main": "electron.js", | ||||
|   "bin": { | ||||
| @@ -20,8 +20,7 @@ | ||||
|     "start-forge": "electron-forge start", | ||||
|     "package-forge": "electron-forge package", | ||||
|     "make-forge": "electron-forge make", | ||||
|     "publish-forge": "electron-forge publish", | ||||
|     "build-pkg": "pkg . --targets node8-linux-x64 --output dist/trilium-linux-x64-server.elf" | ||||
|     "publish-forge": "electron-forge publish" | ||||
|   }, | ||||
|   "dependencies": { | ||||
|     "async-mutex": "^0.1.3", | ||||
| @@ -37,16 +36,17 @@ | ||||
|     "electron-in-page-search": "^1.3.2", | ||||
|     "express": "~4.16.3", | ||||
|     "express-session": "^1.15.6", | ||||
|     "fs-extra": "^6.0.1", | ||||
|     "helmet": "^3.12.1", | ||||
|     "fs-extra": "^7.0.0", | ||||
|     "get-port": "^4.0.0", | ||||
|     "helmet": "^3.13.0", | ||||
|     "html": "^1.0.0", | ||||
|     "image-type": "^3.0.0", | ||||
|     "imagemin": "^5.3.1", | ||||
|     "imagemin": "^6.0.0", | ||||
|     "imagemin-giflossy": "^5.1.10", | ||||
|     "imagemin-mozjpeg": "^7.0.0", | ||||
|     "imagemin-pngquant": "^5.1.0", | ||||
|     "imagemin-pngquant": "^6.0.0", | ||||
|     "ini": "^1.3.5", | ||||
|     "jimp": "^0.2.28", | ||||
|     "jimp": "^0.3.0", | ||||
|     "moment": "^2.22.2", | ||||
|     "multer": "^1.3.1", | ||||
|     "open": "0.0.5", | ||||
| @@ -63,15 +63,15 @@ | ||||
|     "sqlite": "^2.9.2", | ||||
|     "tar-stream": "^1.6.1", | ||||
|     "unescape": "^1.0.1", | ||||
|     "ws": "^5.2.1", | ||||
|     "ws": "^6.0.0", | ||||
|     "xml2js": "^0.4.19" | ||||
|   }, | ||||
|   "devDependencies": { | ||||
|     "electron": "^2.0.4", | ||||
|     "electron": "^2.0.6", | ||||
|     "electron-compile": "^6.4.3", | ||||
|     "electron-packager": "^12.1.0", | ||||
|     "electron-prebuilt-compile": "2.0.4", | ||||
|     "electron-rebuild": "^1.8.1", | ||||
|     "electron-prebuilt-compile": "2.0.6", | ||||
|     "electron-rebuild": "^1.8.2", | ||||
|     "lorem-ipsum": "^1.0.5", | ||||
|     "tape": "^4.9.1", | ||||
|     "xo": "^0.21.1", | ||||
| @@ -119,7 +119,10 @@ | ||||
|     "assets": [ | ||||
|       "./db/**/*", | ||||
|       "./src/public/**/*", | ||||
|       "./src/views/**/*" | ||||
|       "./src/views/**/*", | ||||
|       "./node_modules/mozjpeg/vendor/*", | ||||
|       "./node_modules/pngquant-bin/vendor/*", | ||||
|       "./node_modules/giflossy/vendor/*" | ||||
|     ] | ||||
|   } | ||||
| } | ||||
|   | ||||
| @@ -11,6 +11,7 @@ const os = require('os'); | ||||
| const sessionSecret = require('./services/session_secret'); | ||||
| const cls = require('./services/cls'); | ||||
| require('./entities/entity_constructor'); | ||||
| require('./services/handlers'); | ||||
|  | ||||
| const app = express(); | ||||
|  | ||||
| @@ -47,7 +48,7 @@ const sessionParser = session({ | ||||
|     cookie: { | ||||
|         //    path: "/", | ||||
|         httpOnly: true, | ||||
|         maxAge:  1800000 | ||||
|         maxAge:  24 * 60 * 60 * 1000 // in milliseconds | ||||
|     }, | ||||
|     store: new FileStore({ | ||||
|         ttl: 30 * 24 * 3600, | ||||
|   | ||||
| @@ -9,8 +9,6 @@ class ApiToken extends Entity { | ||||
|     static get hashedProperties() { return ["apiTokenId", "token", "dateCreated", "isDeleted"]; } | ||||
|  | ||||
|     beforeSaving() { | ||||
|         super.beforeSaving(); | ||||
|  | ||||
|         if (!this.isDeleted) { | ||||
|             this.isDeleted = false; | ||||
|         } | ||||
| @@ -18,6 +16,8 @@ class ApiToken extends Entity { | ||||
|         if (!this.dateCreated) { | ||||
|             this.dateCreated = dateUtils.nowDate(); | ||||
|         } | ||||
|  | ||||
|         super.beforeSaving(); | ||||
|     } | ||||
| } | ||||
|  | ||||
|   | ||||
							
								
								
									
										77
									
								
								src/entities/attribute.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										77
									
								
								src/entities/attribute.js
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,77 @@ | ||||
| "use strict"; | ||||
|  | ||||
| const Entity = require('./entity'); | ||||
| const repository = require('../services/repository'); | ||||
| const dateUtils = require('../services/date_utils'); | ||||
| const sql = require('../services/sql'); | ||||
|  | ||||
| class Attribute extends Entity { | ||||
|     static get tableName() { return "attributes"; } | ||||
|     static get primaryKeyName() { return "attributeId"; } | ||||
|     static get hashedProperties() { return ["attributeId", "noteId", "type", "name", "value", "isInheritable", "isDeleted", "dateCreated"]; } | ||||
|  | ||||
|     constructor(row) { | ||||
|         super(row); | ||||
|  | ||||
|         this.isInheritable = !!this.isInheritable; | ||||
|  | ||||
|         if (this.isDefinition()) { | ||||
|             try { | ||||
|                 this.value = JSON.parse(this.value); | ||||
|             } | ||||
|             catch (e) { | ||||
|             } | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     async getNote() { | ||||
|         return await repository.getEntity("SELECT * FROM notes WHERE noteId = ?", [this.noteId]); | ||||
|     } | ||||
|  | ||||
|     async getTargetNote() { | ||||
|         if (this.type !== 'relation') { | ||||
|             throw new Error(`Attribute ${this.attributeId} is not relation`); | ||||
|         } | ||||
|  | ||||
|         if (!this.value) { | ||||
|             return null; | ||||
|         } | ||||
|  | ||||
|         return await repository.getEntity("SELECT * FROM notes WHERE noteId = ?", [this.value]); | ||||
|     } | ||||
|  | ||||
|     isDefinition() { | ||||
|         return this.type === 'label-definition' || this.type === 'relation-definition'; | ||||
|     } | ||||
|  | ||||
|     async beforeSaving() { | ||||
|         if (!this.value) { | ||||
|             // null value isn't allowed | ||||
|             this.value = ""; | ||||
|         } | ||||
|  | ||||
|         if (this.position === undefined) { | ||||
|             this.position = 1 + await sql.getValue(`SELECT COALESCE(MAX(position), 0) FROM attributes WHERE noteId = ?`, [this.noteId]); | ||||
|         } | ||||
|  | ||||
|         if (!this.isInheritable) { | ||||
|             this.isInheritable = false; | ||||
|         } | ||||
|  | ||||
|         if (!this.isDeleted) { | ||||
|             this.isDeleted = false; | ||||
|         } | ||||
|  | ||||
|         if (!this.dateCreated) { | ||||
|             this.dateCreated = dateUtils.nowDate(); | ||||
|         } | ||||
|  | ||||
|         super.beforeSaving(); | ||||
|  | ||||
|         if (this.isChanged) { | ||||
|             this.dateModified = dateUtils.nowDate(); | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
| module.exports = Attribute; | ||||
| @@ -9,15 +9,13 @@ class Branch extends Entity { | ||||
|     static get tableName() { return "branches"; } | ||||
|     static get primaryKeyName() { return "branchId"; } | ||||
|     // notePosition is not part of hash because it would produce a lot of updates in case of reordering | ||||
|     static get hashedProperties() { return ["branchId", "noteId", "parentNoteId", "dateModified", "isDeleted", "prefix"]; } | ||||
|     static get hashedProperties() { return ["branchId", "noteId", "parentNoteId", "isDeleted", "prefix"]; } | ||||
|  | ||||
|     async getNote() { | ||||
|         return await repository.getEntity("SELECT * FROM notes WHERE noteId = ?", [this.noteId]); | ||||
|     } | ||||
|  | ||||
|     async beforeSaving() { | ||||
|         super.beforeSaving(); | ||||
|  | ||||
|         if (this.notePosition === undefined) { | ||||
|             const maxNotePos = await sql.getValue('SELECT MAX(notePosition) FROM branches WHERE parentNoteId = ? AND isDeleted = 0', [this.parentNoteId]); | ||||
|             this.notePosition = maxNotePos === null ? 0 : maxNotePos + 1; | ||||
| @@ -31,7 +29,11 @@ class Branch extends Entity { | ||||
|             this.dateCreated = dateUtils.nowDate(); | ||||
|         } | ||||
|  | ||||
|         this.dateModified = dateUtils.nowDate(); | ||||
|         super.beforeSaving(); | ||||
|  | ||||
|         if (this.isChanged) { | ||||
|             this.dateModified = dateUtils.nowDate(); | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
|   | ||||
| @@ -1,13 +1,16 @@ | ||||
| "use strict"; | ||||
|  | ||||
| const utils = require('../services/utils'); | ||||
| const repository = require('../services/repository'); | ||||
|  | ||||
| class Entity { | ||||
|     constructor(row = {}) { | ||||
|         for (const key in row) { | ||||
|             this[key] = row[key]; | ||||
|         } | ||||
|  | ||||
|         if ('isDeleted' in this) { | ||||
|             this.isDeleted = !!this.isDeleted; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     beforeSaving() { | ||||
| @@ -15,17 +18,25 @@ class Entity { | ||||
|             this[this.constructor.primaryKeyName] = utils.newEntityId(); | ||||
|         } | ||||
|  | ||||
|         const origHash = this.hash; | ||||
|  | ||||
|         this.hash = this.generateHash(); | ||||
|  | ||||
|         this.isChanged = origHash !== this.hash; | ||||
|     } | ||||
|  | ||||
|     generateHash() { | ||||
|         let contentToHash = ""; | ||||
|  | ||||
|         for (const propertyName of this.constructor.hashedProperties) { | ||||
|             contentToHash += "|" + this[propertyName]; | ||||
|         } | ||||
|  | ||||
|         this["hash"] = utils.hash(contentToHash).substr(0, 10); | ||||
|         return utils.hash(contentToHash).substr(0, 10); | ||||
|     } | ||||
|  | ||||
|     async save() { | ||||
|         await repository.updateEntity(this); | ||||
|         await require('../services/repository').updateEntity(this); | ||||
|  | ||||
|         return this; | ||||
|     } | ||||
|   | ||||
| @@ -3,17 +3,37 @@ const NoteRevision = require('../entities/note_revision'); | ||||
| const Image = require('../entities/image'); | ||||
| const NoteImage = require('../entities/note_image'); | ||||
| const Branch = require('../entities/branch'); | ||||
| const Label = require('../entities/label'); | ||||
| const Attribute = require('../entities/attribute'); | ||||
| const RecentNote = require('../entities/recent_note'); | ||||
| const ApiToken = require('../entities/api_token'); | ||||
| const Option = require('../entities/option'); | ||||
| const repository = require('../services/repository'); | ||||
|  | ||||
| const TABLE_NAME_TO_ENTITY = { | ||||
|     "attributes": Attribute, | ||||
|     "images": Image, | ||||
|     "note_images": NoteImage, | ||||
|     "branches": Branch, | ||||
|     "notes": Note, | ||||
|     "note_revisions": NoteRevision, | ||||
|     "recent_notes": RecentNote, | ||||
|     "options": Option, | ||||
|     "api_tokens": ApiToken | ||||
| }; | ||||
|  | ||||
| function getEntityFromTableName(tableName) { | ||||
|     if (!(tableName in TABLE_NAME_TO_ENTITY)) { | ||||
|         throw new Error(`Entity for table ${tableName} not found!`); | ||||
|     } | ||||
|  | ||||
|     return TABLE_NAME_TO_ENTITY[tableName]; | ||||
| } | ||||
|  | ||||
| function createEntityFromRow(row) { | ||||
|     let entity; | ||||
|  | ||||
|     if (row.labelId) { | ||||
|         entity = new Label(row); | ||||
|     if (row.attributeId) { | ||||
|         entity = new Attribute(row); | ||||
|     } | ||||
|     else if (row.noteRevisionId) { | ||||
|         entity = new NoteRevision(row); | ||||
| @@ -46,8 +66,9 @@ function createEntityFromRow(row) { | ||||
|     return entity; | ||||
| } | ||||
|  | ||||
| repository.setEntityConstructor(createEntityFromRow); | ||||
|  | ||||
| module.exports = { | ||||
|     createEntityFromRow | ||||
|     createEntityFromRow, | ||||
|     getEntityFromTableName | ||||
| }; | ||||
|  | ||||
| repository.setEntityConstructor(module.exports); | ||||
|   | ||||
| @@ -6,11 +6,9 @@ const dateUtils = require('../services/date_utils'); | ||||
| class Image extends Entity { | ||||
|     static get tableName() { return "images"; } | ||||
|     static get primaryKeyName() { return "imageId"; } | ||||
|     static get hashedProperties() { return ["imageId", "format", "checksum", "name", "isDeleted", "dateModified", "dateCreated"]; } | ||||
|     static get hashedProperties() { return ["imageId", "format", "checksum", "name", "isDeleted", "dateCreated"]; } | ||||
|  | ||||
|     beforeSaving() { | ||||
|         super.beforeSaving(); | ||||
|  | ||||
|         if (!this.isDeleted) { | ||||
|             this.isDeleted = false; | ||||
|         } | ||||
| @@ -19,7 +17,11 @@ class Image extends Entity { | ||||
|             this.dateCreated = dateUtils.nowDate(); | ||||
|         } | ||||
|  | ||||
|         this.dateModified = dateUtils.nowDate(); | ||||
|         super.beforeSaving(); | ||||
|  | ||||
|         if (this.isChanged) { | ||||
|             this.dateModified = dateUtils.nowDate(); | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
|   | ||||
| @@ -1,41 +0,0 @@ | ||||
| "use strict"; | ||||
|  | ||||
| const Entity = require('./entity'); | ||||
| const repository = require('../services/repository'); | ||||
| const dateUtils = require('../services/date_utils'); | ||||
| const sql = require('../services/sql'); | ||||
|  | ||||
| class Label extends Entity { | ||||
|     static get tableName() { return "labels"; } | ||||
|     static get primaryKeyName() { return "labelId"; } | ||||
|     static get hashedProperties() { return ["labelId", "noteId", "name", "value", "dateModified", "dateCreated"]; } | ||||
|  | ||||
|     async getNote() { | ||||
|         return await repository.getEntity("SELECT * FROM notes WHERE noteId = ?", [this.noteId]); | ||||
|     } | ||||
|  | ||||
|     async beforeSaving() { | ||||
|         super.beforeSaving(); | ||||
|  | ||||
|         if (!this.value) { | ||||
|             // null value isn't allowed | ||||
|             this.value = ""; | ||||
|         } | ||||
|  | ||||
|         if (this.position === undefined) { | ||||
|             this.position = 1 + await sql.getValue(`SELECT COALESCE(MAX(position), 0) FROM labels WHERE noteId = ?`, [this.noteId]); | ||||
|         } | ||||
|  | ||||
|         if (!this.isDeleted) { | ||||
|             this.isDeleted = false; | ||||
|         } | ||||
|  | ||||
|         if (!this.dateCreated) { | ||||
|             this.dateCreated = dateUtils.nowDate(); | ||||
|         } | ||||
|  | ||||
|         this.dateModified = dateUtils.nowDate(); | ||||
|     } | ||||
| } | ||||
|  | ||||
| module.exports = Label; | ||||
| @@ -1,6 +1,7 @@ | ||||
| "use strict"; | ||||
|  | ||||
| const Entity = require('./entity'); | ||||
| const Attribute = require('./attribute'); | ||||
| const protectedSessionService = require('../services/protected_session'); | ||||
| const repository = require('../services/repository'); | ||||
| const dateUtils = require('../services/date_utils'); | ||||
| @@ -8,11 +9,13 @@ const dateUtils = require('../services/date_utils'); | ||||
| class Note extends Entity { | ||||
|     static get tableName() { return "notes"; } | ||||
|     static get primaryKeyName() { return "noteId"; } | ||||
|     static get hashedProperties() { return ["noteId", "title", "content", "type", "dateModified", "isProtected", "isDeleted"]; } | ||||
|     static get hashedProperties() { return ["noteId", "title", "content", "type", "isProtected", "isDeleted"]; } | ||||
|  | ||||
|     constructor(row) { | ||||
|         super(row); | ||||
|  | ||||
|         this.isProtected = !!this.isProtected; | ||||
|  | ||||
|         // check if there's noteId, otherwise this is a new entity which wasn't encrypted yet | ||||
|         if (this.isProtected && this.noteId) { | ||||
|             protectedSessionService.decryptNote(this); | ||||
| @@ -30,6 +33,10 @@ class Note extends Entity { | ||||
|         catch(e) {} | ||||
|     } | ||||
|  | ||||
|     isRoot() { | ||||
|         return this.noteId === 'root'; | ||||
|     } | ||||
|  | ||||
|     isJson() { | ||||
|         return this.mime === "application/json"; | ||||
|     } | ||||
| @@ -59,30 +66,140 @@ class Note extends Entity { | ||||
|         return null; | ||||
|     } | ||||
|  | ||||
|     async getLabels() { | ||||
|         return await repository.getEntities("SELECT * FROM labels WHERE noteId = ? AND isDeleted = 0", [this.noteId]); | ||||
|     async getOwnedAttributes() { | ||||
|         return await repository.getEntities(`SELECT * FROM attributes WHERE isDeleted = 0 AND noteId = ?`, [this.noteId]); | ||||
|     } | ||||
|  | ||||
|     // WARNING: this doesn't take into account the possibility to have multi-valued labels! | ||||
|     async getLabelMap() { | ||||
|         const map = {}; | ||||
|  | ||||
|         for (const label of await this.getLabels()) { | ||||
|             map[label.name] = label.value; | ||||
|     async getAttributes() { | ||||
|         if (!this.__attributeCache) { | ||||
|             await this.loadAttributesToCache(); | ||||
|         } | ||||
|  | ||||
|         return map; | ||||
|         return this.__attributeCache; | ||||
|     } | ||||
|  | ||||
|     invalidateAttributeCache() { | ||||
|         this.__attributeCache = null; | ||||
|     } | ||||
|  | ||||
|     async loadAttributesToCache() { | ||||
|         const attributes = await repository.getEntities(` | ||||
|             WITH RECURSIVE | ||||
|             tree(noteId, level) AS ( | ||||
|                 SELECT ?, 0 | ||||
|                 UNION | ||||
|                 SELECT branches.parentNoteId, tree.level + 1 FROM branches | ||||
|                     JOIN tree ON branches.noteId = tree.noteId | ||||
|                     JOIN notes ON notes.noteId = branches.parentNoteId | ||||
|                 WHERE notes.isDeleted = 0 | ||||
|                   AND branches.isDeleted = 0 | ||||
|             ), | ||||
|             treeWithAttrs(noteId, level) AS ( | ||||
|                 SELECT * FROM tree | ||||
|                 UNION | ||||
|                 SELECT attributes.value, treeWithAttrs.level + 1 FROM attributes | ||||
|                      JOIN treeWithAttrs ON treeWithAttrs.noteId = attributes.noteId | ||||
|                 WHERE attributes.isDeleted = 0 | ||||
|                   AND attributes.type = 'relation' | ||||
|                   AND attributes.name = 'inheritAttributes' | ||||
|                   AND (attributes.noteId = ? OR attributes.isInheritable = 1) | ||||
|                 ) | ||||
|             SELECT attributes.* FROM attributes JOIN treeWithAttrs ON attributes.noteId = treeWithAttrs.noteId | ||||
|             WHERE attributes.isDeleted = 0 AND (attributes.isInheritable = 1 OR attributes.noteId = ?) | ||||
|             ORDER BY level, noteId, position`, [this.noteId, this.noteId, this.noteId]); | ||||
|         // attributes are ordered so that "closest" attributes are first | ||||
|         // we order by noteId so that attributes from same note stay together. Actual noteId ordering doesn't matter. | ||||
|  | ||||
|         const filteredAttributes = attributes.filter((attr, index) => { | ||||
|             if (attr.isDefinition()) { | ||||
|                 const firstDefinitionIndex = attributes.findIndex(el => el.type === attr.type && el.name === attr.name); | ||||
|  | ||||
|                 // keep only if this element is the first definition for this type & name | ||||
|                 return firstDefinitionIndex === index; | ||||
|             } | ||||
|             else { | ||||
|                 const definitionAttr = attributes.find(el => el.type === attr.type + '-definition' && el.name === attr.name); | ||||
|  | ||||
|                 if (!definitionAttr) { | ||||
|                     return true; | ||||
|                 } | ||||
|  | ||||
|                 const definition = definitionAttr.value; | ||||
|  | ||||
|                 if (definition.multiplicityType === 'multivalue') { | ||||
|                     return true; | ||||
|                 } | ||||
|                 else { | ||||
|                     const firstAttrIndex = attributes.findIndex(el => el.type === attr.type && el.name === attr.name); | ||||
|  | ||||
|                     // in case of single-valued attribute we'll keep it only if it's first (closest) | ||||
|                     return firstAttrIndex === index; | ||||
|                 } | ||||
|             } | ||||
|         }); | ||||
|  | ||||
|         for (const attr of filteredAttributes) { | ||||
|             attr.isOwned = attr.noteId === this.noteId; | ||||
|         } | ||||
|  | ||||
|         this.__attributeCache = filteredAttributes; | ||||
|     } | ||||
|  | ||||
|     async hasLabel(name) { | ||||
|         const map = await this.getLabelMap(); | ||||
|  | ||||
|         return map.hasOwnProperty(name); | ||||
|         return !!await this.getLabel(name); | ||||
|     } | ||||
|  | ||||
|     // WARNING: this doesn't take into account the possibility to have multi-valued labels! | ||||
|     async getLabel(name) { | ||||
|         return await repository.getEntity("SELECT * FROM labels WHERE noteId = ? AND name = ?", [this.noteId, name]); | ||||
|         const attributes = await this.getAttributes(); | ||||
|  | ||||
|         return attributes.find(attr => attr.type === 'label' && attr.name === name); | ||||
|     } | ||||
|  | ||||
|     async getLabelValue(name) { | ||||
|         const label = await this.getLabel(name); | ||||
|  | ||||
|         return label ? label.value : null; | ||||
|     } | ||||
|  | ||||
|     async toggleLabel(enabled, name, value = "") { | ||||
|         if (enabled) { | ||||
|             await this.setLabel(name, value); | ||||
|         } | ||||
|         else { | ||||
|             await this.removeLabel(name, value); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     async setLabel(name, value = "") { | ||||
|         const attributes = await this.getOwnedAttributes(); | ||||
|         let label = attributes.find(attr => attr.type === 'label' && attr.value === value); | ||||
|  | ||||
|         if (!label) { | ||||
|             label = new Attribute({ | ||||
|                 noteId: this.noteId, | ||||
|                 type: 'label', | ||||
|                 name: name, | ||||
|                 value: value | ||||
|             }); | ||||
|  | ||||
|             await label.save(); | ||||
|  | ||||
|             this.invalidateAttributeCache(); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     async removeLabel(name, value = "") { | ||||
|         const attributes = await this.getOwnedAttributes(); | ||||
|  | ||||
|         for (const attribute of attributes) { | ||||
|             if (attribute.type === 'label' && (!value || value === attribute.value)) { | ||||
|                 attribute.isDeleted = true; | ||||
|                 await attribute.save(); | ||||
|  | ||||
|                 this.invalidateAttributeCache(); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     async getRevisions() { | ||||
| @@ -140,8 +257,6 @@ class Note extends Entity { | ||||
|     } | ||||
|  | ||||
|     beforeSaving() { | ||||
|         super.beforeSaving(); | ||||
|  | ||||
|         if (this.isJson() && this.jsonContent) { | ||||
|             this.content = JSON.stringify(this.jsonContent, null, '\t'); | ||||
|         } | ||||
| @@ -158,7 +273,11 @@ class Note extends Entity { | ||||
|             this.dateCreated = dateUtils.nowDate(); | ||||
|         } | ||||
|  | ||||
|         this.dateModified = dateUtils.nowDate(); | ||||
|         super.beforeSaving(); | ||||
|  | ||||
|         if (this.isChanged) { | ||||
|             this.dateModified = dateUtils.nowDate(); | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
|   | ||||
| @@ -7,7 +7,7 @@ const dateUtils = require('../services/date_utils'); | ||||
| class NoteImage extends Entity { | ||||
|     static get tableName() { return "note_images"; } | ||||
|     static get primaryKeyName() { return "noteImageId"; } | ||||
|     static get hashedProperties() { return ["noteImageId", "noteId", "imageId", "isDeleted", "dateModified", "dateCreated"]; } | ||||
|     static get hashedProperties() { return ["noteImageId", "noteId", "imageId", "isDeleted", "dateCreated"]; } | ||||
|  | ||||
|     async getNote() { | ||||
|         return await repository.getEntity("SELECT * FROM notes WHERE noteId = ?", [this.noteId]); | ||||
| @@ -18,8 +18,6 @@ class NoteImage extends Entity { | ||||
|     } | ||||
|  | ||||
|     beforeSaving() { | ||||
|         super.beforeSaving(); | ||||
|  | ||||
|         if (!this.isDeleted) { | ||||
|             this.isDeleted = false; | ||||
|         } | ||||
| @@ -28,7 +26,11 @@ class NoteImage extends Entity { | ||||
|             this.dateCreated = dateUtils.nowDate(); | ||||
|         } | ||||
|  | ||||
|         this.dateModified = dateUtils.nowDate(); | ||||
|         super.beforeSaving(); | ||||
|  | ||||
|         if (this.isChanged) { | ||||
|             this.dateModified = dateUtils.nowDate(); | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
|   | ||||
| @@ -7,11 +7,13 @@ const repository = require('../services/repository'); | ||||
| class NoteRevision extends Entity { | ||||
|     static get tableName() { return "note_revisions"; } | ||||
|     static get primaryKeyName() { return "noteRevisionId"; } | ||||
|     static get hashedProperties() { return ["noteRevisionId", "noteId", "title", "content", "dateModifiedFrom", "dateModifiedTo"]; } | ||||
|     static get hashedProperties() { return ["noteRevisionId", "noteId", "title", "content", "isProtected", "dateModifiedFrom", "dateModifiedTo"]; } | ||||
|  | ||||
|     constructor(row) { | ||||
|         super(row); | ||||
|  | ||||
|         this.isProtected = !!this.isProtected; | ||||
|  | ||||
|         if (this.isProtected) { | ||||
|             protectedSessionService.decryptNoteRevision(this); | ||||
|         } | ||||
| @@ -22,11 +24,11 @@ class NoteRevision extends Entity { | ||||
|     } | ||||
|  | ||||
|     beforeSaving() { | ||||
|         super.beforeSaving(); | ||||
|  | ||||
|         if (this.isProtected) { | ||||
|             protectedSessionService.encryptNoteRevision(this); | ||||
|         } | ||||
|  | ||||
|         super.beforeSaving(); | ||||
|     } | ||||
| } | ||||
|  | ||||
|   | ||||
| @@ -8,10 +8,18 @@ class Option extends Entity { | ||||
|     static get primaryKeyName() { return "name"; } | ||||
|     static get hashedProperties() { return ["name", "value"]; } | ||||
|  | ||||
|     constructor(row) { | ||||
|         super(row); | ||||
|  | ||||
|         this.isSynced = !!this.isSynced; | ||||
|     } | ||||
|  | ||||
|     beforeSaving() { | ||||
|         super.beforeSaving(); | ||||
|  | ||||
|         this.dateModified = dateUtils.nowDate(); | ||||
|         if (this.isChanged) { | ||||
|             this.dateModified = dateUtils.nowDate(); | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
|   | ||||
| @@ -9,8 +9,6 @@ class RecentNote extends Entity { | ||||
|     static get hashedProperties() { return ["branchId", "notePath", "dateCreated", "isDeleted"]; } | ||||
|  | ||||
|     beforeSaving() { | ||||
|         super.beforeSaving(); | ||||
|  | ||||
|         if (!this.isDeleted) { | ||||
|             this.isDeleted = false; | ||||
|         } | ||||
| @@ -18,6 +16,8 @@ class RecentNote extends Entity { | ||||
|         if (!this.dateCreated) { | ||||
|             this.dateCreated = dateUtils.nowDate(); | ||||
|         } | ||||
|  | ||||
|         super.beforeSaving(); | ||||
|     } | ||||
| } | ||||
|  | ||||
|   | ||||
							
								
								
									
										
											BIN
										
									
								
								src/public/images/icons/clock-16.png
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										
											BIN
										
									
								
								src/public/images/icons/clock-16.png
									
									
									
									
									
										Normal file
									
								
							
										
											Binary file not shown.
										
									
								
							| After Width: | Height: | Size: 381 B | 
| @@ -15,6 +15,7 @@ const $prefixFormGroup = $("#add-link-prefix-form-group"); | ||||
| const $linkTypeDiv = $("#add-link-type-div"); | ||||
| const $linkTypes = $("input[name='add-link-type']"); | ||||
| const $linkTypeHtml = $linkTypes.filter('input[value="html"]'); | ||||
| const $showRecentNotesButton = $dialog.find(".show-recent-notes-button"); | ||||
|  | ||||
| function setLinkType(linkType) { | ||||
|     $linkTypes.each(function () { | ||||
| @@ -53,12 +54,17 @@ async function showDialog() { | ||||
|         $linkTitle.val(noteTitle); | ||||
|     } | ||||
|  | ||||
|     $autoComplete.autocomplete({ | ||||
|     await $autoComplete.autocomplete({ | ||||
|         source: async function(request, response) { | ||||
|             const result = await server.get('autocomplete?query=' + encodeURIComponent(request.term)); | ||||
|  | ||||
|             if (result.length > 0) { | ||||
|                 response(result); | ||||
|                 response(result.map(row => { | ||||
|                     return { | ||||
|                         label: row.label, | ||||
|                         value: row.label + ' (' + row.value + ')' | ||||
|                     } | ||||
|                 })); | ||||
|             } | ||||
|             else { | ||||
|                 response([{ | ||||
| @@ -67,10 +73,14 @@ async function showDialog() { | ||||
|                 }]); | ||||
|             } | ||||
|         }, | ||||
|         minLength: 2, | ||||
|         change: async () => { | ||||
|             const val = $autoComplete.val(); | ||||
|             const notePath = linkService.getNodePathFromLabel(val); | ||||
|         minLength: 0, | ||||
|         change: async (event, ui) => { | ||||
|             if (!ui.item) { | ||||
|                 return; | ||||
|             } | ||||
|  | ||||
|             const notePath = linkService.getNotePathFromLabel(ui.item.value); | ||||
|  | ||||
|             if (!notePath) { | ||||
|                 return; | ||||
|             } | ||||
| @@ -81,21 +91,30 @@ async function showDialog() { | ||||
|                 await setDefaultLinkTitle(noteId); | ||||
|             } | ||||
|         }, | ||||
|         select: function (event, ui) { | ||||
|             if (ui.item.value === 'No results') { | ||||
|                 return false; | ||||
|             } | ||||
|         }, | ||||
|         // this is called when user goes through autocomplete list with keyboard | ||||
|         // at this point the item isn't selected yet so we use supplied ui.item to see WHERE the cursor is | ||||
|         focus: async (event, ui) => { | ||||
|             const notePath = linkService.getNodePathFromLabel(ui.item.value); | ||||
|             const notePath = linkService.getNotePathFromLabel(ui.item.value); | ||||
|             const noteId = treeUtils.getNoteIdFromNotePath(notePath); | ||||
|  | ||||
|             await setDefaultLinkTitle(noteId); | ||||
|  | ||||
|             event.preventDefault(); | ||||
|         } | ||||
|     }); | ||||
|  | ||||
|     showRecentNotes(); | ||||
| } | ||||
|  | ||||
| $form.submit(() => { | ||||
|     const value = $autoComplete.val(); | ||||
|  | ||||
|     const notePath = linkService.getNodePathFromLabel(value); | ||||
|     const notePath = linkService.getNotePathFromLabel(value); | ||||
|     const noteId = treeUtils.getNoteIdFromNotePath(notePath); | ||||
|  | ||||
|     if (notePath) { | ||||
| @@ -153,8 +172,14 @@ function linkTypeChanged() { | ||||
|     $linkTypeDiv.toggle(!hasSelection()); | ||||
| } | ||||
|  | ||||
| function showRecentNotes() { | ||||
|     $autoComplete.autocomplete("search", ""); | ||||
| } | ||||
|  | ||||
| $linkTypes.change(linkTypeChanged); | ||||
|  | ||||
| $showRecentNotesButton.click(showRecentNotes); | ||||
|  | ||||
| export default { | ||||
|     showDialog | ||||
| }; | ||||
							
								
								
									
										318
									
								
								src/public/javascripts/dialogs/attributes.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										318
									
								
								src/public/javascripts/dialogs/attributes.js
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,318 @@ | ||||
| import noteDetailService from '../services/note_detail.js'; | ||||
| import server from '../services/server.js'; | ||||
| import infoService from "../services/info.js"; | ||||
| import treeUtils from "../services/tree_utils.js"; | ||||
| import linkService from "../services/link.js"; | ||||
|  | ||||
| const $dialog = $("#attributes-dialog"); | ||||
| const $saveAttributesButton = $("#save-attributes-button"); | ||||
| const $ownedAttributesBody = $('#owned-attributes-table tbody'); | ||||
|  | ||||
| const attributesModel = new AttributesModel(); | ||||
|  | ||||
| function AttributesModel() { | ||||
|     const self = this; | ||||
|  | ||||
|     this.ownedAttributes = ko.observableArray(); | ||||
|     this.inheritedAttributes = ko.observableArray(); | ||||
|  | ||||
|     this.availableTypes = [ | ||||
|         { text: "Label", value: "label" }, | ||||
|         { text: "Label definition", value: "label-definition" }, | ||||
|         { text: "Relation", value: "relation" }, | ||||
|         { text: "Relation definition", value: "relation-definition" } | ||||
|     ]; | ||||
|  | ||||
|     this.availableLabelTypes = [ | ||||
|         { text: "Text", value: "text" }, | ||||
|         { text: "Number", value: "number" }, | ||||
|         { text: "Boolean", value: "boolean" }, | ||||
|         { text: "Date", value: "date" } | ||||
|     ]; | ||||
|  | ||||
|     this.multiplicityTypes = [ | ||||
|         { text: "Single value", value: "singlevalue" }, | ||||
|         { text: "Multi value", value: "multivalue" } | ||||
|     ]; | ||||
|  | ||||
|     this.typeChanged = function(data, event) { | ||||
|         self.getTargetAttribute(event.target).valueHasMutated(); | ||||
|     }; | ||||
|  | ||||
|     this.labelTypeChanged = function(data, event) { | ||||
|         self.getTargetAttribute(event.target).valueHasMutated(); | ||||
|     }; | ||||
|  | ||||
|     this.updateAttributePositions = function() { | ||||
|         let position = 0; | ||||
|  | ||||
|         // we need to update positions by searching in the DOM, because order of the | ||||
|         // attributes in the viewmodel (self.ownedAttributes()) stays the same | ||||
|         $ownedAttributesBody.find('input[name="position"]').each(function() { | ||||
|             const attribute = self.getTargetAttribute(this); | ||||
|  | ||||
|             attribute().position = position++; | ||||
|         }); | ||||
|     }; | ||||
|  | ||||
|     async function showAttributes(attributes) { | ||||
|         const ownedAttributes = attributes.filter(attr => attr.isOwned); | ||||
|  | ||||
|         for (const attr of ownedAttributes) { | ||||
|             attr.labelValue = attr.type === 'label' ? attr.value : ''; | ||||
|             attr.relationValue = attr.type === 'relation' ? (await treeUtils.getNoteTitle(attr.value) + " (" + attr.value + ")") : ''; | ||||
|             attr.labelDefinition = (attr.type === 'label-definition' && attr.value) ? attr.value : { | ||||
|                 labelType: "text", | ||||
|                 multiplicityType: "singlevalue", | ||||
|                 isPromoted: true | ||||
|             }; | ||||
|             attr.relationDefinition = attr.type === ('relation-definition' && attr.value) ? attr.value : { | ||||
|                 multiplicityType: "singlevalue", | ||||
|                 isPromoted: true | ||||
|             }; | ||||
|  | ||||
|             delete attr.value; | ||||
|         } | ||||
|  | ||||
|         self.ownedAttributes(ownedAttributes.map(ko.observable)); | ||||
|  | ||||
|         addLastEmptyRow(); | ||||
|  | ||||
|         const inheritedAttributes = attributes.filter(attr => !attr.isOwned); | ||||
|  | ||||
|         self.inheritedAttributes(inheritedAttributes); | ||||
|     } | ||||
|  | ||||
|     this.loadAttributes = async function() { | ||||
|         const noteId = noteDetailService.getCurrentNoteId(); | ||||
|  | ||||
|         const attributes = await server.get('notes/' + noteId + '/attributes'); | ||||
|  | ||||
|         await showAttributes(attributes); | ||||
|  | ||||
|         // attribute might not be rendered immediatelly so could not focus | ||||
|         setTimeout(() => $(".attribute-name:last").focus(), 100); | ||||
|  | ||||
|         $ownedAttributesBody.sortable({ | ||||
|             handle: '.handle', | ||||
|             containment: $ownedAttributesBody, | ||||
|             update: this.updateAttributePositions | ||||
|         }); | ||||
|     }; | ||||
|  | ||||
|     this.deleteAttribute = function(data, event) { | ||||
|         const attribute = self.getTargetAttribute(event.target); | ||||
|         const attributeData = attribute(); | ||||
|  | ||||
|         if (attributeData) { | ||||
|             attributeData.isDeleted = true; | ||||
|  | ||||
|             attribute(attributeData); | ||||
|  | ||||
|             addLastEmptyRow(); | ||||
|         } | ||||
|     }; | ||||
|  | ||||
|     function isValid() { | ||||
|         for (let attributes = self.ownedAttributes(), i = 0; i < attributes.length; i++) { | ||||
|             if (self.isEmptyName(i)) { | ||||
|                 return false; | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         return true; | ||||
|     } | ||||
|  | ||||
|     this.save = async function() { | ||||
|         // we need to defocus from input (in case of enter-triggered save) because value is updated | ||||
|         // on blur event (because of conflict with jQuery UI Autocomplete). Without this, input would | ||||
|         // stay in focus, blur wouldn't be triggered and change wouldn't be updated in the viewmodel. | ||||
|         $saveAttributesButton.focus(); | ||||
|  | ||||
|         if (!isValid()) { | ||||
|             alert("Please fix all validation errors and try saving again."); | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         self.updateAttributePositions(); | ||||
|  | ||||
|         const noteId = noteDetailService.getCurrentNoteId(); | ||||
|  | ||||
|         const attributesToSave = self.ownedAttributes() | ||||
|             .map(attribute => attribute()) | ||||
|             .filter(attribute => attribute.attributeId !== "" || attribute.name !== ""); | ||||
|  | ||||
|         for (const attr of attributesToSave) { | ||||
|             if (attr.type === 'label') { | ||||
|                 attr.value = attr.labelValue; | ||||
|             } | ||||
|             else if (attr.type === 'relation') { | ||||
|                 attr.value = treeUtils.getNoteIdFromNotePath(linkService.getNotePathFromLabel(attr.relationValue)); | ||||
|             } | ||||
|             else if (attr.type === 'label-definition') { | ||||
|                 attr.value = attr.labelDefinition; | ||||
|             } | ||||
|             else if (attr.type === 'relation-definition') { | ||||
|                 attr.value = attr.relationDefinition; | ||||
|             } | ||||
|  | ||||
|             delete attr.labelValue; | ||||
|             delete attr.relationValue; | ||||
|             delete attr.labelDefinition; | ||||
|             delete attr.relationDefinition; | ||||
|         } | ||||
|  | ||||
|         const attributes = await server.put('notes/' + noteId + '/attributes', attributesToSave); | ||||
|  | ||||
|         await showAttributes(attributes); | ||||
|  | ||||
|         infoService.showMessage("Attributes have been saved."); | ||||
|  | ||||
|         noteDetailService.loadAttributes(); | ||||
|     }; | ||||
|  | ||||
|     function addLastEmptyRow() { | ||||
|         const attributes = self.ownedAttributes().filter(attr => !attr().isDeleted); | ||||
|         const last = attributes.length === 0 ? null : attributes[attributes.length - 1](); | ||||
|  | ||||
|         if (!last || last.name.trim() !== "") { | ||||
|             self.ownedAttributes.push(ko.observable({ | ||||
|                 attributeId: '', | ||||
|                 type: 'label', | ||||
|                 name: '', | ||||
|                 labelValue: '', | ||||
|                 relationValue: '', | ||||
|                 isInheritable: false, | ||||
|                 isDeleted: false, | ||||
|                 position: 0, | ||||
|                 labelDefinition: { | ||||
|                     labelType: "text", | ||||
|                     multiplicityType: "singlevalue", | ||||
|                     isPromoted: true | ||||
|                 }, | ||||
|                 relationDefinition: { | ||||
|                     multiplicityType: "singlevalue", | ||||
|                     isPromoted: true | ||||
|                 } | ||||
|             })); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     this.attributeChanged = function (data, event) { | ||||
|         addLastEmptyRow(); | ||||
|  | ||||
|         const attribute = self.getTargetAttribute(event.target); | ||||
|  | ||||
|         attribute.valueHasMutated(); | ||||
|     }; | ||||
|  | ||||
|     this.isNotUnique = function(index) { | ||||
|         const cur = self.ownedAttributes()[index](); | ||||
|  | ||||
|         if (cur.name.trim() === "") { | ||||
|             return false; | ||||
|         } | ||||
|  | ||||
|         for (let attributes = self.ownedAttributes(), i = 0; i < attributes.length; i++) { | ||||
|             const attribute = attributes[i](); | ||||
|  | ||||
|             if (index !== i && cur.name === attribute.name && cur.type === attribute.type) { | ||||
|                 return true; | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         return false; | ||||
|     }; | ||||
|  | ||||
|     this.isEmptyName = function(index) { | ||||
|         const cur = self.ownedAttributes()[index](); | ||||
|  | ||||
|         return cur.name.trim() === "" && !cur.isDeleted && (cur.attributeId !== "" || cur.labelValue !== "" || cur.relationValue); | ||||
|     }; | ||||
|  | ||||
|     this.getTargetAttribute = function(target) { | ||||
|         const context = ko.contextFor(target); | ||||
|         const index = context.$index(); | ||||
|  | ||||
|         return self.ownedAttributes()[index]; | ||||
|     } | ||||
| } | ||||
|  | ||||
| async function showDialog() { | ||||
|     glob.activeDialog = $dialog; | ||||
|  | ||||
|     await attributesModel.loadAttributes(); | ||||
|  | ||||
|     $dialog.dialog({ | ||||
|         modal: true, | ||||
|         width: 950, | ||||
|         height: 500 | ||||
|     }); | ||||
| } | ||||
|  | ||||
| ko.applyBindings(attributesModel, $dialog[0]); | ||||
|  | ||||
| $dialog.on('focus', '.attribute-name', function (e) { | ||||
|     if (!$(this).hasClass("ui-autocomplete-input")) { | ||||
|         $(this).autocomplete({ | ||||
|             source: async (request, response) => { | ||||
|                 const attribute = attributesModel.getTargetAttribute(this); | ||||
|                 const type = (attribute().type === 'relation' || attribute().type === 'relation-definition') ? 'relation' : 'label'; | ||||
|                 const names = await server.get('attributes/names/?type=' + type + '&query=' + encodeURIComponent(request.term)); | ||||
|                 const result = names.map(name => { | ||||
|                     return { | ||||
|                         label: name, | ||||
|                         value: name | ||||
|                     } | ||||
|                 }); | ||||
|  | ||||
|                 if (result.length > 0) { | ||||
|                     response(result); | ||||
|                 } | ||||
|                 else { | ||||
|                     response([{ | ||||
|                         label: "No results", | ||||
|                         value: "No results" | ||||
|                     }]); | ||||
|                 } | ||||
|             }, | ||||
|             minLength: 0 | ||||
|         }); | ||||
|     } | ||||
|  | ||||
|     $(this).autocomplete("search", $(this).val()); | ||||
| }); | ||||
|  | ||||
| $dialog.on('focus', '.label-value', async function (e) { | ||||
|     if (!$(this).hasClass("ui-autocomplete-input")) { | ||||
|         const attributeName = $(this).parent().parent().find('.attribute-name').val(); | ||||
|  | ||||
|         if (attributeName.trim() === "") { | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         const attributeValues = await server.get('attributes/values/' + encodeURIComponent(attributeName)); | ||||
|  | ||||
|         if (attributeValues.length === 0) { | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         $(this).autocomplete({ | ||||
|             // shouldn't be required and autocomplete should just accept array of strings, but that fails | ||||
|             // because we have overriden filter() function in autocomplete.js | ||||
|             source: attributeValues.map(attribute => { | ||||
|                 return { | ||||
|                     attribute: attribute, | ||||
|                     value: attribute | ||||
|                 } | ||||
|             }), | ||||
|             minLength: 0 | ||||
|         }); | ||||
|     } | ||||
|  | ||||
|     $(this).autocomplete("search", $(this).val()); | ||||
| }); | ||||
|  | ||||
| export default { | ||||
|     showDialog | ||||
| }; | ||||
| @@ -1,13 +1,11 @@ | ||||
| import treeService from '../services/tree.js'; | ||||
| import linkService from '../services/link.js'; | ||||
| import server from '../services/server.js'; | ||||
| import searchNotesService from '../services/search_notes.js'; | ||||
|  | ||||
| const $dialog = $("#jump-to-note-dialog"); | ||||
| const $autoComplete = $("#jump-to-note-autocomplete"); | ||||
| const $form = $("#jump-to-note-form"); | ||||
| const $jumpToNoteButton = $("#jump-to-note-button"); | ||||
| const $showInFullTextButton = $("#show-in-full-text-button"); | ||||
| const $showRecentNotesButton = $dialog.find(".show-recent-notes-button"); | ||||
|  | ||||
| async function showDialog() { | ||||
|     glob.activeDialog = $dialog; | ||||
| @@ -16,7 +14,8 @@ async function showDialog() { | ||||
|  | ||||
|     $dialog.dialog({ | ||||
|         modal: true, | ||||
|         width: 800 | ||||
|         width: 800, | ||||
|         position: { my: "center top+100", at: "top", of: window } | ||||
|     }); | ||||
|  | ||||
|     await $autoComplete.autocomplete({ | ||||
| @@ -34,25 +33,22 @@ async function showDialog() { | ||||
|             } | ||||
|         }, | ||||
|         focus: function(event, ui) { | ||||
|             return $(ui.item).val() !== 'No results'; | ||||
|             event.preventDefault(); | ||||
|         }, | ||||
|         minLength: 2 | ||||
|         minLength: 0, | ||||
|         autoFocus: true, | ||||
|         select: function (event, ui) { | ||||
|             if (ui.item.value === 'No results') { | ||||
|                 return false; | ||||
|             } | ||||
|  | ||||
|             treeService.activateNode(ui.item.value); | ||||
|  | ||||
|             $dialog.dialog('close'); | ||||
|         } | ||||
|     }); | ||||
| } | ||||
|  | ||||
| function getSelectedNotePath() { | ||||
|     const val = $autoComplete.val(); | ||||
|     return linkService.getNodePathFromLabel(val); | ||||
| } | ||||
|  | ||||
| function goToNote() { | ||||
|     const notePath = getSelectedNotePath(); | ||||
|  | ||||
|     if (notePath) { | ||||
|         treeService.activateNode(notePath); | ||||
|  | ||||
|         $dialog.dialog('close'); | ||||
|     } | ||||
|     showRecentNotes(); | ||||
| } | ||||
|  | ||||
| function showInFullText(e) { | ||||
| @@ -69,16 +65,14 @@ function showInFullText(e) { | ||||
|     $dialog.dialog('close'); | ||||
| } | ||||
|  | ||||
| $form.submit(() => { | ||||
|     goToNote(); | ||||
|  | ||||
|     return false; | ||||
| }); | ||||
|  | ||||
| $jumpToNoteButton.click(goToNote); | ||||
| function showRecentNotes() { | ||||
|     $autoComplete.autocomplete("search", ""); | ||||
| } | ||||
|  | ||||
| $showInFullTextButton.click(showInFullText); | ||||
|  | ||||
| $showRecentNotesButton.click(showRecentNotes); | ||||
|  | ||||
| $dialog.bind('keydown', 'ctrl+return', showInFullText); | ||||
|  | ||||
| export default { | ||||
|   | ||||
| @@ -1,223 +0,0 @@ | ||||
| import noteDetailService from '../services/note_detail.js'; | ||||
| import utils from '../services/utils.js'; | ||||
| import server from '../services/server.js'; | ||||
| import infoService from "../services/info.js"; | ||||
|  | ||||
| const $dialog = $("#labels-dialog"); | ||||
| const $saveLabelsButton = $("#save-labels-button"); | ||||
| const $labelsBody = $('#labels-table tbody'); | ||||
|  | ||||
| const labelsModel = new LabelsModel(); | ||||
| let labelNames = []; | ||||
|  | ||||
| function LabelsModel() { | ||||
|     const self = this; | ||||
|  | ||||
|     this.labels = ko.observableArray(); | ||||
|  | ||||
|     this.updateLabelPositions = function() { | ||||
|         let position = 0; | ||||
|  | ||||
|         // we need to update positions by searching in the DOM, because order of the | ||||
|         // labels in the viewmodel (self.labels()) stays the same | ||||
|         $labelsBody.find('input[name="position"]').each(function() { | ||||
|             const label = self.getTargetLabel(this); | ||||
|  | ||||
|             label().position = position++; | ||||
|         }); | ||||
|     }; | ||||
|  | ||||
|     this.loadLabels = async function() { | ||||
|         const noteId = noteDetailService.getCurrentNoteId(); | ||||
|  | ||||
|         const labels = await server.get('notes/' + noteId + '/labels'); | ||||
|  | ||||
|         self.labels(labels.map(ko.observable)); | ||||
|  | ||||
|         addLastEmptyRow(); | ||||
|  | ||||
|         labelNames = await server.get('labels/names'); | ||||
|  | ||||
|         // label might not be rendered immediatelly so could not focus | ||||
|         setTimeout(() => $(".label-name:last").focus(), 100); | ||||
|  | ||||
|         $labelsBody.sortable({ | ||||
|             handle: '.handle', | ||||
|             containment: $labelsBody, | ||||
|             update: this.updateLabelPositions | ||||
|         }); | ||||
|     }; | ||||
|  | ||||
|     this.deleteLabel = function(data, event) { | ||||
|         const label = self.getTargetLabel(event.target); | ||||
|         const labelData = label(); | ||||
|  | ||||
|         if (labelData) { | ||||
|             labelData.isDeleted = 1; | ||||
|  | ||||
|             label(labelData); | ||||
|  | ||||
|             addLastEmptyRow(); | ||||
|         } | ||||
|     }; | ||||
|  | ||||
|     function isValid() { | ||||
|         for (let labels = self.labels(), i = 0; i < labels.length; i++) { | ||||
|             if (self.isEmptyName(i)) { | ||||
|                 return false; | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         return true; | ||||
|     } | ||||
|  | ||||
|     this.save = async function() { | ||||
|         // we need to defocus from input (in case of enter-triggered save) because value is updated | ||||
|         // on blur event (because of conflict with jQuery UI Autocomplete). Without this, input would | ||||
|         // stay in focus, blur wouldn't be triggered and change wouldn't be updated in the viewmodel. | ||||
|         $saveLabelsButton.focus(); | ||||
|  | ||||
|         if (!isValid()) { | ||||
|             alert("Please fix all validation errors and try saving again."); | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         self.updateLabelPositions(); | ||||
|  | ||||
|         const noteId = noteDetailService.getCurrentNoteId(); | ||||
|  | ||||
|         const labelsToSave = self.labels() | ||||
|             .map(label => label()) | ||||
|             .filter(label => label.labelId !== "" || label.name !== ""); | ||||
|  | ||||
|         const labels = await server.put('notes/' + noteId + '/labels', labelsToSave); | ||||
|  | ||||
|         self.labels(labels.map(ko.observable)); | ||||
|  | ||||
|         addLastEmptyRow(); | ||||
|  | ||||
|         infoService.showMessage("Labels have been saved."); | ||||
|  | ||||
|         noteDetailService.loadLabelList(); | ||||
|     }; | ||||
|  | ||||
|     function addLastEmptyRow() { | ||||
|         const labels = self.labels().filter(attr => attr().isDeleted === 0); | ||||
|         const last = labels.length === 0 ? null : labels[labels.length - 1](); | ||||
|  | ||||
|         if (!last || last.name.trim() !== "" || last.value !== "") { | ||||
|             self.labels.push(ko.observable({ | ||||
|                 labelId: '', | ||||
|                 name: '', | ||||
|                 value: '', | ||||
|                 isDeleted: 0, | ||||
|                 position: 0 | ||||
|             })); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     this.labelChanged = function (data, event) { | ||||
|         addLastEmptyRow(); | ||||
|  | ||||
|         const label = self.getTargetLabel(event.target); | ||||
|  | ||||
|         label.valueHasMutated(); | ||||
|     }; | ||||
|  | ||||
|     this.isNotUnique = function(index) { | ||||
|         const cur = self.labels()[index](); | ||||
|  | ||||
|         if (cur.name.trim() === "") { | ||||
|             return false; | ||||
|         } | ||||
|  | ||||
|         for (let labels = self.labels(), i = 0; i < labels.length; i++) { | ||||
|             const label = labels[i](); | ||||
|  | ||||
|             if (index !== i && cur.name === label.name) { | ||||
|                 return true; | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         return false; | ||||
|     }; | ||||
|  | ||||
|     this.isEmptyName = function(index) { | ||||
|         const cur = self.labels()[index](); | ||||
|  | ||||
|         return cur.name.trim() === "" && (cur.labelId !== "" || cur.value !== ""); | ||||
|     }; | ||||
|  | ||||
|     this.getTargetLabel = function(target) { | ||||
|         const context = ko.contextFor(target); | ||||
|         const index = context.$index(); | ||||
|  | ||||
|         return self.labels()[index]; | ||||
|     } | ||||
| } | ||||
|  | ||||
| async function showDialog() { | ||||
|     glob.activeDialog = $dialog; | ||||
|  | ||||
|     await labelsModel.loadLabels(); | ||||
|  | ||||
|     $dialog.dialog({ | ||||
|         modal: true, | ||||
|         width: 800, | ||||
|         height: 500 | ||||
|     }); | ||||
| } | ||||
|  | ||||
| ko.applyBindings(labelsModel, document.getElementById('labels-dialog')); | ||||
|  | ||||
| $(document).on('focus', '.label-name', function (e) { | ||||
|     if (!$(this).hasClass("ui-autocomplete-input")) { | ||||
|         $(this).autocomplete({ | ||||
|             // shouldn't be required and autocomplete should just accept array of strings, but that fails | ||||
|             // because we have overriden filter() function in autocomplete.js | ||||
|             source: labelNames.map(label => { | ||||
|                 return { | ||||
|                     label: label, | ||||
|                     value: label | ||||
|                 } | ||||
|             }), | ||||
|             minLength: 0 | ||||
|         }); | ||||
|     } | ||||
|  | ||||
|     $(this).autocomplete("search", $(this).val()); | ||||
| }); | ||||
|  | ||||
| $(document).on('focus', '.label-value', async function (e) { | ||||
|     if (!$(this).hasClass("ui-autocomplete-input")) { | ||||
|         const labelName = $(this).parent().parent().find('.label-name').val(); | ||||
|  | ||||
|         if (labelName.trim() === "") { | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         const labelValues = await server.get('labels/values/' + encodeURIComponent(labelName)); | ||||
|  | ||||
|         if (labelValues.length === 0) { | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         $(this).autocomplete({ | ||||
|             // shouldn't be required and autocomplete should just accept array of strings, but that fails | ||||
|             // because we have overriden filter() function in autocomplete.js | ||||
|             source: labelValues.map(label => { | ||||
|                 return { | ||||
|                     label: label, | ||||
|                     value: label | ||||
|                 } | ||||
|             }), | ||||
|             minLength: 0 | ||||
|         }); | ||||
|     } | ||||
|  | ||||
|     $(this).autocomplete("search", $(this).val()); | ||||
| }); | ||||
|  | ||||
| export default { | ||||
|     showDialog | ||||
| }; | ||||
| @@ -34,8 +34,8 @@ async function showDialog() { | ||||
|     } | ||||
| } | ||||
|  | ||||
| async function saveOptions(optionName, optionValue) { | ||||
|     await server.put('options/' + encodeURIComponent(optionName) + '/' + encodeURIComponent(optionValue)); | ||||
| async function saveOptions(options) { | ||||
|     await server.put('options', options); | ||||
|  | ||||
|     infoService.showMessage("Options change have been saved."); | ||||
| } | ||||
| @@ -129,16 +129,15 @@ addTabHandler((function() { | ||||
| addTabHandler((function() { | ||||
|     const $form = $("#protected-session-timeout-form"); | ||||
|     const $protectedSessionTimeout = $("#protected-session-timeout-in-seconds"); | ||||
|     const optionName = 'protectedSessionTimeout'; | ||||
|  | ||||
|     function optionsLoaded(options) { | ||||
|         $protectedSessionTimeout.val(options[optionName]); | ||||
|         $protectedSessionTimeout.val(options['protectedSessionTimeout']); | ||||
|     } | ||||
|  | ||||
|     $form.submit(() => { | ||||
|         const protectedSessionTimeout = $protectedSessionTimeout.val(); | ||||
|  | ||||
|         saveOptions(optionName, protectedSessionTimeout).then(() => { | ||||
|         saveOptions({ 'protectedSessionTimeout': protectedSessionTimeout }).then(() => { | ||||
|             protectedSessionHolder.setProtectedSessionTimeout(protectedSessionTimeout); | ||||
|         }); | ||||
|  | ||||
| @@ -153,14 +152,13 @@ addTabHandler((function() { | ||||
| addTabHandler((function () { | ||||
|     const $form = $("#note-revision-snapshot-time-interval-form"); | ||||
|     const $timeInterval = $("#note-revision-snapshot-time-interval-in-seconds"); | ||||
|     const optionName = 'noteRevisionSnapshotTimeInterval'; | ||||
|  | ||||
|     function optionsLoaded(options) { | ||||
|         $timeInterval.val(options[optionName]); | ||||
|         $timeInterval.val(options['noteRevisionSnapshotTimeInterval']); | ||||
|     } | ||||
|  | ||||
|     $form.submit(() => { | ||||
|         saveOptions(optionName, $timeInterval.val()); | ||||
|         saveOptions({ 'noteRevisionSnapshotTimeInterval': $timeInterval.val() }); | ||||
|  | ||||
|         return false; | ||||
|     }); | ||||
| @@ -189,6 +187,57 @@ addTabHandler((async function () { | ||||
|     return {}; | ||||
| })()); | ||||
|  | ||||
| addTabHandler((function() { | ||||
|     const $form = $("#sync-setup-form"); | ||||
|     const $syncServerHost = $("#sync-server-host"); | ||||
|     const $syncServerTimeout = $("#sync-server-timeout"); | ||||
|     const $syncProxy = $("#sync-proxy"); | ||||
|     const $testSyncButton = $("#test-sync-button"); | ||||
|     const $syncToServerButton = $("#sync-to-server-button"); | ||||
|  | ||||
|     function optionsLoaded(options) { | ||||
|         $syncServerHost.val(options['syncServerHost']); | ||||
|         $syncServerTimeout.val(options['syncServerTimeout']); | ||||
|         $syncProxy.val(options['syncProxy']); | ||||
|     } | ||||
|  | ||||
|     $form.submit(() => { | ||||
|         saveOptions({ | ||||
|             'syncServerHost': $syncServerHost.val(), | ||||
|             'syncServerTimeout': $syncServerTimeout.val(), | ||||
|             'syncProxy': $syncProxy.val() | ||||
|         }); | ||||
|  | ||||
|         return false; | ||||
|     }); | ||||
|  | ||||
|     $testSyncButton.click(async () => { | ||||
|         const result = await server.post('sync/test'); | ||||
|  | ||||
|         if (result.connection === "Success") { | ||||
|             infoService.showMessage("Sync server handshake has been successful"); | ||||
|         } | ||||
|         else { | ||||
|             infoService.showError("Sync server handshake failed, error: " + result.error); | ||||
|         } | ||||
|     }); | ||||
|  | ||||
|     $syncToServerButton.click(async () => { | ||||
|         const resp = await server.post("setup/sync-to-server"); | ||||
|  | ||||
|         if (resp.success) { | ||||
|             infoService.showMessage("Sync has been established to the server instance. It will take some time to finish."); | ||||
|         } | ||||
|         else { | ||||
|             infoService.showError('Sync setup failed: ' + resp.error); | ||||
|         } | ||||
|     }); | ||||
|  | ||||
|     return { | ||||
|         optionsLoaded | ||||
|     }; | ||||
| })()); | ||||
|  | ||||
| addTabHandler((async function () { | ||||
|     const $forceFullSyncButton = $("#force-full-sync-button"); | ||||
|     const $fillSyncRowsButton = $("#fill-sync-rows-button"); | ||||
|   | ||||
| @@ -1,74 +0,0 @@ | ||||
| import treeService from '../services/tree.js'; | ||||
| import server from '../services/server.js'; | ||||
|  | ||||
| const $dialog = $("#recent-notes-dialog"); | ||||
| const $searchInput = $('#recent-notes-search-input'); | ||||
|  | ||||
| function addRecentNote(branchId, notePath) { | ||||
|     setTimeout(async () => { | ||||
|         // we include the note into recent list only if the user stayed on the note at least 5 seconds | ||||
|         if (notePath && notePath === treeService.getCurrentNotePath()) { | ||||
|             const result = await server.put('recent-notes/' + branchId + '/' + encodeURIComponent(notePath)); | ||||
|         } | ||||
|     }, 1500); | ||||
| } | ||||
|  | ||||
| async function showDialog() { | ||||
|     glob.activeDialog = $dialog; | ||||
|  | ||||
|     $dialog.dialog({ | ||||
|         modal: true, | ||||
|         width: 800, | ||||
|         height: 100, | ||||
|         position: { my: "center top+100", at: "top", of: window } | ||||
|     }); | ||||
|  | ||||
|     $searchInput.val(''); | ||||
|  | ||||
|     const result = await server.get('recent-notes'); | ||||
|  | ||||
|     // remove the current note | ||||
|     const recNotes = result.filter(note => note.notePath !== treeService.getCurrentNotePath()); | ||||
|  | ||||
|     const items = recNotes.map(rn => { | ||||
|         return { | ||||
|             label: rn.title, | ||||
|             value: rn.notePath | ||||
|         }; | ||||
|     }); | ||||
|  | ||||
|     $searchInput.autocomplete({ | ||||
|         source: items, | ||||
|         minLength: 0, | ||||
|         autoFocus: true, | ||||
|         select: function (event, ui) { | ||||
|             treeService.activateNode(ui.item.value); | ||||
|  | ||||
|             $searchInput.autocomplete('destroy'); | ||||
|             $dialog.dialog('close'); | ||||
|         }, | ||||
|         focus: function (event, ui) { | ||||
|             event.preventDefault(); | ||||
|         }, | ||||
|         close: function (event, ui) { | ||||
|             if (event.keyCode === 27) { // escape closes dialog | ||||
|                 $searchInput.autocomplete('destroy'); | ||||
|                 $dialog.dialog('close'); | ||||
|             } | ||||
|             else { | ||||
|                 // keep autocomplete open | ||||
|                 // we're kind of abusing autocomplete to work in a way which it's not designed for | ||||
|                 $searchInput.autocomplete("search", ""); | ||||
|             } | ||||
|         }, | ||||
|         create: () => $searchInput.autocomplete("search", ""), | ||||
|         classes: { | ||||
|             "ui-autocomplete": "recent-notes-autocomplete" | ||||
|         } | ||||
|     }); | ||||
| } | ||||
|  | ||||
| export default { | ||||
|     showDialog, | ||||
|     addRecentNote | ||||
| }; | ||||
| @@ -7,6 +7,7 @@ class NoteShort { | ||||
|         this.type = row.type; | ||||
|         this.mime = row.mime; | ||||
|         this.archived = row.archived; | ||||
|         this.cssClass = row.cssClass; | ||||
|     } | ||||
|  | ||||
|     isJson() { | ||||
|   | ||||
							
								
								
									
										5
									
								
								src/public/javascripts/services/bootstrap.js
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										5
									
								
								src/public/javascripts/services/bootstrap.js
									
									
									
									
										vendored
									
									
								
							| @@ -1,10 +1,9 @@ | ||||
| import addLinkDialog from '../dialogs/add_link.js'; | ||||
| import jumpToNoteDialog from '../dialogs/jump_to_note.js'; | ||||
| import labelsDialog from '../dialogs/labels.js'; | ||||
| import attributesDialog from '../dialogs/attributes.js'; | ||||
| import noteRevisionsDialog from '../dialogs/note_revisions.js'; | ||||
| import noteSourceDialog from '../dialogs/note_source.js'; | ||||
| import recentChangesDialog from '../dialogs/recent_changes.js'; | ||||
| import recentNotesDialog from '../dialogs/recent_notes.js'; | ||||
| import optionsDialog from '../dialogs/options.js'; | ||||
| import sqlConsoleDialog from '../dialogs/sql_console.js'; | ||||
|  | ||||
| @@ -36,6 +35,8 @@ import libraryLoader from "./library_loader.js"; | ||||
| window.glob.getCurrentNode = treeService.getCurrentNode; | ||||
| window.glob.getHeaders = server.getHeaders; | ||||
| window.glob.showAddLinkDialog = addLinkDialog.showDialog; | ||||
| // this is required by CKEditor when uploading images | ||||
| window.glob.noteChanged = noteDetailService.noteChanged; | ||||
|  | ||||
| // required for ESLint plugin | ||||
| window.glob.getCurrentNote = noteDetailService.getCurrentNote; | ||||
|   | ||||
| @@ -1,8 +1,14 @@ | ||||
| import ScriptContext from "./script_context.js"; | ||||
| import server from "./server.js"; | ||||
|  | ||||
| async function executeBundle(bundle) { | ||||
|     const apiContext = ScriptContext(bundle.note, bundle.allNotes); | ||||
| async function getAndExecuteBundle(noteId, originEntity = null) { | ||||
|     const bundle = await server.get('script/bundle/' + noteId); | ||||
|  | ||||
|     await executeBundle(bundle, originEntity); | ||||
| } | ||||
|  | ||||
| async function executeBundle(bundle, originEntity) { | ||||
|     const apiContext = ScriptContext(bundle.note, bundle.allNotes, originEntity); | ||||
|  | ||||
|     return await (function () { | ||||
|         return eval(`const apiContext = this; (async function() { ${bundle.script}\r\n})()`); | ||||
| @@ -17,7 +23,17 @@ async function executeStartupBundles() { | ||||
|     } | ||||
| } | ||||
|  | ||||
| async function executeRelationBundles(note, relationName) { | ||||
|     const bundlesToRun = await server.get("script/relation/" + note.noteId + "/" + relationName); | ||||
|  | ||||
|     for (const bundle of bundlesToRun) { | ||||
|         await executeBundle(bundle, note); | ||||
|     } | ||||
| } | ||||
|  | ||||
| export default { | ||||
|     executeBundle, | ||||
|     executeStartupBundles | ||||
|     getAndExecuteBundle, | ||||
|     executeStartupBundles, | ||||
|     executeRelationBundles | ||||
| } | ||||
| @@ -121,7 +121,7 @@ const contextMenuOptions = { | ||||
|         $tree.contextmenu("enableEntry", "pasteInto", clipboardIds.length > 0 && note.type !== 'search'); | ||||
|         $tree.contextmenu("enableEntry", "importBranch", note.type !== 'search'); | ||||
|         $tree.contextmenu("enableEntry", "exportBranch", note.type !== 'search'); | ||||
|         $tree.contextmenu("enableEntry", "editBranchPrefix", parentNote.type !== 'search'); | ||||
|         $tree.contextmenu("enableEntry", "editBranchPrefix", isNotRoot && parentNote.type !== 'search'); | ||||
|  | ||||
|         // Activate node on right-click | ||||
|         node.setActive(); | ||||
|   | ||||
| @@ -6,13 +6,12 @@ import zoomService from "./zoom.js"; | ||||
| import noteRevisionsDialog from "../dialogs/note_revisions.js"; | ||||
| import optionsDialog from "../dialogs/options.js"; | ||||
| import addLinkDialog from "../dialogs/add_link.js"; | ||||
| import recentNotesDialog from "../dialogs/recent_notes.js"; | ||||
| import jumpToNoteDialog from "../dialogs/jump_to_note.js"; | ||||
| import noteSourceDialog from "../dialogs/note_source.js"; | ||||
| import recentChangesDialog from "../dialogs/recent_changes.js"; | ||||
| import sqlConsoleDialog from "../dialogs/sql_console.js"; | ||||
| import searchNotesService from "./search_notes.js"; | ||||
| import labelsDialog from "../dialogs/labels.js"; | ||||
| import attributesDialog from "../dialogs/attributes.js"; | ||||
| import protectedSessionService from "./protected_session.js"; | ||||
|  | ||||
| function registerEntrypoints() { | ||||
| @@ -35,14 +34,11 @@ function registerEntrypoints() { | ||||
|     $("#protected-session-on").click(protectedSessionService.enterProtectedSession); | ||||
|     $("#protected-session-off").click(protectedSessionService.leaveProtectedSession); | ||||
|  | ||||
|     $("#recent-notes-button").click(recentNotesDialog.showDialog); | ||||
|     utils.bindShortcut('ctrl+e', recentNotesDialog.showDialog); | ||||
|  | ||||
|     $("#toggle-search-button").click(searchNotesService.toggleSearch); | ||||
|     utils.bindShortcut('ctrl+s', searchNotesService.toggleSearch); | ||||
|  | ||||
|     $(".show-labels-button").click(labelsDialog.showDialog); | ||||
|     utils.bindShortcut('alt+l', labelsDialog.showDialog); | ||||
|     $(".show-attributes-button").click(attributesDialog.showDialog); | ||||
|     utils.bindShortcut('alt+a', attributesDialog.showDialog); | ||||
|  | ||||
|     $("#options-button").click(optionsDialog.showDialog); | ||||
|  | ||||
|   | ||||
| @@ -3,7 +3,7 @@ import noteDetailText from './note_detail_text.js'; | ||||
| import treeUtils from './tree_utils.js'; | ||||
|  | ||||
| function getNotePathFromLink(url) { | ||||
|     const notePathMatch = /#([A-Za-z0-9/]+)$/.exec(url); | ||||
|     const notePathMatch = /#root([A-Za-z0-9/]*)$/.exec(url); | ||||
|  | ||||
|     if (notePathMatch === null) { | ||||
|         return null; | ||||
| @@ -13,8 +13,8 @@ function getNotePathFromLink(url) { | ||||
|     } | ||||
| } | ||||
|  | ||||
| function getNodePathFromLabel(label) { | ||||
|     const notePathMatch = / \(([A-Za-z0-9/]+)\)/.exec(label); | ||||
| function getNotePathFromLabel(label) { | ||||
|     const notePathMatch = / \(([#A-Za-z0-9/]+)\)/.exec(label); | ||||
|  | ||||
|     if (notePathMatch !== null) { | ||||
|         return notePathMatch[1]; | ||||
| @@ -23,7 +23,7 @@ function getNodePathFromLabel(label) { | ||||
|     return null; | ||||
| } | ||||
|  | ||||
| async function createNoteLink(notePath, noteTitle) { | ||||
| async function createNoteLink(notePath, noteTitle = null) { | ||||
|     if (!noteTitle) { | ||||
|         const noteId = treeUtils.getNoteIdFromNotePath(notePath); | ||||
|  | ||||
| @@ -90,6 +90,18 @@ function addTextToEditor(text) { | ||||
|     doc.enqueueChanges(() => editor.data.insertText(text), doc.selection); | ||||
| } | ||||
|  | ||||
| ko.bindingHandlers.noteLink = { | ||||
|     init: async function(element, valueAccessor, allBindings, viewModel, bindingContext) { | ||||
|         const noteId = ko.unwrap(valueAccessor()); | ||||
|  | ||||
|         if (noteId) { | ||||
|             const link = await createNoteLink(noteId); | ||||
|  | ||||
|             $(element).append(link); | ||||
|         } | ||||
|     } | ||||
| }; | ||||
|  | ||||
| // when click on link popup, in case of internal link, just go the the referenced note instead of default behavior | ||||
| // of opening the link in new window/tab | ||||
| $(document).on('click', "a[action='note']", goToLink); | ||||
| @@ -97,7 +109,7 @@ $(document).on('click', 'div.popover-content a, div.ui-tooltip-content a', goToL | ||||
| $(document).on('dblclick', '#note-detail-text a', goToLink); | ||||
|  | ||||
| export default { | ||||
|     getNodePathFromLabel, | ||||
|     getNotePathFromLabel, | ||||
|     getNotePathFromLink, | ||||
|     createNoteLink, | ||||
|     addLinkToEditor, | ||||
|   | ||||
| @@ -1,8 +1,9 @@ | ||||
| import utils from './utils.js'; | ||||
| import infoService from "./info.js"; | ||||
|  | ||||
| const $changesToPushCount = $("#changes-to-push-count"); | ||||
| const $outstandingSyncsCount = $("#outstanding-syncs-count"); | ||||
|  | ||||
| const syncMessageHandlers = []; | ||||
| const messageHandlers = []; | ||||
|  | ||||
| let ws; | ||||
| @@ -25,9 +26,17 @@ function subscribeToMessages(messageHandler) { | ||||
|     messageHandlers.push(messageHandler); | ||||
| } | ||||
|  | ||||
| function subscribeToSyncMessages(messageHandler) { | ||||
|     syncMessageHandlers.push(messageHandler); | ||||
| } | ||||
|  | ||||
| function handleMessage(event) { | ||||
|     const message = JSON.parse(event.data); | ||||
|  | ||||
|     for (const messageHandler of messageHandlers) { | ||||
|         messageHandler(message); | ||||
|     } | ||||
|  | ||||
|     if (message.type === 'sync') { | ||||
|         lastPingTs = new Date().getTime(); | ||||
|  | ||||
| @@ -39,11 +48,11 @@ function handleMessage(event) { | ||||
|  | ||||
|         const syncData = message.data.filter(sync => sync.sourceId !== glob.sourceId); | ||||
|  | ||||
|         for (const messageHandler of messageHandlers) { | ||||
|             messageHandler(syncData); | ||||
|         for (const syncMessageHandler of syncMessageHandlers) { | ||||
|             syncMessageHandler(syncData); | ||||
|         } | ||||
|  | ||||
|         $changesToPushCount.html(message.changesToPushCount); | ||||
|         $outstandingSyncsCount.html(message.outstandingSyncs); | ||||
|     } | ||||
|     else if (message.type === 'sync-hash-check-failed') { | ||||
|         infoService.showError("Sync check failed!", 60000); | ||||
| @@ -73,26 +82,10 @@ setTimeout(() => { | ||||
|  | ||||
|     lastSyncId = glob.maxSyncIdAtLoad; | ||||
|     lastPingTs = new Date().getTime(); | ||||
|     let connectionBrokenNotification = null; | ||||
|  | ||||
|     setInterval(async () => { | ||||
|         if (new Date().getTime() - lastPingTs > 30000) { | ||||
|             if (!connectionBrokenNotification) { | ||||
|                 connectionBrokenNotification = $.notify({ | ||||
|                     // options | ||||
|                     message: "Lost connection to server" | ||||
|                 },{ | ||||
|                     // options | ||||
|                     type: 'danger', | ||||
|                     delay: 100000000 // keep it until we explicitly close it | ||||
|                 }); | ||||
|             } | ||||
|         } | ||||
|         else if (connectionBrokenNotification) { | ||||
|             await connectionBrokenNotification.close(); | ||||
|             connectionBrokenNotification = null; | ||||
|  | ||||
|             infoService.showMessage("Re-connected to server"); | ||||
|             console.log("Lost connection to server"); | ||||
|         } | ||||
|  | ||||
|         ws.send(JSON.stringify({ | ||||
| @@ -104,5 +97,6 @@ setTimeout(() => { | ||||
|  | ||||
| export default { | ||||
|     logError, | ||||
|     subscribeToMessages | ||||
|     subscribeToMessages, | ||||
|     subscribeToSyncMessages | ||||
| }; | ||||
							
								
								
									
										54
									
								
								src/public/javascripts/services/note_autocomplete.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										54
									
								
								src/public/javascripts/services/note_autocomplete.js
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,54 @@ | ||||
| import server from "./server.js"; | ||||
|  | ||||
| async function initNoteAutocomplete($el) { | ||||
|     if (!$el.hasClass("ui-autocomplete-input")) { | ||||
|         const $showRecentNotesButton = $("<span>") | ||||
|             .addClass("input-group-addon show-recent-notes-button") | ||||
|             .prop("title", "Show recent notes"); | ||||
|  | ||||
|         $el.after($showRecentNotesButton); | ||||
|  | ||||
|         $showRecentNotesButton.click(() => $el.autocomplete("search", "")); | ||||
|  | ||||
|         await $el.autocomplete({ | ||||
|             appendTo: $el.parent().parent(), | ||||
|             source: async function (request, response) { | ||||
|                 const result = await server.get('autocomplete?query=' + encodeURIComponent(request.term)); | ||||
|  | ||||
|                 if (result.length > 0) { | ||||
|                     response(result.map(row => { | ||||
|                         return { | ||||
|                             label: row.label, | ||||
|                             value: row.label + ' (' + row.value + ')' | ||||
|                         } | ||||
|                     })); | ||||
|                 } | ||||
|                 else { | ||||
|                     response([{ | ||||
|                         label: "No results", | ||||
|                         value: "No results" | ||||
|                     }]); | ||||
|                 } | ||||
|             }, | ||||
|             minLength: 0, | ||||
|             change: function (event, ui) { | ||||
|                 $el.trigger("change"); | ||||
|             }, | ||||
|             select: function (event, ui) { | ||||
|                 if (ui.item.value === 'No results') { | ||||
|                     return false; | ||||
|                 } | ||||
|             } | ||||
|         }); | ||||
|     } | ||||
| } | ||||
|  | ||||
| ko.bindingHandlers.noteAutocomplete = { | ||||
|     init: function(element, valueAccessor, allBindings, viewModel, bindingContext) { | ||||
|         initNoteAutocomplete($(element)); | ||||
|     } | ||||
| }; | ||||
|  | ||||
| export default { | ||||
|     initNoteAutocomplete | ||||
| } | ||||
| @@ -7,6 +7,7 @@ import utils from './utils.js'; | ||||
| import server from './server.js'; | ||||
| import messagingService from "./messaging.js"; | ||||
| import infoService from "./info.js"; | ||||
| import linkService from "./link.js"; | ||||
| import treeCache from "./tree_cache.js"; | ||||
| import NoteFull from "../entities/note_full.js"; | ||||
| import noteDetailCode from './note_detail_code.js'; | ||||
| @@ -14,6 +15,8 @@ import noteDetailText from './note_detail_text.js'; | ||||
| import noteDetailFile from './note_detail_file.js'; | ||||
| import noteDetailSearch from './note_detail_search.js'; | ||||
| import noteDetailRender from './note_detail_render.js'; | ||||
| import bundleService from "./bundle.js"; | ||||
| import noteAutocompleteService from "./note_autocomplete.js"; | ||||
|  | ||||
| const $noteTitle = $("#note-title"); | ||||
|  | ||||
| @@ -24,9 +27,11 @@ const $unprotectButton = $("#unprotect-button"); | ||||
| const $noteDetailWrapper = $("#note-detail-wrapper"); | ||||
| const $noteDetailComponentWrapper = $("#note-detail-component-wrapper"); | ||||
| const $noteIdDisplay = $("#note-id-display"); | ||||
| const $labelList = $("#label-list"); | ||||
| const $labelListInner = $("#label-list-inner"); | ||||
| const $attributeList = $("#attribute-list"); | ||||
| const $attributeListInner = $("#attribute-list-inner"); | ||||
| const $childrenOverview = $("#children-overview"); | ||||
| const $scriptArea = $("#note-detail-script-area"); | ||||
| const $promotedAttributesContainer = $("#note-detail-promoted-attributes"); | ||||
|  | ||||
| let currentNote = null; | ||||
|  | ||||
| @@ -178,9 +183,13 @@ async function loadNoteDetail(noteId) { | ||||
|     // after loading new note make sure editor is scrolled to the top | ||||
|     $noteDetailWrapper.scrollTop(0); | ||||
|  | ||||
|     const labels = await loadLabelList(); | ||||
|     $scriptArea.html(''); | ||||
|  | ||||
|     const hideChildrenOverview = labels.some(label => label.name === 'hideChildrenOverview'); | ||||
|     await bundleService.executeRelationBundles(getCurrentNote(), 'runOnNoteView'); | ||||
|  | ||||
|     const attributes = await loadAttributes(); | ||||
|  | ||||
|     const hideChildrenOverview = attributes.some(attr => attr.type === 'label' && attr.name === 'hideChildrenOverview'); | ||||
|     await showChildrenOverview(hideChildrenOverview); | ||||
| } | ||||
|  | ||||
| @@ -209,25 +218,207 @@ async function showChildrenOverview(hideChildrenOverview) { | ||||
|     $childrenOverview.show(); | ||||
| } | ||||
|  | ||||
| async function loadLabelList() { | ||||
| async function loadAttributes() { | ||||
|     $promotedAttributesContainer.empty(); | ||||
|     $attributeList.hide(); | ||||
|  | ||||
|     const noteId = getCurrentNoteId(); | ||||
|  | ||||
|     const labels = await server.get('notes/' + noteId + '/labels'); | ||||
|     const attributes = await server.get('notes/' + noteId + '/attributes'); | ||||
|  | ||||
|     $labelListInner.html(''); | ||||
|     const promoted = attributes.filter(attr => (attr.type === 'label-definition' || attr.type === 'relation-definition') && attr.value.isPromoted); | ||||
|  | ||||
|     if (labels.length > 0) { | ||||
|         for (const label of labels) { | ||||
|             $labelListInner.append(utils.formatLabel(label) + " "); | ||||
|     let idx = 1; | ||||
|  | ||||
|     async function createRow(definitionAttr, valueAttr) { | ||||
|         const definition = definitionAttr.value; | ||||
|         const inputId = "promoted-input-" + idx; | ||||
|         const $tr = $("<tr>"); | ||||
|         const $labelCell = $("<th>").append(valueAttr.name); | ||||
|         const $input = $("<input>") | ||||
|             .prop("id", inputId) | ||||
|             .prop("tabindex", definitionAttr.position) | ||||
|             .prop("attribute-id", valueAttr.isOwned ? valueAttr.attributeId : '') // if not owned, we'll force creation of a new attribute instead of updating the inherited one | ||||
|             .prop("attribute-type", valueAttr.type) | ||||
|             .prop("attribute-name", valueAttr.name) | ||||
|             .prop("value", valueAttr.value) | ||||
|             .addClass("form-control") | ||||
|             .addClass("promoted-attribute-input"); | ||||
|  | ||||
|         idx++; | ||||
|  | ||||
|         const $inputCell = $("<td>").append($("<div>").addClass("input-group").append($input)); | ||||
|  | ||||
|         const $actionCell = $("<td>"); | ||||
|         const $multiplicityCell = $("<td>"); | ||||
|  | ||||
|         $tr | ||||
|             .append($labelCell) | ||||
|             .append($inputCell) | ||||
|             .append($actionCell) | ||||
|             .append($multiplicityCell); | ||||
|  | ||||
|         if (valueAttr.type === 'label') { | ||||
|             if (definition.labelType === 'text') { | ||||
|                 $input.prop("type", "text"); | ||||
|  | ||||
|                 // no need to await for this, can be done asynchronously | ||||
|                 server.get('attributes/values/' + encodeURIComponent(valueAttr.name)).then(attributeValues => { | ||||
|                     if (attributeValues.length === 0) { | ||||
|                         return; | ||||
|                     } | ||||
|  | ||||
|                     $input.autocomplete({ | ||||
|                         // shouldn't be required and autocomplete should just accept array of strings, but that fails | ||||
|                         // because we have overriden filter() function in autocomplete.js | ||||
|                         source: attributeValues.map(attribute => { | ||||
|                             return { | ||||
|                                 attribute: attribute, | ||||
|                                 value: attribute | ||||
|                             } | ||||
|                         }), | ||||
|                         minLength: 0 | ||||
|                     }); | ||||
|  | ||||
|                     $input.focus(() => $input.autocomplete("search", "")); | ||||
|                 }); | ||||
|             } | ||||
|             else if (definition.labelType === 'number') { | ||||
|                 $input.prop("type", "number"); | ||||
|             } | ||||
|             else if (definition.labelType === 'boolean') { | ||||
|                 $input.prop("type", "checkbox"); | ||||
|  | ||||
|                 if (valueAttr.value === "true") { | ||||
|                     $input.prop("checked", "checked"); | ||||
|                 } | ||||
|             } | ||||
|             else if (definition.labelType === 'date') { | ||||
|                 $input.prop("type", "text"); | ||||
|  | ||||
|                 $input.datepicker({ | ||||
|                     changeMonth: true, | ||||
|                     changeYear: true, | ||||
|                     dateFormat: "yy-mm-dd" | ||||
|                 }); | ||||
|  | ||||
|                 const $todayButton = $("<button>").addClass("btn btn-small").text("Today").click(() => { | ||||
|                     $input.val(utils.formatDateISO(new Date())); | ||||
|                     $input.trigger("change"); | ||||
|                 }); | ||||
|  | ||||
|                 $actionCell.append($todayButton); | ||||
|             } | ||||
|             else { | ||||
|                 messagingService.logError("Unknown labelType=" + definitionAttr.labelType); | ||||
|             } | ||||
|         } | ||||
|         else if (valueAttr.type === 'relation') { | ||||
|             if (valueAttr.value) { | ||||
|                 $input.val((await treeUtils.getNoteTitle(valueAttr.value) + " (" + valueAttr.value + ")")); | ||||
|             } | ||||
|  | ||||
|             // no need to wait for this | ||||
|             noteAutocompleteService.initNoteAutocomplete($input); | ||||
|         } | ||||
|         else { | ||||
|             messagingService.logError("Unknown attribute type=" + valueAttr.type); | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         $labelList.show(); | ||||
|     } | ||||
|     else { | ||||
|         $labelList.hide(); | ||||
|         if (definition.multiplicityType === "multivalue") { | ||||
|             const addButton = $("<span>") | ||||
|                 .addClass("glyphicon glyphicon-plus pointer") | ||||
|                 .prop("title", "Add new attribute") | ||||
|                 .click(async () => { | ||||
|                 const $new = await createRow(definitionAttr, { | ||||
|                     attributeId: "", | ||||
|                     type: valueAttr.type, | ||||
|                     name: definitionAttr.name, | ||||
|                     value: "" | ||||
|                 }); | ||||
|  | ||||
|                 $tr.after($new); | ||||
|  | ||||
|                 $new.find('input').focus(); | ||||
|             }); | ||||
|  | ||||
|             const removeButton = $("<span>") | ||||
|                 .addClass("glyphicon glyphicon-trash pointer") | ||||
|                 .prop("title", "Remove this attribute") | ||||
|                 .click(async () => { | ||||
|                 if (valueAttr.attributeId) { | ||||
|                     await server.remove("notes/" + noteId + "/attributes/" + valueAttr.attributeId); | ||||
|                 } | ||||
|  | ||||
|                 $tr.remove(); | ||||
|             }); | ||||
|  | ||||
|             $multiplicityCell.append(addButton).append("   ").append(removeButton); | ||||
|         } | ||||
|  | ||||
|         return $tr; | ||||
|     } | ||||
|  | ||||
|     return labels; | ||||
|     if (promoted.length > 0) { | ||||
|         const $tbody = $("<tbody>"); | ||||
|  | ||||
|         for (const definitionAttr of promoted) { | ||||
|             const definitionType = definitionAttr.type; | ||||
|             const valueType = definitionType.substr(0, definitionType.length - 11); | ||||
|  | ||||
|             let valueAttrs = attributes.filter(el => el.name === definitionAttr.name && el.type === valueType); | ||||
|  | ||||
|             if (valueAttrs.length === 0) { | ||||
|                 valueAttrs.push({ | ||||
|                     attributeId: "", | ||||
|                     type: valueType, | ||||
|                     name: definitionAttr.name, | ||||
|                     value: "" | ||||
|                 }); | ||||
|             } | ||||
|  | ||||
|             if (definitionAttr.value.multiplicityType === 'singlevalue') { | ||||
|                 valueAttrs = valueAttrs.slice(0, 1); | ||||
|             } | ||||
|  | ||||
|             for (const valueAttr of valueAttrs) { | ||||
|                 const $tr = await createRow(definitionAttr, valueAttr); | ||||
|  | ||||
|                 $tbody.append($tr); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         // we replace the whole content in one step so there can't be any race conditions | ||||
|         // (previously we saw promoted attributes doubling) | ||||
|         $promotedAttributesContainer.empty().append($tbody); | ||||
|     } | ||||
|     else { | ||||
|         $attributeListInner.html(''); | ||||
|  | ||||
|         if (attributes.length > 0) { | ||||
|             for (const attribute of attributes) { | ||||
|                 if (attribute.type === 'label') { | ||||
|                     $attributeListInner.append(utils.formatLabel(attribute) + " "); | ||||
|                 } | ||||
|                 else if (attribute.type === 'relation') { | ||||
|                     $attributeListInner.append(attribute.name + "="); | ||||
|                     $attributeListInner.append(await linkService.createNoteLink(attribute.value)); | ||||
|                     $attributeListInner.append(" "); | ||||
|                 } | ||||
|                 else if (attribute.type === 'label-definition' || attribute.type === 'relation-definition') { | ||||
|                     $attributeListInner.append(attribute.name + " definition "); | ||||
|                 } | ||||
|                 else { | ||||
|                     messagingService.logError("Unknown attr type: " + attribute.type); | ||||
|                 } | ||||
|             } | ||||
|  | ||||
|             $attributeList.show(); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     return attributes; | ||||
| } | ||||
|  | ||||
| async function loadNote(noteId) { | ||||
| @@ -242,7 +433,7 @@ function focus() { | ||||
|     getComponent(note.type).focus(); | ||||
| } | ||||
|  | ||||
| messagingService.subscribeToMessages(syncData => { | ||||
| messagingService.subscribeToSyncMessages(syncData => { | ||||
|     if (syncData.some(sync => sync.entityName === 'notes' && sync.entityId === getCurrentNoteId())) { | ||||
|         infoService.showMessage('Reloading note because of background changes'); | ||||
|  | ||||
| @@ -250,6 +441,35 @@ messagingService.subscribeToMessages(syncData => { | ||||
|     } | ||||
| }); | ||||
|  | ||||
| $promotedAttributesContainer.on('change', '.promoted-attribute-input', async event => { | ||||
|     const $attr = $(event.target); | ||||
|  | ||||
|     let value; | ||||
|  | ||||
|     if ($attr.prop("type") === "checkbox") { | ||||
|         value = $attr.is(':checked') ? "true" : "false"; | ||||
|     } | ||||
|     else if ($attr.prop("attribute-type") === "relation") { | ||||
|         if ($attr.val()) { | ||||
|             value = treeUtils.getNoteIdFromNotePath(linkService.getNotePathFromLabel($attr.val())); | ||||
|         } | ||||
|     } | ||||
|     else { | ||||
|         value = $attr.val(); | ||||
|     } | ||||
|  | ||||
|     const result = await server.put("notes/" + getCurrentNoteId() + "/attribute", { | ||||
|         attributeId: $attr.prop("attribute-id"), | ||||
|         type: $attr.prop("attribute-type"), | ||||
|         name: $attr.prop("attribute-name"), | ||||
|         value: value | ||||
|     }); | ||||
|  | ||||
|     $attr.prop("attribute-id", result.attributeId); | ||||
|  | ||||
|     infoService.showMessage("Attribute has been saved."); | ||||
| }); | ||||
|  | ||||
| $(document).ready(() => { | ||||
|     $noteTitle.on('input', () => { | ||||
|         noteChanged(); | ||||
| @@ -278,7 +498,7 @@ export default { | ||||
|     getCurrentNoteId, | ||||
|     newNoteCreated, | ||||
|     focus, | ||||
|     loadLabelList, | ||||
|     loadAttributes, | ||||
|     saveNote, | ||||
|     saveNoteIfChanged, | ||||
|     noteChanged | ||||
|   | ||||
| @@ -32,7 +32,7 @@ async function show() { | ||||
|             lint: true, | ||||
|             gutters: ["CodeMirror-lint-markers"], | ||||
|             lineNumbers: true, | ||||
|             tabindex: 2 // so that tab from title will lead to code editor focus | ||||
|             tabindex: 100 | ||||
|         }); | ||||
|  | ||||
|         codeEditor.on('change', noteDetailService.noteChanged); | ||||
| @@ -75,9 +75,7 @@ async function executeCurrentNote() { | ||||
|     const currentNote = noteDetailService.getCurrentNote(); | ||||
|  | ||||
|     if (currentNote.mime.endsWith("env=frontend")) { | ||||
|         const bundle = await server.get('script/bundle/' + noteDetailService.getCurrentNoteId()); | ||||
|  | ||||
|         bundleService.executeBundle(bundle); | ||||
|         await bundleService.getAndExecuteBundle(noteDetailService.getCurrentNoteId()); | ||||
|     } | ||||
|  | ||||
|     if (currentNote.mime.endsWith("env=backend")) { | ||||
|   | ||||
| @@ -14,13 +14,13 @@ const $fileOpen = $("#file-open"); | ||||
| async function show() { | ||||
|     const currentNote = noteDetailService.getCurrentNote(); | ||||
|  | ||||
|     const labels = await server.get('notes/' + currentNote.noteId + '/labels'); | ||||
|     const labelMap = utils.toObject(labels, l => [l.name, l.value]); | ||||
|     const attributes = await server.get('notes/' + currentNote.noteId + '/attributes'); | ||||
|     const attributeMap = utils.toObject(attributes, l => [l.name, l.value]); | ||||
|  | ||||
|     $noteDetailFile.show(); | ||||
|  | ||||
|     $fileFileName.text(labelMap.original_file_name); | ||||
|     $fileFileSize.text(labelMap.file_size + " bytes"); | ||||
|     $fileFileName.text(attributeMap.original_file_name); | ||||
|     $fileFileSize.text(attributeMap.file_size + " bytes"); | ||||
|     $fileFileType.text(currentNote.mime); | ||||
| } | ||||
|  | ||||
|   | ||||
| @@ -2,14 +2,21 @@ import treeService from './tree.js'; | ||||
| import server from './server.js'; | ||||
| import utils from './utils.js'; | ||||
| import infoService from './info.js'; | ||||
| import linkService from './link.js'; | ||||
|  | ||||
| function ScriptApi(startNote, currentNote) { | ||||
| function ScriptApi(startNote, currentNote, originEntity = null) { | ||||
|     const $pluginButtons = $("#plugin-buttons"); | ||||
|  | ||||
|     async function activateNote(notePath) { | ||||
|         await treeService.activateNode(notePath); | ||||
|     } | ||||
|  | ||||
|     async function activateNewNote(notePath) { | ||||
|         await treeService.reload(); | ||||
|  | ||||
|         await treeService.activateNode(notePath, true); | ||||
|     } | ||||
|  | ||||
|     function addButtonToToolbar(buttonId, button) { | ||||
|         $("#" + buttonId).remove(); | ||||
|  | ||||
| @@ -42,7 +49,9 @@ function ScriptApi(startNote, currentNote) { | ||||
|             script: script, | ||||
|             params: prepareParams(params), | ||||
|             startNoteId: startNote.noteId, | ||||
|             currentNoteId: currentNote.noteId | ||||
|             currentNoteId: currentNote.noteId, | ||||
|             originEntityName: originEntity ? originEntity.constructor.tableName : null, | ||||
|             originEntityId: originEntity ? originEntity.noteId : null | ||||
|         }); | ||||
|  | ||||
|         return ret.executionResult; | ||||
| @@ -51,15 +60,19 @@ function ScriptApi(startNote, currentNote) { | ||||
|     return { | ||||
|         startNote: startNote, | ||||
|         currentNote: currentNote, | ||||
|         originEntity: originEntity, | ||||
|         addButtonToToolbar, | ||||
|         activateNote, | ||||
|         activateNewNote, | ||||
|         getInstanceName: () => window.glob.instanceName, | ||||
|         runOnServer, | ||||
|         formatDateISO: utils.formatDateISO, | ||||
|         parseDate: utils.parseDate, | ||||
|         showMessage: infoService.showMessage, | ||||
|         showError: infoService.showError, | ||||
|         reloadTree: treeService.reload | ||||
|         reloadTree: treeService.reload, // deprecated | ||||
|         refreshTree: treeService.reload, | ||||
|         createNoteLink: linkService.createNoteLink | ||||
|     } | ||||
| } | ||||
|  | ||||
|   | ||||
| @@ -1,13 +1,13 @@ | ||||
| import ScriptApi from './script_api.js'; | ||||
| import utils from './utils.js'; | ||||
|  | ||||
| function ScriptContext(startNote, allNotes) { | ||||
| function ScriptContext(startNote, allNotes, originEntity = null) { | ||||
|     const modules = {}; | ||||
|  | ||||
|     return { | ||||
|         modules: modules, | ||||
|         notes: utils.toObject(allNotes, note => [note.noteId, note]), | ||||
|         apis: utils.toObject(allNotes, note => [note.noteId, ScriptApi(startNote, note)]), | ||||
|         apis: utils.toObject(allNotes, note => [note.noteId, ScriptApi(startNote, note, originEntity)]), | ||||
|         require: moduleNoteIds => { | ||||
|             return moduleName => { | ||||
|                 const candidates = allNotes.filter(note => moduleNoteIds.includes(note.noteId)); | ||||
|   | ||||
| @@ -4,14 +4,30 @@ import linkService from "./link.js"; | ||||
|  | ||||
| function setupTooltip() { | ||||
|     $(document).tooltip({ | ||||
|         items: "#note-detail-text a", | ||||
|         items: "body a", | ||||
|         content: function (callback) { | ||||
|             const notePath = linkService.getNotePathFromLink($(this).attr("href")); | ||||
|             let notePath = linkService.getNotePathFromLink($(this).attr("href")); | ||||
|  | ||||
|             if (notePath !== null) { | ||||
|             if (!notePath) { | ||||
|                 notePath = $(this).attr("note-path"); | ||||
|             } | ||||
|  | ||||
|             if (notePath) { | ||||
|                 const noteId = treeUtils.getNoteIdFromNotePath(notePath); | ||||
|  | ||||
|                 noteDetailService.loadNote(noteId).then(note => callback(note.content)); | ||||
|                 noteDetailService.loadNote(noteId).then(note => { | ||||
|                     if (!note.content.trim()) { | ||||
|                         return; | ||||
|                     } | ||||
|  | ||||
|                     if (note.type === 'text') { | ||||
|                         callback(note.content); | ||||
|                     } | ||||
|                     else if (note.type === 'code') { | ||||
|                         callback($("<pre>").text(note.content).prop('outerHTML')); | ||||
|                     } | ||||
|                     // other types of notes don't have tooltip preview | ||||
|                 }); | ||||
|             } | ||||
|         }, | ||||
|         close: function (event, ui) { | ||||
|   | ||||
| @@ -8,7 +8,6 @@ import treeChangesService from './branches.js'; | ||||
| import treeUtils from './tree_utils.js'; | ||||
| import utils from './utils.js'; | ||||
| import server from './server.js'; | ||||
| import recentNotesDialog from '../dialogs/recent_notes.js'; | ||||
| import treeCache from './tree_cache.js'; | ||||
| import infoService from "./info.js"; | ||||
| import treeBuilder from "./tree_builder.js"; | ||||
| @@ -101,14 +100,22 @@ async function expandToNote(notePath, expandOpts) { | ||||
|     } | ||||
| } | ||||
|  | ||||
| async function activateNode(notePath) { | ||||
| async function activateNode(notePath, newNote) { | ||||
|     utils.assertArguments(notePath); | ||||
|  | ||||
|     const node = await expandToNote(notePath); | ||||
|  | ||||
|     await node.setActive(); | ||||
|     if (newNote) { | ||||
|         noteDetailService.newNoteCreated(); | ||||
|     } | ||||
|  | ||||
|     // we use noFocus because when we reload the tree because of background changes | ||||
|     // we don't want the reload event to steal focus from whatever was focused before | ||||
|     await node.setActive(true, { noFocus: true }); | ||||
|  | ||||
|     clearSelectedNodes(); | ||||
|  | ||||
|     return node; | ||||
| } | ||||
|  | ||||
| /** | ||||
| @@ -239,6 +246,15 @@ async function setExpandedToServer(branchId, isExpanded) { | ||||
|     await server.put('branches/' + branchId + '/expanded/' + expandedNum); | ||||
| } | ||||
|  | ||||
| function addRecentNote(branchId, notePath) { | ||||
|     setTimeout(async () => { | ||||
|         // we include the note into recent list only if the user stayed on the note at least 5 seconds | ||||
|         if (notePath && notePath === getCurrentNotePath()) { | ||||
|             await server.put('recent-notes/' + branchId + '/' + encodeURIComponent(notePath)); | ||||
|         } | ||||
|     }, 1500); | ||||
| } | ||||
|  | ||||
| function setCurrentNotePathToHash(node) { | ||||
|     utils.assertArguments(node); | ||||
|  | ||||
| @@ -247,7 +263,7 @@ function setCurrentNotePathToHash(node) { | ||||
|  | ||||
|     document.location.hash = currentNotePath; | ||||
|  | ||||
|     recentNotesDialog.addRecentNote(currentBranchId, currentNotePath); | ||||
|     addRecentNote(currentBranchId, currentNotePath); | ||||
| } | ||||
|  | ||||
| function getSelectedNodes(stopOnParents = false) { | ||||
| @@ -275,11 +291,11 @@ async function treeInitialized() { | ||||
|     } | ||||
|  | ||||
|     if (startNotePath) { | ||||
|         await activateNode(startNotePath); | ||||
|         const node = await activateNode(startNotePath); | ||||
|  | ||||
|         // looks like this this doesn't work when triggered immediatelly after activating node | ||||
|         // so waiting a second helps | ||||
|         setTimeout(scrollToCurrentNote, 1000); | ||||
|         setTimeout(() => node.makeVisible({scrollIntoView: true}), 1000); | ||||
|     } | ||||
| } | ||||
|  | ||||
| @@ -497,7 +513,13 @@ async function showTree() { | ||||
|     initFancyTree(tree); | ||||
| } | ||||
|  | ||||
| messagingService.subscribeToMessages(syncData => { | ||||
| messagingService.subscribeToMessages(message => { | ||||
|    if (message.type === 'refresh-tree') { | ||||
|        reload(); | ||||
|    } | ||||
| }); | ||||
|  | ||||
| messagingService.subscribeToSyncMessages(syncData => { | ||||
|     if (syncData.some(sync => sync.entityName === 'branches') | ||||
|         || syncData.some(sync => sync.entityName === 'notes')) { | ||||
|  | ||||
|   | ||||
| @@ -115,6 +115,10 @@ async function getExtraClasses(note) { | ||||
|         extraClasses.push("multiple-parents"); | ||||
|     } | ||||
|  | ||||
|     if (note.cssClass) { | ||||
|         extraClasses.push(note.cssClass); | ||||
|     } | ||||
|  | ||||
|     extraClasses.push(note.type); | ||||
|  | ||||
|     return extraClasses.join(" "); | ||||
|   | ||||
| @@ -2,6 +2,7 @@ import utils from "./utils.js"; | ||||
| import Branch from "../entities/branch.js"; | ||||
| import NoteShort from "../entities/note_short.js"; | ||||
| import infoService from "./info.js"; | ||||
| import messagingService from "./messaging.js"; | ||||
| import server from "./server.js"; | ||||
|  | ||||
| class TreeCache { | ||||
| @@ -48,12 +49,14 @@ class TreeCache { | ||||
|  | ||||
|         return noteIds.map(noteId => { | ||||
|             if (!this.notes[noteId]) { | ||||
|                 throw new Error(`Can't find note ${noteId}`); | ||||
|                 messagingService.logError(`Can't find note ${noteId}`); | ||||
|  | ||||
|                 return null; | ||||
|             } | ||||
|             else { | ||||
|                 return this.notes[noteId]; | ||||
|             } | ||||
|         }); | ||||
|         }).filter(note => note !== null); | ||||
|     } | ||||
|  | ||||
|     /** @return NoteShort */ | ||||
|   | ||||
| @@ -42,7 +42,7 @@ const keyBindings = { | ||||
|     }, | ||||
|     "shift+up": node => { | ||||
|         node.navigate($.ui.keyCode.UP, true).then(() => { | ||||
|             const currentNode = getCurrentNode(); | ||||
|             const currentNode = treeService.getCurrentNode(); | ||||
|  | ||||
|             if (currentNode.isSelected()) { | ||||
|                 node.setSelected(false); | ||||
|   | ||||
| @@ -46,7 +46,7 @@ function isElectron() { | ||||
| function assertArguments() { | ||||
|     for (const i in arguments) { | ||||
|         if (!arguments[i]) { | ||||
|             throw new Error(`Argument idx#${i} should not be falsy: ${arguments[i]}`); | ||||
|             console.trace(`Argument idx#${i} should not be falsy: ${arguments[i]}`); | ||||
|         } | ||||
|     } | ||||
| } | ||||
|   | ||||
| @@ -1,36 +1,141 @@ | ||||
| import server from './services/server.js'; | ||||
| import utils from "./services/utils.js"; | ||||
|  | ||||
| $("#setup-form").submit(() => { | ||||
|     const username = $("#username").val(); | ||||
|     const password1 = $("#password1").val(); | ||||
|     const password2 = $("#password2").val(); | ||||
|  | ||||
|     if (!username) { | ||||
|         showAlert("Username can't be empty"); | ||||
|         return false; | ||||
| function SetupModel() { | ||||
|     if (syncInProgress) { | ||||
|         setInterval(checkOutstandingSyncs, 1000); | ||||
|     } | ||||
|  | ||||
|     if (!password1) { | ||||
|         showAlert("Password can't be empty"); | ||||
|         return false; | ||||
|     } | ||||
|     const serverAddress = location.protocol + '//' + location.host; | ||||
|  | ||||
|     if (password1 !== password2) { | ||||
|         showAlert("Both password fields need be identical."); | ||||
|         return false; | ||||
|     } | ||||
|     $("#current-host").html(serverAddress); | ||||
|  | ||||
|     server.post('setup', { | ||||
|         username: username, | ||||
|         password: password1 | ||||
|     }).then(() => { | ||||
|     this.step = ko.observable(syncInProgress ? "sync-in-progress" : "setup-type"); | ||||
|     this.setupType = ko.observable(); | ||||
|  | ||||
|     this.setupNewDocument = ko.observable(false); | ||||
|     this.setupSyncFromDesktop = ko.observable(false); | ||||
|     this.setupSyncFromServer = ko.observable(false); | ||||
|  | ||||
|     this.username = ko.observable(); | ||||
|     this.password1 = ko.observable(); | ||||
|     this.password2 = ko.observable(); | ||||
|  | ||||
|     this.syncServerHost = ko.observable(); | ||||
|     this.syncProxy = ko.observable(); | ||||
|  | ||||
|     this.instanceType = utils.isElectron() ? "desktop" : "server"; | ||||
|  | ||||
|     this.setupTypeSelected = this.getSetupType = () => | ||||
|         this.setupNewDocument() | ||||
|         || this.setupSyncFromDesktop() | ||||
|         || this.setupSyncFromServer(); | ||||
|  | ||||
|     this.selectSetupType = () => { | ||||
|         this.step(this.getSetupType()); | ||||
|         this.setupType(this.getSetupType()); | ||||
|     }; | ||||
|  | ||||
|     this.back = () => { | ||||
|         this.step("setup-type"); | ||||
|  | ||||
|         this.setupNewDocument(false); | ||||
|         this.setupSyncFromServer(false); | ||||
|         this.setupSyncFromDesktop(false); | ||||
|     }; | ||||
|  | ||||
|     this.finish = async () => { | ||||
|         if (this.setupNewDocument()) { | ||||
|             const username = this.username(); | ||||
|             const password1 = this.password1(); | ||||
|             const password2 = this.password2(); | ||||
|  | ||||
|             if (!username) { | ||||
|                 showAlert("Username can't be empty"); | ||||
|                 return; | ||||
|             } | ||||
|  | ||||
|             if (!password1) { | ||||
|                 showAlert("Password can't be empty"); | ||||
|                 return; | ||||
|             } | ||||
|  | ||||
|             if (password1 !== password2) { | ||||
|                 showAlert("Both password fields need be identical."); | ||||
|                 return; | ||||
|             } | ||||
|  | ||||
|             // not using server.js because it loads too many dependencies | ||||
|             $.post('/api/setup/new-document', { | ||||
|                 username: username, | ||||
|                 password: password1 | ||||
|             }).then(() => { | ||||
|                 window.location.replace("/"); | ||||
|             }); | ||||
|         } | ||||
|         else if (this.setupSyncFromServer()) { | ||||
|             const syncServerHost = this.syncServerHost(); | ||||
|             const syncProxy = this.syncProxy(); | ||||
|             const username = this.username(); | ||||
|             const password = this.password1(); | ||||
|  | ||||
|             if (!syncServerHost) { | ||||
|                 showAlert("Trilium server address can't be empty"); | ||||
|                 return; | ||||
|             } | ||||
|  | ||||
|             if (!username) { | ||||
|                 showAlert("Username can't be empty"); | ||||
|                 return; | ||||
|             } | ||||
|  | ||||
|             if (!password) { | ||||
|                 showAlert("Password can't be empty"); | ||||
|                 return; | ||||
|             } | ||||
|  | ||||
|             // not using server.js because it loads too many dependencies | ||||
|             const resp = await $.post('/api/setup/sync-from-server', { | ||||
|                 syncServerHost: syncServerHost, | ||||
|                 syncProxy: syncProxy, | ||||
|                 username: username, | ||||
|                 password: password | ||||
|             }); | ||||
|  | ||||
|             if (resp.result === 'success') { | ||||
|                 this.step('sync-in-progress'); | ||||
|  | ||||
|                 setInterval(checkOutstandingSyncs, 1000); | ||||
|  | ||||
|                 hideAlert(); | ||||
|             } | ||||
|             else { | ||||
|                 showAlert('Sync setup failed: ' + resp.error); | ||||
|             } | ||||
|         } | ||||
|     }; | ||||
| } | ||||
|  | ||||
| async function checkOutstandingSyncs() { | ||||
|     const { stats, initialized } = await $.get('/api/sync/stats'); | ||||
|  | ||||
|     if (initialized) { | ||||
|         window.location.replace("/"); | ||||
|     }); | ||||
|     } | ||||
|  | ||||
|     return false; | ||||
| }); | ||||
|     const totalOutstandingSyncs = stats.outstandingPushes + stats.outstandingPulls; | ||||
|  | ||||
|     $("#outstanding-syncs").html(totalOutstandingSyncs); | ||||
| } | ||||
|  | ||||
| function showAlert(message) { | ||||
|     $("#alert").html(message); | ||||
|     $("#alert").show(); | ||||
| } | ||||
|  | ||||
| function hideAlert() { | ||||
|     $("#alert").hide(); | ||||
| } | ||||
|  | ||||
| ko.applyBindings(new SetupModel(), document.getElementById('setup-dialog')); | ||||
|  | ||||
| $("#setup-dialog").show(); | ||||
							
								
								
									
										2
									
								
								src/public/libraries/ckeditor/ckeditor.js
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										2
									
								
								src/public/libraries/ckeditor/ckeditor.js
									
									
									
									
										vendored
									
									
								
							
										
											
												File diff suppressed because one or more lines are too long
											
										
									
								
							
										
											
												File diff suppressed because one or more lines are too long
											
										
									
								
							| @@ -308,13 +308,13 @@ div.ui-tooltip { | ||||
|  | ||||
| .cm-matchhighlight {background-color: #eeeeee} | ||||
|  | ||||
| #label-list { | ||||
| #label-list, #relation-list, #attribute-list { | ||||
|     color: #777777; | ||||
|     border-top: 1px solid #eee; | ||||
|     padding: 5px; display: none; | ||||
|     padding: 5px; | ||||
|     display: none; | ||||
| } | ||||
|  | ||||
| #label-list button { | ||||
| #label-list button, #relation-list button, #attribute-list button { | ||||
|     padding: 2px; | ||||
|     margin-right: 5px; | ||||
| } | ||||
| @@ -421,3 +421,25 @@ html.theme-dark img, html.theme-dark video { | ||||
| html.theme-dark body { | ||||
|     background: #191819; | ||||
| } | ||||
|  | ||||
| .ck.ck-block-toolbar-button { | ||||
|     transform: translateX(10px); | ||||
| } | ||||
|  | ||||
| #note-detail-promoted-attributes { | ||||
|     max-width: 70%; | ||||
|     margin: auto; | ||||
| } | ||||
|  | ||||
| #note-detail-promoted-attributes td, note-detail-promoted-attributes th { | ||||
|     padding: 5px; | ||||
| } | ||||
|  | ||||
| .pointer { | ||||
|     cursor: pointer; | ||||
| } | ||||
|  | ||||
| .show-recent-notes-button { | ||||
|     background: url('/images/icons/clock-16.png') no-repeat center; | ||||
|     cursor: pointer; | ||||
| } | ||||
							
								
								
									
										117
									
								
								src/routes/api/attributes.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										117
									
								
								src/routes/api/attributes.js
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,117 @@ | ||||
| "use strict"; | ||||
|  | ||||
| const sql = require('../../services/sql'); | ||||
| const attributeService = require('../../services/attributes'); | ||||
| const repository = require('../../services/repository'); | ||||
| const Attribute = require('../../entities/attribute'); | ||||
|  | ||||
| async function getEffectiveNoteAttributes(req) { | ||||
|     const note = await repository.getNote(req.params.noteId); | ||||
|  | ||||
|     return await note.getAttributes(); | ||||
| } | ||||
|  | ||||
| async function updateNoteAttribute(req) { | ||||
|     const noteId = req.params.noteId; | ||||
|     const body = req.body; | ||||
|  | ||||
|     let attribute; | ||||
|     if (body.attributeId) { | ||||
|         attribute = await repository.getAttribute(body.attributeId); | ||||
|     } | ||||
|     else { | ||||
|         attribute = new Attribute(); | ||||
|         attribute.noteId = noteId; | ||||
|         attribute.name = body.name; | ||||
|         attribute.type = body.type; | ||||
|     } | ||||
|  | ||||
|     if (attribute.noteId !== noteId) { | ||||
|         return [400, `Attribute ${body.attributeId} is not owned by ${noteId}`]; | ||||
|     } | ||||
|  | ||||
|     attribute.value = body.value; | ||||
|  | ||||
|     await attribute.save(); | ||||
|  | ||||
|     return { | ||||
|         attributeId: attribute.attributeId | ||||
|     }; | ||||
| } | ||||
|  | ||||
| async function deleteNoteAttribute(req) { | ||||
|     const noteId = req.params.noteId; | ||||
|     const attributeId = req.params.attributeId; | ||||
|  | ||||
|     const attribute = await repository.getAttribute(attributeId); | ||||
|  | ||||
|     if (attribute) { | ||||
|         if (attribute.noteId !== noteId) { | ||||
|             return [400, `Attribute ${attributeId} is not owned by ${noteId}`]; | ||||
|         } | ||||
|  | ||||
|         attribute.isDeleted = true; | ||||
|         await attribute.save(); | ||||
|     } | ||||
| } | ||||
|  | ||||
| async function updateNoteAttributes(req) { | ||||
|     const noteId = req.params.noteId; | ||||
|     const attributes = req.body; | ||||
|  | ||||
|     for (const attribute of attributes) { | ||||
|         let attributeEntity; | ||||
|  | ||||
|         if (attribute.attributeId) { | ||||
|             attributeEntity = await repository.getAttribute(attribute.attributeId); | ||||
|  | ||||
|             if (attributeEntity.noteId !== noteId) { | ||||
|                 return [400, `Attribute ${attributeEntity.noteId} is not owned by ${noteId}`]; | ||||
|             } | ||||
|         } | ||||
|         else { | ||||
|             // if it was "created" and then immediatelly deleted, we just don't create it at all | ||||
|             if (attribute.isDeleted) { | ||||
|                 continue; | ||||
|             } | ||||
|  | ||||
|             attributeEntity = new Attribute(); | ||||
|             attributeEntity.noteId = noteId; | ||||
|         } | ||||
|  | ||||
|         attributeEntity.type = attribute.type; | ||||
|         attributeEntity.name = attribute.name; | ||||
|         attributeEntity.value = attribute.value; | ||||
|         attributeEntity.position = attribute.position; | ||||
|         attributeEntity.isInheritable = attribute.isInheritable; | ||||
|         attributeEntity.isDeleted = attribute.isDeleted; | ||||
|  | ||||
|         await attributeEntity.save(); | ||||
|     } | ||||
|  | ||||
|     const note = await repository.getNote(noteId); | ||||
|  | ||||
|     return await note.getAttributes(); | ||||
| } | ||||
|  | ||||
| async function getAttributeNames(req) { | ||||
|     const type = req.query.type; | ||||
|     const query = req.query.query; | ||||
|  | ||||
|     return attributeService.getAttributeNames(type, query); | ||||
| } | ||||
|  | ||||
| async function getValuesForAttribute(req) { | ||||
|     const attributeName = req.params.attributeName; | ||||
|  | ||||
|     return await sql.getColumn("SELECT DISTINCT value FROM attributes WHERE isDeleted = 0 AND name = ? AND type = 'label' AND value != '' ORDER BY value", [attributeName]); | ||||
| } | ||||
|  | ||||
| module.exports = { | ||||
|     updateNoteAttributes, | ||||
|     updateNoteAttribute, | ||||
|     deleteNoteAttribute, | ||||
|     getAttributeNames, | ||||
|     getValuesForAttribute, | ||||
|     getEffectiveNoteAttributes | ||||
| }; | ||||
| @@ -1,20 +1,50 @@ | ||||
| "use strict"; | ||||
|  | ||||
| const noteCacheService = require('../../services/note_cache'); | ||||
| const repository = require('../../services/repository'); | ||||
|  | ||||
| async function getAutocomplete(req) { | ||||
|     const query = req.query.query; | ||||
|  | ||||
|     const results = noteCacheService.findNotes(query); | ||||
|     let results; | ||||
|  | ||||
|     if (query.trim().length === 0) { | ||||
|         results = await getRecentNotes(); | ||||
|     } | ||||
|     else { | ||||
|         results = noteCacheService.findNotes(query); | ||||
|     } | ||||
|  | ||||
|     return results.map(res => { | ||||
|         return { | ||||
|             value: res.title + ' (' + res.path + ')', | ||||
|             value: res.path, | ||||
|             label: res.title | ||||
|         } | ||||
|     }); | ||||
| } | ||||
|  | ||||
| async function getRecentNotes() { | ||||
|     const recentNotes = await repository.getEntities(` | ||||
|       SELECT  | ||||
|         recent_notes.*  | ||||
|       FROM  | ||||
|         recent_notes | ||||
|         JOIN branches USING(branchId) | ||||
|       WHERE | ||||
|         recent_notes.isDeleted = 0 | ||||
|         AND branches.isDeleted = 0 | ||||
|       ORDER BY  | ||||
|         dateCreated DESC | ||||
|       LIMIT 200`); | ||||
|  | ||||
|     return recentNotes.map(rn => { | ||||
|         return { | ||||
|             path: rn.notePath, | ||||
|             title: noteCacheService.getNoteTitleForPath(rn.notePath.split('/')) | ||||
|         }; | ||||
|     }); | ||||
| } | ||||
|  | ||||
| module.exports = { | ||||
|     getAutocomplete | ||||
| }; | ||||
| @@ -1,46 +1,9 @@ | ||||
| "use strict"; | ||||
|  | ||||
| const sql = require('../../services/sql'); | ||||
| const utils = require('../../services/utils'); | ||||
| const syncTable = require('../../services/sync_table'); | ||||
| const log = require('../../services/log'); | ||||
| const repository = require('../../services/repository'); | ||||
|  | ||||
| async function cleanupSoftDeletedItems() { | ||||
|     const noteIdsToDelete = await sql.getColumn("SELECT noteId FROM notes WHERE isDeleted = 1"); | ||||
|     const noteIdsSql = noteIdsToDelete | ||||
|         .map(noteId => "'" + utils.sanitizeSql(noteId) + "'") | ||||
|         .join(', '); | ||||
|  | ||||
|     await sql.execute(`DELETE FROM event_log WHERE noteId IN (${noteIdsSql})`); | ||||
|  | ||||
|     await sql.execute(`DELETE FROM note_revisions WHERE noteId IN (${noteIdsSql})`); | ||||
|  | ||||
|     await sql.execute(`DELETE FROM note_images WHERE noteId IN (${noteIdsSql})`); | ||||
|  | ||||
|     await sql.execute(`DELETE FROM labels WHERE noteId IN (${noteIdsSql})`); | ||||
|  | ||||
|     await sql.execute("DELETE FROM branches WHERE isDeleted = 1"); | ||||
|  | ||||
|     await sql.execute("DELETE FROM note_images WHERE isDeleted = 1"); | ||||
|  | ||||
|     await sql.execute("DELETE FROM images WHERE isDeleted = 1"); | ||||
|  | ||||
|     await sql.execute("DELETE FROM notes WHERE isDeleted = 1"); | ||||
|  | ||||
|     await sql.execute("DELETE FROM recent_notes"); | ||||
|  | ||||
|     await syncTable.cleanupSyncRowsForMissingEntities("notes", "noteId"); | ||||
|     await syncTable.cleanupSyncRowsForMissingEntities("branches", "branchId"); | ||||
|     await syncTable.cleanupSyncRowsForMissingEntities("note_revisions", "noteRevisionId"); | ||||
|     await syncTable.cleanupSyncRowsForMissingEntities("recent_notes", "branchId"); | ||||
|     await syncTable.cleanupSyncRowsForMissingEntities("images", "imageId"); | ||||
|     await syncTable.cleanupSyncRowsForMissingEntities("note_images", "noteImageId"); | ||||
|     await syncTable.cleanupSyncRowsForMissingEntities("labels", "labelId"); | ||||
|  | ||||
|     log.info("Following notes has been completely cleaned from database: " + noteIdsSql); | ||||
| } | ||||
|  | ||||
| async function cleanupUnusedImages() { | ||||
|     const unusedImageIds = await sql.getColumn(` | ||||
|       SELECT images.imageId  | ||||
| @@ -67,7 +30,6 @@ async function vacuumDatabase() { | ||||
| } | ||||
|  | ||||
| module.exports = { | ||||
|     cleanupSoftDeletedItems, | ||||
|     cleanupUnusedImages, | ||||
|     vacuumDatabase | ||||
| }; | ||||
| @@ -113,15 +113,18 @@ async function exportToTar(branchId, res) { | ||||
|             prefix: branch.prefix, | ||||
|             type: note.type, | ||||
|             mime: note.mime, | ||||
|             labels: (await note.getLabels()).map(label => { | ||||
|             attributes: (await note.getOwnedAttributes()).map(attribute => { | ||||
|                 return { | ||||
|                     name: label.name, | ||||
|                     value: label.value | ||||
|                     type: attribute.type, | ||||
|                     name: attribute.name, | ||||
|                     value: attribute.value, | ||||
|                     isInheritable: attribute.isInheritable, | ||||
|                     position: attribute.position | ||||
|                 }; | ||||
|             }) | ||||
|         }; | ||||
|  | ||||
|         if (metadata.labels.find(label => label.name === 'excludeFromExport')) { | ||||
|         if (metadata.attributes.find(attributes => attributes.type === 'label' && attributes.name === 'excludeFromExport')) { | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|   | ||||
| @@ -1,7 +1,7 @@ | ||||
| "use strict"; | ||||
|  | ||||
| const noteService = require('../../services/notes'); | ||||
| const labelService = require('../../services/labels'); | ||||
| const attributeService = require('../../services/attributes'); | ||||
| const protectedSessionService = require('../../services/protected_session'); | ||||
| const repository = require('../../services/repository'); | ||||
|  | ||||
| @@ -26,8 +26,8 @@ async function uploadFile(req) { | ||||
|         mime: file.mimetype | ||||
|     }); | ||||
|  | ||||
|     await labelService.createLabel(note.noteId, "originalFileName", originalName); | ||||
|     await labelService.createLabel(note.noteId, "fileSize", size); | ||||
|     await attributeService.createLabel(note.noteId, "originalFileName", originalName); | ||||
|     await attributeService.createLabel(note.noteId, "fileSize", size); | ||||
|  | ||||
|     return { | ||||
|         noteId: note.noteId | ||||
| @@ -47,8 +47,8 @@ async function downloadFile(req, res) { | ||||
|         return; | ||||
|     } | ||||
|  | ||||
|     const labelMap = await note.getLabelMap(); | ||||
|     const fileName = labelMap.originalFileName || note.title; | ||||
|     const originalFileName = await note.getLabel('originalFileName'); | ||||
|     const fileName = originalFileName.value || note.title; | ||||
|  | ||||
|     res.setHeader('Content-Disposition', 'file; filename="' + fileName + '"'); | ||||
|     res.setHeader('Content-Type', note.mime); | ||||
|   | ||||
| @@ -1,7 +1,7 @@ | ||||
| "use strict"; | ||||
|  | ||||
| const repository = require('../../services/repository'); | ||||
| const labelService = require('../../services/labels'); | ||||
| const attributeService = require('../../services/attributes'); | ||||
| const noteService = require('../../services/notes'); | ||||
| const Branch = require('../../entities/branch'); | ||||
| const tar = require('tar-stream'); | ||||
| @@ -187,8 +187,15 @@ async function importNotes(files, parentNoteId, noteIdMap) { | ||||
|  | ||||
|         noteIdMap[file.meta.noteId] = note.noteId; | ||||
|  | ||||
|         for (const label of file.meta.labels) { | ||||
|             await labelService.createLabel(note.noteId, label.name, label.value); | ||||
|         for (const attribute of file.meta.attributes) { | ||||
|             await attributeService.createAttribute({ | ||||
|                 noteId: note.noteId, | ||||
|                 type: attribute.type, | ||||
|                 name: attribute.name, | ||||
|                 value: attribute.value, | ||||
|                 isInheritable: attribute.isInheritable, | ||||
|                 position: attribute.position | ||||
|             }); | ||||
|         } | ||||
|  | ||||
|         if (file.children.length > 0) { | ||||
|   | ||||
| @@ -1,70 +0,0 @@ | ||||
| "use strict"; | ||||
|  | ||||
| const sql = require('../../services/sql'); | ||||
| const labelService = require('../../services/labels'); | ||||
| const repository = require('../../services/repository'); | ||||
| const Label = require('../../entities/label'); | ||||
|  | ||||
| async function getNoteLabels(req) { | ||||
|     const noteId = req.params.noteId; | ||||
|  | ||||
|     return await repository.getEntities("SELECT * FROM labels WHERE isDeleted = 0 AND noteId = ? ORDER BY position, dateCreated", [noteId]); | ||||
| } | ||||
|  | ||||
| async function updateNoteLabels(req) { | ||||
|     const noteId = req.params.noteId; | ||||
|     const labels = req.body; | ||||
|  | ||||
|     for (const label of labels) { | ||||
|         let labelEntity; | ||||
|  | ||||
|         if (label.labelId) { | ||||
|             labelEntity = await repository.getLabel(label.labelId); | ||||
|         } | ||||
|         else { | ||||
|             // if it was "created" and then immediatelly deleted, we just don't create it at all | ||||
|             if (label.isDeleted) { | ||||
|                 continue; | ||||
|             } | ||||
|  | ||||
|             labelEntity = new Label(); | ||||
|             labelEntity.noteId = noteId; | ||||
|         } | ||||
|  | ||||
|         labelEntity.name = label.name; | ||||
|         labelEntity.value = label.value; | ||||
|         labelEntity.position = label.position; | ||||
|         labelEntity.isDeleted = label.isDeleted; | ||||
|  | ||||
|         await labelEntity.save(); | ||||
|     } | ||||
|  | ||||
|     return await repository.getEntities("SELECT * FROM labels WHERE isDeleted = 0 AND noteId = ? ORDER BY position, dateCreated", [noteId]); | ||||
| } | ||||
|  | ||||
| async function getAllLabelNames() { | ||||
|     const names = await sql.getColumn("SELECT DISTINCT name FROM labels WHERE isDeleted = 0"); | ||||
|  | ||||
|     for (const label of labelService.BUILTIN_LABELS) { | ||||
|         if (!names.includes(label)) { | ||||
|             names.push(label); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     names.sort(); | ||||
|  | ||||
|     return names; | ||||
| } | ||||
|  | ||||
| async function getValuesForLabel(req) { | ||||
|     const labelName = req.params.labelName; | ||||
|  | ||||
|     return await sql.getColumn("SELECT DISTINCT value FROM labels WHERE isDeleted = 0 AND name = ? AND value != '' ORDER BY value", [labelName]); | ||||
| } | ||||
|  | ||||
| module.exports = { | ||||
|     getNoteLabels, | ||||
|     updateNoteLabels, | ||||
|     getAllLabelNames, | ||||
|     getValuesForLabel | ||||
| }; | ||||
| @@ -9,8 +9,13 @@ const protectedSessionService = require('../../services/protected_session'); | ||||
| const appInfo = require('../../services/app_info'); | ||||
| const eventService = require('../../services/events'); | ||||
| const cls = require('../../services/cls'); | ||||
| const sqlInit = require('../../services/sql_init'); | ||||
|  | ||||
| async function loginSync(req) { | ||||
|     if (!await sqlInit.schemaExists()) { | ||||
|         return [400, { message: "DB schema does not exist, can't sync." }]; | ||||
|     } | ||||
|  | ||||
|     const timestampStr = req.body.timestamp; | ||||
|  | ||||
|     const timestamp = dateUtils.parseDateTime(timestampStr); | ||||
| @@ -60,7 +65,7 @@ async function loginToProtectedSession(req) { | ||||
|     // this is set here so that event handlers have access to the protected session | ||||
|     cls.namespace.set('protectedSessionId', protectedSessionId); | ||||
|  | ||||
|     eventService.emit(eventService.ENTER_PROTECTED_SESSION); | ||||
|     await eventService.emit(eventService.ENTER_PROTECTED_SESSION); | ||||
|  | ||||
|     return { | ||||
|         success: true, | ||||
|   | ||||
| @@ -5,7 +5,8 @@ const optionService = require('../../services/options'); | ||||
| const log = require('../../services/log'); | ||||
|  | ||||
| // options allowed to be updated directly in options dialog | ||||
| const ALLOWED_OPTIONS = ['protectedSessionTimeout', 'noteRevisionSnapshotTimeInterval', 'zoomFactor', 'theme']; | ||||
| const ALLOWED_OPTIONS = ['protectedSessionTimeout', 'noteRevisionSnapshotTimeInterval', | ||||
|     'zoomFactor', 'theme', 'syncServerHost', 'syncServerTimeout', 'syncProxy']; | ||||
|  | ||||
| async function getOptions() { | ||||
|     const options = await sql.getMap("SELECT name, value FROM options WHERE name IN (" | ||||
| @@ -17,16 +18,35 @@ async function getOptions() { | ||||
| async function updateOption(req) { | ||||
|     const {name, value} = req.params; | ||||
|  | ||||
|     if (!update(name, value)) { | ||||
|         return [400, "not allowed option to change"]; | ||||
|     } | ||||
| } | ||||
|  | ||||
| async function updateOptions(req) { | ||||
|     for (const optionName in req.body) { | ||||
|         if (!update(optionName, req.body[optionName])) { | ||||
|             // this should be improved | ||||
|             // it should return 400 instead of current 500, but at least it now rollbacks transaction | ||||
|             throw new Error(`${optionName} is not allowed to change`); | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
| async function update(name, value) { | ||||
|     if (!ALLOWED_OPTIONS.includes(name)) { | ||||
|         return [400, "not allowed option to set"]; | ||||
|         return false; | ||||
|     } | ||||
|  | ||||
|     log.info(`Updating option ${name} to ${value}`); | ||||
|  | ||||
|     await optionService.setOption(name, value); | ||||
|  | ||||
|     return true; | ||||
| } | ||||
|  | ||||
| module.exports = { | ||||
|     getOptions, | ||||
|     updateOption | ||||
|     updateOption, | ||||
|     updateOptions | ||||
| }; | ||||
| @@ -1,30 +1,7 @@ | ||||
| "use strict"; | ||||
|  | ||||
| const repository = require('../../services/repository'); | ||||
| const optionService = require('../../services/options'); | ||||
| const RecentNote = require('../../entities/recent_note'); | ||||
| const noteCacheService = require('../../services/note_cache'); | ||||
|  | ||||
| async function getRecentNotes() { | ||||
|     const recentNotes = await repository.getEntities(` | ||||
|       SELECT  | ||||
|         recent_notes.*  | ||||
|       FROM  | ||||
|         recent_notes | ||||
|         JOIN branches USING(branchId) | ||||
|       WHERE | ||||
|         recent_notes.isDeleted = 0 | ||||
|         AND branches.isDeleted = 0 | ||||
|       ORDER BY  | ||||
|         dateCreated DESC | ||||
|       LIMIT 200`); | ||||
|  | ||||
|     for (const rn of recentNotes) { | ||||
|         rn.title = noteCacheService.getNoteTitleForPath(rn.notePath.split('/')); | ||||
|     } | ||||
|  | ||||
|     return recentNotes; | ||||
| } | ||||
|  | ||||
| async function addRecentNote(req) { | ||||
|     const branchId = req.params.branchId; | ||||
| @@ -36,11 +13,8 @@ async function addRecentNote(req) { | ||||
|     }).save(); | ||||
|  | ||||
|     await optionService.setOption('startNotePath', notePath); | ||||
|  | ||||
|     return await getRecentNotes(); | ||||
| } | ||||
|  | ||||
| module.exports = { | ||||
|     getRecentNotes, | ||||
|     addRecentNote | ||||
| }; | ||||
| @@ -1,11 +1,12 @@ | ||||
| "use strict"; | ||||
|  | ||||
| const labelService = require('../../services/labels'); | ||||
| const scriptService = require('../../services/script'); | ||||
| const attributeService = require('../../services/attributes'); | ||||
| const repository = require('../../services/repository'); | ||||
|  | ||||
| async function exec(req) { | ||||
|     const result = await scriptService.executeScript(req.body.script, req.body.params, req.body.startNoteId, req.body.currentNoteId); | ||||
|     const result = await scriptService.executeScript(req.body.script, req.body.params, req.body.startNoteId, | ||||
|         req.body.currentNoteId, req.body.originEntityName, req.body.originEntityId); | ||||
|  | ||||
|     return { executionResult: result }; | ||||
| } | ||||
| @@ -13,13 +14,13 @@ async function exec(req) { | ||||
| async function run(req) { | ||||
|     const note = await repository.getNote(req.params.noteId); | ||||
|  | ||||
|     const result = await scriptService.executeNote(req, note); | ||||
|     const result = await scriptService.executeNote(note, note); | ||||
|  | ||||
|     return { executionResult: result }; | ||||
| } | ||||
|  | ||||
| async function getStartupBundles() { | ||||
|     const notes = await labelService.getNotesWithLabel("run", "frontendStartup"); | ||||
|     const notes = await attributeService.getNotesWithLabel("run", "frontendStartup"); | ||||
|  | ||||
|     const bundles = []; | ||||
|  | ||||
| @@ -34,14 +35,33 @@ async function getStartupBundles() { | ||||
|     return bundles; | ||||
| } | ||||
|  | ||||
| async function getRelationBundles(req) { | ||||
|     const noteId = req.params.noteId; | ||||
|     const note = await repository.getNote(noteId); | ||||
|     const relationName = req.params.relationName; | ||||
|  | ||||
|     const attributes = await note.getAttributes(); | ||||
|     const filtered = attributes.filter(attr => attr.type === 'relation' && attr.name === relationName); | ||||
|     const targetNoteIds = filtered.map(relation => relation.value); | ||||
|     const uniqueNoteIds = Array.from(new Set(targetNoteIds)); | ||||
|  | ||||
|     const bundles = []; | ||||
|  | ||||
|     for (const noteId of uniqueNoteIds) { | ||||
|         bundles.push(await scriptService.getScriptBundleForNoteId(noteId)); | ||||
|     } | ||||
|  | ||||
|     return bundles; | ||||
| } | ||||
|  | ||||
| async function getBundle(req) { | ||||
|     const note = await repository.getNote(req.params.noteId); | ||||
|     return await scriptService.getScriptBundle(note); | ||||
|     return await scriptService.getScriptBundleForNoteId(req.params.noteId); | ||||
| } | ||||
|  | ||||
| module.exports = { | ||||
|     exec, | ||||
|     run, | ||||
|     getStartupBundles, | ||||
|     getRelationBundles, | ||||
|     getBundle | ||||
| }; | ||||
| @@ -1,27 +1,76 @@ | ||||
| "use strict"; | ||||
|  | ||||
| const optionService = require('../../services/options'); | ||||
| const sqlInit = require('../../services/sql_init'); | ||||
| const utils = require('../../services/utils'); | ||||
| const myScryptService = require('../../services/my_scrypt'); | ||||
| const passwordEncryptionService = require('../../services/password_encryption'); | ||||
| const setupService = require('../../services/setup'); | ||||
| const optionService = require('../../services/options'); | ||||
| const syncService = require('../../services/sync'); | ||||
| const log = require('../../services/log'); | ||||
| const rp = require('request-promise'); | ||||
|  | ||||
| async function setup(req) { | ||||
| async function setupNewDocument(req) { | ||||
|     const { username, password } = req.body; | ||||
|  | ||||
|     await optionService.setOption('username', username); | ||||
|     await sqlInit.createInitialDatabase(username, password); | ||||
| } | ||||
|  | ||||
|     await optionService.setOption('passwordVerificationSalt', utils.randomSecureToken(32)); | ||||
|     await optionService.setOption('passwordDerivedKeySalt', utils.randomSecureToken(32)); | ||||
| async function setupSyncFromServer(req) { | ||||
|     const { syncServerHost, syncProxy, username, password } = req.body; | ||||
|  | ||||
|     const passwordVerificationKey = utils.toBase64(await myScryptService.getVerificationHash(password)); | ||||
|     await optionService.setOption('passwordVerificationHash', passwordVerificationKey); | ||||
|     return await setupService.setupSyncFromSyncServer(syncServerHost, syncProxy, username, password); | ||||
| } | ||||
|  | ||||
|     await passwordEncryptionService.setDataKey(password, utils.randomSecureToken(16)); | ||||
| async function setupSyncToSyncServer() { | ||||
|     log.info("Initiating sync to server"); | ||||
|  | ||||
|     sqlInit.setDbReadyAsResolved(); | ||||
|     const syncServerHost = await optionService.getOption('syncServerHost'); | ||||
|     const syncProxy = await optionService.getOption('syncProxy'); | ||||
|  | ||||
|     const rpOpts = { | ||||
|         uri: syncServerHost + '/api/setup/sync-seed', | ||||
|         method: 'POST', | ||||
|         json: true, | ||||
|         body: { | ||||
|             options: await setupService.getSyncSeedOptions() | ||||
|         } | ||||
|     }; | ||||
|  | ||||
|     if (syncProxy) { | ||||
|         rpOpts.proxy = syncProxy; | ||||
|     } | ||||
|  | ||||
|     try { | ||||
|         await rp(rpOpts); | ||||
|     } | ||||
|     catch (e) { | ||||
|         return { success: false, error: e.message }; | ||||
|     } | ||||
|  | ||||
|     // this is completely new sync, need to reset counters. If this would not be new sync, | ||||
|     // the previous request would have failed. | ||||
|     await optionService.setOption('lastSyncedPush', 0); | ||||
|     await optionService.setOption('lastSyncedPull', 0); | ||||
|  | ||||
|     syncService.sync(); | ||||
|  | ||||
|     return { success: true }; | ||||
| } | ||||
|  | ||||
| async function saveSyncSeed(req) { | ||||
|     const options = req.body.options; | ||||
|  | ||||
|     await sqlInit.createDatabaseForSync(options); | ||||
| } | ||||
|  | ||||
| async function getSyncSeed() { | ||||
|     log.info("Serving sync seed."); | ||||
|  | ||||
|     return await setupService.getSyncSeedOptions(); | ||||
| } | ||||
|  | ||||
| module.exports = { | ||||
|     setup | ||||
|     setupNewDocument, | ||||
|     setupSyncFromServer, | ||||
|     setupSyncToSyncServer, | ||||
|     getSyncSeed, | ||||
|     saveSyncSeed | ||||
| }; | ||||
| @@ -4,10 +4,37 @@ const syncService = require('../../services/sync'); | ||||
| const syncUpdateService = require('../../services/sync_update'); | ||||
| const syncTableService = require('../../services/sync_table'); | ||||
| const sql = require('../../services/sql'); | ||||
| const sqlInit = require('../../services/sql_init'); | ||||
| const optionService = require('../../services/options'); | ||||
| const contentHashService = require('../../services/content_hash'); | ||||
| const log = require('../../services/log'); | ||||
|  | ||||
| async function testSync() { | ||||
|     try { | ||||
|         await syncService.login(); | ||||
|  | ||||
|         return { connection: "Success" }; | ||||
|     } | ||||
|     catch (e) { | ||||
|         return { | ||||
|             connection: "Failure", | ||||
|             error: e.message | ||||
|         }; | ||||
|     } | ||||
| } | ||||
|  | ||||
| async function getStats() { | ||||
|     if (!await sqlInit.schemaExists()) { | ||||
|         // fail silently but prevent errors from not existing options table | ||||
|         return {}; | ||||
|     } | ||||
|  | ||||
|     return { | ||||
|         initialized: await optionService.getOption('initialized') === 'true', | ||||
|         stats: syncService.stats | ||||
|     }; | ||||
| } | ||||
|  | ||||
| async function checkSync() { | ||||
|     return { | ||||
|         hashes: await contentHashService.getHashes(), | ||||
| @@ -60,7 +87,10 @@ async function getChanged(req) { | ||||
|  | ||||
|     const syncs = await sql.getRows("SELECT * FROM sync WHERE id > ? LIMIT 1000", [lastSyncId]); | ||||
|  | ||||
|     return await syncService.getSyncRecords(syncs); | ||||
|     return { | ||||
|         syncs: await syncService.getSyncRecords(syncs), | ||||
|         maxSyncId: await sql.getValue('SELECT MAX(id) FROM sync') | ||||
|     }; | ||||
| } | ||||
|  | ||||
| async function update(req) { | ||||
| @@ -72,12 +102,21 @@ async function update(req) { | ||||
|     } | ||||
| } | ||||
|  | ||||
| async function syncFinished() { | ||||
|     // after first sync finishes, the application is ready to be used | ||||
|     // this is meaningless but at the same time harmless (idempotent) for further syncs | ||||
|     await sqlInit.dbInitialized(); | ||||
| } | ||||
|  | ||||
| module.exports = { | ||||
|     testSync, | ||||
|     checkSync, | ||||
|     syncNow, | ||||
|     fillSyncRows, | ||||
|     forceFullSync, | ||||
|     forceNoteSync, | ||||
|     getChanged, | ||||
|     update | ||||
|     update, | ||||
|     getStats, | ||||
|     syncFinished | ||||
| }; | ||||
| @@ -9,6 +9,26 @@ async function getNotes(noteIds) { | ||||
|       SELECT noteId, title, isProtected, type, mime | ||||
|       FROM notes WHERE isDeleted = 0 AND noteId IN (???)`, noteIds); | ||||
|  | ||||
|     const cssClassLabels = await sql.getManyRows(` | ||||
|       SELECT noteId, value FROM attributes WHERE isDeleted = 0 AND type = 'label'  | ||||
|                                              AND name = 'cssClass' AND noteId IN (???)`, noteIds); | ||||
|  | ||||
|     for (const label of cssClassLabels) { | ||||
|         // FIXME: inefficient! | ||||
|         const note = notes.find(note => note.noteId === label.noteId); | ||||
|  | ||||
|         if (!note) { | ||||
|             continue; | ||||
|         } | ||||
|  | ||||
|         if (note.cssClass) { | ||||
|             note.cssClass += " " + label.value; | ||||
|         } | ||||
|         else { | ||||
|             note.cssClass = label.value; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     protectedSessionService.decryptNotes(notes); | ||||
|  | ||||
|     notes.forEach(note => note.isProtected = !!note.isProtected); | ||||
| @@ -35,9 +55,9 @@ async function getTree() { | ||||
|               JOIN tree ON branches.parentNoteId = tree.noteId | ||||
|               WHERE tree.isExpanded = 1 AND branches.isDeleted = 0 | ||||
|           ) | ||||
|         SELECT branches.* FROM tree JOIN branches USING(noteId) ORDER BY branches.notePosition`); | ||||
|         SELECT branches.* FROM tree JOIN branches USING(noteId) WHERE branches.isDeleted = 0 ORDER BY branches.notePosition`); | ||||
|  | ||||
|     const noteIds = branches.map(b => b.noteId); | ||||
|     const noteIds = Array.from(new Set(branches.map(b => b.noteId))); | ||||
|  | ||||
|     const notes = await getNotes(noteIds); | ||||
|  | ||||
|   | ||||
| @@ -2,7 +2,7 @@ | ||||
|  | ||||
| const sourceIdService = require('../services/source_id'); | ||||
| const sql = require('../services/sql'); | ||||
| const labelService = require('../services/labels'); | ||||
| const attributeService = require('../services/attributes'); | ||||
| const config = require('../services/config'); | ||||
| const optionService = require('../services/options'); | ||||
|  | ||||
| @@ -18,7 +18,7 @@ async function index(req, res) { | ||||
|  | ||||
| async function getAppCss() { | ||||
|     let css = ''; | ||||
|     const notes = labelService.getNotesWithLabel('appCss'); | ||||
|     const notes = attributeService.getNotesWithLabel('appCss'); | ||||
|  | ||||
|     for (const note of await notes) { | ||||
|         css += `/* ${note.noteId} */ | ||||
|   | ||||
| @@ -25,7 +25,7 @@ const sqlRoute = require('./api/sql'); | ||||
| const anonymizationRoute = require('./api/anonymization'); | ||||
| const cleanupRoute = require('./api/cleanup'); | ||||
| const imageRoute = require('./api/image'); | ||||
| const labelsRoute = require('./api/labels'); | ||||
| const attributesRoute = require('./api/attributes'); | ||||
| const scriptRoute = require('./api/script'); | ||||
| const senderRoute = require('./api/sender'); | ||||
| const filesRoute = require('./api/file_upload'); | ||||
| @@ -62,16 +62,21 @@ function apiRoute(method, path, routeHandler) { | ||||
|     route(method, path, [auth.checkApiAuth], routeHandler, apiResultHandler); | ||||
| } | ||||
|  | ||||
| function route(method, path, middleware, routeHandler, resultHandler) { | ||||
| function route(method, path, middleware, routeHandler, resultHandler, transactional = true) { | ||||
|     router[method](path, ...middleware, async (req, res, next) => { | ||||
|         try { | ||||
|             const result = await cls.init(async () => { | ||||
|                 cls.namespace.set('sourceId', req.headers.source_id); | ||||
|                 protectedSessionService.setProtectedSessionId(req); | ||||
|  | ||||
|                 return await sql.transactional(async () => { | ||||
|                 if (transactional) { | ||||
|                     return await sql.transactional(async () => { | ||||
|                         return await routeHandler(req, res, next); | ||||
|                     }); | ||||
|                 } | ||||
|                 else { | ||||
|                     return await routeHandler(req, res, next); | ||||
|                 }); | ||||
|                 } | ||||
|             }); | ||||
|  | ||||
|             if (resultHandler) { | ||||
| @@ -91,7 +96,7 @@ const uploadMiddleware = multer.single('upload'); | ||||
|  | ||||
| function register(app) { | ||||
|     route(GET, '/', [auth.checkAuth], indexRoute.index); | ||||
|     route(GET, '/login', [], loginRoute.loginPage); | ||||
|     route(GET, '/login', [auth.checkAppInitialized], loginRoute.loginPage); | ||||
|     route(POST, '/login', [], loginRoute.login); | ||||
|     route(POST, '/logout', [auth.checkAuth], loginRoute.logout); | ||||
|     route(GET, '/setup', [auth.checkAppNotInitialized], setupRoute.setupPage); | ||||
| @@ -127,10 +132,12 @@ function register(app) { | ||||
|  | ||||
|     route(GET, '/api/notes/:noteId/download', [auth.checkApiAuthOrElectron], filesRoute.downloadFile); | ||||
|  | ||||
|     apiRoute(GET, '/api/notes/:noteId/labels', labelsRoute.getNoteLabels); | ||||
|     apiRoute(PUT, '/api/notes/:noteId/labels', labelsRoute.updateNoteLabels); | ||||
|     apiRoute(GET, '/api/labels/names', labelsRoute.getAllLabelNames); | ||||
|     apiRoute(GET, '/api/labels/values/:labelName', labelsRoute.getValuesForLabel); | ||||
|     apiRoute(GET, '/api/notes/:noteId/attributes', attributesRoute.getEffectiveNoteAttributes); | ||||
|     apiRoute(PUT, '/api/notes/:noteId/attributes', attributesRoute.updateNoteAttributes); | ||||
|     apiRoute(PUT, '/api/notes/:noteId/attribute', attributesRoute.updateNoteAttribute); | ||||
|     apiRoute(DELETE, '/api/notes/:noteId/attributes/:attributeId', attributesRoute.deleteNoteAttribute); | ||||
|     apiRoute(GET, '/api/attributes/names', attributesRoute.getAttributeNames); | ||||
|     apiRoute(GET, '/api/attributes/values/:attributeName', attributesRoute.getValuesForAttribute); | ||||
|  | ||||
|     route(GET, '/api/images/:imageId/:filename', [auth.checkApiAuthOrElectron], imageRoute.returnImage); | ||||
|     route(POST, '/api/images', [auth.checkApiAuthOrElectron, uploadMiddleware], imageRoute.uploadImage, apiResultHandler); | ||||
| @@ -139,9 +146,11 @@ function register(app) { | ||||
|  | ||||
|     apiRoute(GET, '/api/options', optionsApiRoute.getOptions); | ||||
|     apiRoute(PUT, '/api/options/:name/:value', optionsApiRoute.updateOption); | ||||
|     apiRoute(PUT, '/api/options', optionsApiRoute.updateOptions); | ||||
|  | ||||
|     apiRoute(POST, '/api/password/change', passwordApiRoute.changePassword); | ||||
|  | ||||
|     apiRoute(POST, '/api/sync/test', syncApiRoute.testSync); | ||||
|     apiRoute(GET, '/api/sync/check', syncApiRoute.checkSync); | ||||
|     apiRoute(POST, '/api/sync/now', syncApiRoute.syncNow); | ||||
|     apiRoute(POST, '/api/sync/fill-sync-rows', syncApiRoute.fillSyncRows); | ||||
| @@ -149,26 +158,32 @@ function register(app) { | ||||
|     apiRoute(POST, '/api/sync/force-note-sync/:noteId', syncApiRoute.forceNoteSync); | ||||
|     apiRoute(GET, '/api/sync/changed', syncApiRoute.getChanged); | ||||
|     apiRoute(PUT, '/api/sync/update', syncApiRoute.update); | ||||
|     route(GET, '/api/sync/stats', [], syncApiRoute.getStats, apiResultHandler); | ||||
|     apiRoute(POST, '/api/sync/finished', syncApiRoute.syncFinished); | ||||
|  | ||||
|     apiRoute(GET, '/api/event-log', eventLogRoute.getEventLog); | ||||
|  | ||||
|     apiRoute(GET, '/api/recent-notes', recentNotesRoute.getRecentNotes); | ||||
|     apiRoute(PUT, '/api/recent-notes/:branchId/:notePath', recentNotesRoute.addRecentNote); | ||||
|     apiRoute(GET, '/api/app-info', appInfoRoute.getAppInfo); | ||||
|  | ||||
|     route(POST, '/api/setup', [auth.checkAppNotInitialized], setupApiRoute.setup, apiResultHandler); | ||||
|     route(POST, '/api/setup/new-document', [auth.checkAppNotInitialized], setupApiRoute.setupNewDocument, apiResultHandler); | ||||
|     route(POST, '/api/setup/sync-from-server', [auth.checkAppNotInitialized], setupApiRoute.setupSyncFromServer, apiResultHandler, false); | ||||
|     apiRoute(POST, '/api/setup/sync-to-server', setupApiRoute.setupSyncToSyncServer); | ||||
|     route(GET, '/api/setup/sync-seed', [auth.checkBasicAuth], setupApiRoute.getSyncSeed, apiResultHandler); | ||||
|     route(POST, '/api/setup/sync-seed', [auth.checkAppNotInitialized], setupApiRoute.saveSyncSeed, apiResultHandler, false); | ||||
|  | ||||
|     apiRoute(POST, '/api/sql/execute', sqlRoute.execute); | ||||
|     apiRoute(POST, '/api/anonymization/anonymize', anonymizationRoute.anonymize); | ||||
|  | ||||
|     apiRoute(POST, '/api/cleanup/cleanup-soft-deleted-items', cleanupRoute.cleanupSoftDeletedItems); | ||||
|     apiRoute(POST, '/api/cleanup/cleanup-unused-images', cleanupRoute.cleanupUnusedImages); | ||||
|     apiRoute(POST, '/api/cleanup/vacuum-database', cleanupRoute.vacuumDatabase); | ||||
|     // VACUUM requires execution outside of transaction | ||||
|     route(POST, '/api/cleanup/vacuum-database', [auth.checkApiAuthOrElectron], cleanupRoute.vacuumDatabase, apiResultHandler, false); | ||||
|  | ||||
|     apiRoute(POST, '/api/script/exec', scriptRoute.exec); | ||||
|     apiRoute(POST, '/api/script/run/:noteId', scriptRoute.run); | ||||
|     apiRoute(GET, '/api/script/startup', scriptRoute.getStartupBundles); | ||||
|     apiRoute(GET, '/api/script/bundle/:noteId', scriptRoute.getBundle); | ||||
|     apiRoute(GET, '/api/script/relation/:noteId/:relationName', scriptRoute.getRelationBundles); | ||||
|  | ||||
|     route(POST, '/api/sender/login', [], senderRoute.login, apiResultHandler); | ||||
|     route(POST, '/api/sender/image', [auth.checkSenderToken], senderRoute.uploadImage, apiResultHandler); | ||||
|   | ||||
| @@ -1,7 +1,25 @@ | ||||
| "use strict"; | ||||
|  | ||||
| function setupPage(req, res) { | ||||
|     res.render('setup', {}); | ||||
| const sqlInit = require('../services/sql_init'); | ||||
| const setupService = require('../services/setup'); | ||||
|  | ||||
| async function setupPage(req, res) { | ||||
|     if (await sqlInit.isDbInitialized()) { | ||||
|         res.redirect('/'); | ||||
|     } | ||||
|  | ||||
|     // we got here because DB is not completely initialized so if schema exists | ||||
|     // it means we're in sync in progress state. | ||||
|     const syncInProgress = await sqlInit.schemaExists(); | ||||
|  | ||||
|     if (syncInProgress) { | ||||
|         // trigger sync if it's not already running | ||||
|         setupService.triggerSync(); | ||||
|     } | ||||
|  | ||||
|     res.render('setup', { | ||||
|         syncInProgress: syncInProgress | ||||
|     }); | ||||
| } | ||||
|  | ||||
| module.exports = { | ||||
|   | ||||
							
								
								
									
										
											BIN
										
									
								
								src/scripts/Edited files on day.tar
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										
											BIN
										
									
								
								src/scripts/Edited files on day.tar
									
									
									
									
									
										Normal file
									
								
							
										
											Binary file not shown.
										
									
								
							| @@ -3,7 +3,7 @@ | ||||
| const build = require('./build'); | ||||
| const packageJson = require('../../package'); | ||||
|  | ||||
| const APP_DB_VERSION = 100; | ||||
| const APP_DB_VERSION = 111; | ||||
| const SYNC_VERSION = 1; | ||||
|  | ||||
| module.exports = { | ||||
|   | ||||
							
								
								
									
										87
									
								
								src/services/attributes.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										87
									
								
								src/services/attributes.js
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,87 @@ | ||||
| "use strict"; | ||||
|  | ||||
| const repository = require('./repository'); | ||||
| const sql = require('./sql'); | ||||
| const utils = require('./utils'); | ||||
| const Attribute = require('../entities/attribute'); | ||||
|  | ||||
| const BUILTIN_ATTRIBUTES = [ | ||||
|     // label names | ||||
|     { type: 'label', name: 'disableVersioning' }, | ||||
|     { type: 'label', name: 'calendarRoot' }, | ||||
|     { type: 'label', name: 'archived' }, | ||||
|     { type: 'label', name: 'excludeFromExport' }, | ||||
|     { type: 'label', name: 'run' }, | ||||
|     { type: 'label', name: 'manualTransactionHandling' }, | ||||
|     { type: 'label', name: 'disableInclusion' }, | ||||
|     { type: 'label', name: 'appCss' }, | ||||
|     { type: 'label', name: 'hideChildrenOverview' }, | ||||
|  | ||||
|     // relation names | ||||
|     { type: 'relation', name: 'runOnNoteView' }, | ||||
|     { type: 'relation', name: 'runOnNoteTitleChange' }, | ||||
|     { type: 'relation', name: 'runOnAttributeChange' }, | ||||
|     { type: 'relation', name: 'inheritAttributes' } | ||||
| ]; | ||||
|  | ||||
| async function getNotesWithLabel(name, value) { | ||||
|     let notes; | ||||
|  | ||||
|     if (value !== undefined) { | ||||
|         notes = await repository.getEntities(`SELECT notes.* FROM notes JOIN attributes USING(noteId)  | ||||
|           WHERE notes.isDeleted = 0 AND attributes.isDeleted = 0 AND attributes.name = ? AND attributes.value = ?`, [name, value]); | ||||
|     } | ||||
|     else { | ||||
|         notes = await repository.getEntities(`SELECT notes.* FROM notes JOIN attributes USING(noteId)  | ||||
|           WHERE notes.isDeleted = 0 AND attributes.isDeleted = 0 AND attributes.name = ?`, [name]); | ||||
|     } | ||||
|  | ||||
|     return notes; | ||||
| } | ||||
|  | ||||
| async function getNoteWithLabel(name, value) { | ||||
|     const notes = await getNotesWithLabel(name, value); | ||||
|  | ||||
|     return notes.length > 0 ? notes[0] : null; | ||||
| } | ||||
|  | ||||
| async function createLabel(noteId, name, value = "") { | ||||
|     return await createAttribute({ | ||||
|         noteId: noteId, | ||||
|         type: 'label', | ||||
|         name: name, | ||||
|         value: value | ||||
|     }); | ||||
| } | ||||
|  | ||||
| async function createAttribute(attribute) { | ||||
|     return await new Attribute(attribute).save(); | ||||
| } | ||||
|  | ||||
| async function getAttributeNames(type, nameLike) { | ||||
|     const names = await sql.getColumn( | ||||
|         `SELECT DISTINCT name  | ||||
|          FROM attributes  | ||||
|          WHERE isDeleted = 0 | ||||
|            AND type = ? | ||||
|            AND name LIKE '%${utils.sanitizeSql(nameLike)}%'`, [ type ]); | ||||
|  | ||||
|     for (const attribute of BUILTIN_ATTRIBUTES) { | ||||
|         if (attribute.type === type && !names.includes(attribute.name)) { | ||||
|             names.push(attribute.name); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     names.sort(); | ||||
|  | ||||
|     return names; | ||||
| } | ||||
|  | ||||
| module.exports = { | ||||
|     getNotesWithLabel, | ||||
|     getNoteWithLabel, | ||||
|     createLabel, | ||||
|     createAttribute, | ||||
|     getAttributeNames, | ||||
|     BUILTIN_ATTRIBUTES | ||||
| }; | ||||
| @@ -1,12 +1,13 @@ | ||||
| "use strict"; | ||||
|  | ||||
| const migrationService = require('./migration'); | ||||
| const sql = require('./sql'); | ||||
| const sqlInit = require('./sql_init'); | ||||
| const utils = require('./utils'); | ||||
| const passwordEncryptionService = require('./password_encryption'); | ||||
| const optionService = require('./options'); | ||||
|  | ||||
| async function checkAuth(req, res, next) { | ||||
|     if (!await sqlInit.isUserInitialized()) { | ||||
|     if (!await sqlInit.isDbInitialized()) { | ||||
|         res.redirect("setup"); | ||||
|     } | ||||
|     else if (!req.session.loggedIn && !utils.isElectron()) { | ||||
| @@ -37,8 +38,17 @@ async function checkApiAuth(req, res, next) { | ||||
|     } | ||||
| } | ||||
|  | ||||
| async function checkAppInitialized(req, res, next) { | ||||
|     if (!await sqlInit.isDbInitialized()) { | ||||
|         res.redirect("setup"); | ||||
|     } | ||||
|     else { | ||||
|         next(); | ||||
|     } | ||||
| } | ||||
|  | ||||
| async function checkAppNotInitialized(req, res, next) { | ||||
|     if (await sqlInit.isUserInitialized()) { | ||||
|     if (await sqlInit.isDbInitialized()) { | ||||
|         res.status(400).send("App already initialized."); | ||||
|     } | ||||
|     else { | ||||
| @@ -57,10 +67,28 @@ async function checkSenderToken(req, res, next) { | ||||
|     } | ||||
| } | ||||
|  | ||||
| async function checkBasicAuth(req, res, next) { | ||||
|     const header = req.headers.authorization || ''; | ||||
|     const token = header.split(/\s+/).pop() || ''; | ||||
|     const auth = new Buffer.from(token, 'base64').toString(); | ||||
|     const [username, password] = auth.split(/:/); | ||||
|  | ||||
|     const dbUsername = await optionService.getOption('username'); | ||||
|  | ||||
|     if (dbUsername !== username || !await passwordEncryptionService.verifyPassword(password)) { | ||||
|         res.status(401).send("Not authorized"); | ||||
|     } | ||||
|     else { | ||||
|         next(); | ||||
|     } | ||||
| } | ||||
|  | ||||
| module.exports = { | ||||
|     checkAuth, | ||||
|     checkApiAuth, | ||||
|     checkAppInitialized, | ||||
|     checkAppNotInitialized, | ||||
|     checkApiAuthOrElectron, | ||||
|     checkSenderToken | ||||
|     checkSenderToken, | ||||
|     checkBasicAuth | ||||
| }; | ||||
| @@ -10,49 +10,32 @@ const syncMutexService = require('./sync_mutex'); | ||||
| const cls = require('./cls'); | ||||
|  | ||||
| async function regularBackup() { | ||||
|     const now = new Date(); | ||||
|     const lastBackupDate = dateUtils.parseDateTime(await optionService.getOption('lastBackupDate')); | ||||
|     await periodBackup('lastDailyBackupDate', 'daily', 24 * 3600); | ||||
|  | ||||
|     console.log(lastBackupDate); | ||||
|     await periodBackup('lastWeeklyBackupDate', 'weekly', 7 * 24 * 3600); | ||||
|  | ||||
|     if (now.getTime() - lastBackupDate.getTime() > 43200 * 1000) { | ||||
|         await backupNow(); | ||||
|     } | ||||
|  | ||||
|     await cleanupOldBackups(); | ||||
|     await periodBackup('lastMonthlyBackupDate', 'monthly', 30 * 24 * 3600); | ||||
| } | ||||
|  | ||||
| async function backupNow() { | ||||
|     // we don't want to backup DB in the middle of sync with potentially inconsistent DB state | ||||
| async function periodBackup(optionName, fileName, periodInSeconds) { | ||||
|     const now = new Date(); | ||||
|     const lastDailyBackupDate = dateUtils.parseDateTime(await optionService.getOption(optionName)); | ||||
|  | ||||
|     if (now.getTime() - lastDailyBackupDate.getTime() > periodInSeconds * 1000) { | ||||
|         await backupNow(fileName); | ||||
|  | ||||
|         await optionService.setOption(optionName, dateUtils.nowDate()); | ||||
|     } | ||||
| } | ||||
|  | ||||
| async function backupNow(name) { | ||||
|     // we don't want to backup DB in the middle of sync with potentially inconsistent DB state | ||||
|     await syncMutexService.doExclusively(async () => { | ||||
|         const backupFile = dataDir.BACKUP_DIR + "/" + "backup-" + dateUtils.getDateTimeForFile() + ".db"; | ||||
|         const backupFile = `${dataDir.BACKUP_DIR}/backup-${name}.db`; | ||||
|  | ||||
|         fs.copySync(dataDir.DOCUMENT_PATH, backupFile); | ||||
|  | ||||
|         log.info("Created backup at " + backupFile); | ||||
|  | ||||
|         await optionService.setOption('lastBackupDate', dateUtils.nowDate()); | ||||
|     }); | ||||
| } | ||||
|  | ||||
| async function cleanupOldBackups() { | ||||
|     const now = new Date(); | ||||
|  | ||||
|     fs.readdirSync(dataDir.BACKUP_DIR).forEach(file => { | ||||
|         const match = file.match(/backup-([0-9 -:]+)\.db/); | ||||
|  | ||||
|         if (match) { | ||||
|             const date_str = match[1]; | ||||
|  | ||||
|             const date = Date.parse(date_str); | ||||
|  | ||||
|             if (now.getTime() - date.getTime() > 30 * 24 * 3600 * 1000) { | ||||
|                 log.info("Removing old backup - " + file); | ||||
|  | ||||
|                 fs.unlink(dataDir.BACKUP_DIR + "/" + file); | ||||
|             } | ||||
|         } | ||||
|     }); | ||||
| } | ||||
|  | ||||
|   | ||||
| @@ -1 +1 @@ | ||||
| module.exports = { buildDate:"2018-07-09T21:22:12+02:00", buildRevision: "14cffbbe625036d7284056f6a37a5e748e397148" }; | ||||
| module.exports = { buildDate:"2018-08-14T18:06:31+02:00", buildRevision: "6d842a65a2adec832edc82bba14c8616c53fe90b" }; | ||||
|   | ||||
| @@ -1,4 +1,4 @@ | ||||
| module.exports = function(labelFilters) { | ||||
| module.exports = function(attributeFilters) { | ||||
|     const joins = []; | ||||
|     const joinParams = []; | ||||
|     let where = '1'; | ||||
| @@ -6,31 +6,31 @@ module.exports = function(labelFilters) { | ||||
|  | ||||
|     let i = 1; | ||||
|  | ||||
|     for (const filter of labelFilters) { | ||||
|         joins.push(`LEFT JOIN labels AS label${i} ON label${i}.noteId = notes.noteId AND label${i}.name = ?`); | ||||
|     for (const filter of attributeFilters) { | ||||
|         joins.push(`LEFT JOIN attributes AS attribute${i} ON attribute${i}.noteId = notes.noteId AND attribute${i}.name = ? AND attribute${i}.isDeleted = 0`); | ||||
|         joinParams.push(filter.name); | ||||
|  | ||||
|         where += " " + filter.relation + " "; | ||||
|  | ||||
|         if (filter.operator === 'exists') { | ||||
|             where += `label${i}.labelId IS NOT NULL`; | ||||
|             where += `attribute${i}.attributeId IS NOT NULL`; | ||||
|         } | ||||
|         else if (filter.operator === 'not-exists') { | ||||
|             where += `label${i}.labelId IS NULL`; | ||||
|             where += `attribute${i}.attributeId IS NULL`; | ||||
|         } | ||||
|         else if (filter.operator === '=' || filter.operator === '!=') { | ||||
|             where += `label${i}.value ${filter.operator} ?`; | ||||
|             where += `attribute${i}.value ${filter.operator} ?`; | ||||
|             whereParams.push(filter.value); | ||||
|         } | ||||
|         else if ([">", ">=", "<", "<="].includes(filter.operator)) { | ||||
|             const floatParam = parseFloat(filter.value); | ||||
|  | ||||
|             if (isNaN(floatParam)) { | ||||
|                 where += `label${i}.value ${filter.operator} ?`; | ||||
|                 where += `attribute${i}.value ${filter.operator} ?`; | ||||
|                 whereParams.push(filter.value); | ||||
|             } | ||||
|             else { | ||||
|                 where += `CAST(label${i}.value AS DECIMAL) ${filter.operator} ?`; | ||||
|                 where += `CAST(attribute${i}.value AS DECIMAL) ${filter.operator} ?`; | ||||
|                 whereParams.push(floatParam); | ||||
|             } | ||||
|         } | ||||
|   | ||||
| @@ -2,11 +2,13 @@ | ||||
|  | ||||
| const sql = require('./sql'); | ||||
| const syncTable = require('./sync_table'); | ||||
| const tree = require('./tree'); | ||||
| const treeService = require('./tree'); | ||||
| const noteService = require('./notes'); | ||||
| const repository = require('./repository'); | ||||
| const Branch = require('../entities/branch'); | ||||
|  | ||||
| async function cloneNoteToParent(noteId, parentNoteId, prefix) { | ||||
|     const validationResult = await tree.validateParentChild(parentNoteId, noteId); | ||||
|     const validationResult = await treeService.validateParentChild(parentNoteId, noteId); | ||||
|  | ||||
|     if (!validationResult.success) { | ||||
|         return validationResult; | ||||
| @@ -24,10 +26,42 @@ async function cloneNoteToParent(noteId, parentNoteId, prefix) { | ||||
|     return { success: true }; | ||||
| } | ||||
|  | ||||
| async function cloneNoteAfter(noteId, afterBranchId) { | ||||
|     const afterNote = await tree.getBranch(afterBranchId); | ||||
| async function ensureNoteIsPresentInParent(noteId, parentNoteId, prefix) { | ||||
|     const validationResult = await treeService.validateParentChild(parentNoteId, noteId); | ||||
|  | ||||
|     const validationResult = await tree.validateParentChild(afterNote.parentNoteId, noteId); | ||||
|     if (!validationResult.success) { | ||||
|         return validationResult; | ||||
|     } | ||||
|  | ||||
|     await new Branch({ | ||||
|         noteId: noteId, | ||||
|         parentNoteId: parentNoteId, | ||||
|         prefix: prefix, | ||||
|         isExpanded: 0 | ||||
|     }).save(); | ||||
| } | ||||
|  | ||||
| async function ensureNoteIsAbsentFromParent(noteId, parentNoteId) { | ||||
|     const branch = await repository.getEntity(`SELECT * FROM branches WHERE noteId = ? AND parentNoteId = ? AND isDeleted = 0`, [noteId, parentNoteId]); | ||||
|  | ||||
|     if (branch) { | ||||
|         await noteService.deleteNote(branch); | ||||
|     } | ||||
| } | ||||
|  | ||||
| async function toggleNoteInParent(present, noteId, parentNoteId, prefix) { | ||||
|     if (present) { | ||||
|         await ensureNoteIsPresentInParent(noteId, parentNoteId, prefix); | ||||
|     } | ||||
|     else { | ||||
|         await ensureNoteIsAbsentFromParent(noteId, parentNoteId); | ||||
|     } | ||||
| } | ||||
|  | ||||
| async function cloneNoteAfter(noteId, afterBranchId) { | ||||
|     const afterNote = await treeService.getBranch(afterBranchId); | ||||
|  | ||||
|     const validationResult = await treeService.validateParentChild(afterNote.parentNoteId, noteId); | ||||
|  | ||||
|     if (!validationResult.result) { | ||||
|         return validationResult; | ||||
| @@ -52,5 +86,8 @@ async function cloneNoteAfter(noteId, afterBranchId) { | ||||
|  | ||||
| module.exports = { | ||||
|     cloneNoteToParent, | ||||
|     ensureNoteIsPresentInParent, | ||||
|     ensureNoteIsAbsentFromParent, | ||||
|     toggleNoteInParent, | ||||
|     cloneNoteAfter | ||||
| }; | ||||
| @@ -13,9 +13,14 @@ function getSourceId() { | ||||
|     return namespace.get('sourceId'); | ||||
| } | ||||
|  | ||||
| function reset() { | ||||
|     clsHooked.reset(); | ||||
| } | ||||
|  | ||||
| module.exports = { | ||||
|     init, | ||||
|     wrap, | ||||
|     namespace, | ||||
|     getSourceId | ||||
|     getSourceId, | ||||
|     reset | ||||
| }; | ||||
| @@ -3,7 +3,6 @@ | ||||
| const sql = require('./sql'); | ||||
| const sqlInit = require('./sql_init'); | ||||
| const log = require('./log'); | ||||
| const utils = require('./utils'); | ||||
| const messagingService = require('./messaging'); | ||||
| const syncMutexService = require('./sync_mutex'); | ||||
| const cls = require('./cls'); | ||||
| @@ -223,7 +222,7 @@ async function runAllChecks() { | ||||
|     await runSyncRowChecks("recent_notes", "branchId", errorList); | ||||
|     await runSyncRowChecks("images", "imageId", errorList); | ||||
|     await runSyncRowChecks("note_images", "noteImageId", errorList); | ||||
|     await runSyncRowChecks("labels", "labelId", errorList); | ||||
|     await runSyncRowChecks("attributes", "attributeId", errorList); | ||||
|     await runSyncRowChecks("api_tokens", "apiTokenId", errorList); | ||||
|  | ||||
|     if (errorList.length === 0) { | ||||
|   | ||||
| @@ -9,8 +9,8 @@ const ApiToken = require('../entities/api_token'); | ||||
| const Branch = require('../entities/branch'); | ||||
| const Image = require('../entities/image'); | ||||
| const Note = require('../entities/note'); | ||||
| const Attribute = require('../entities/attribute'); | ||||
| const NoteImage = require('../entities/note_image'); | ||||
| const Label = require('../entities/label'); | ||||
| const NoteRevision = require('../entities/note_revision'); | ||||
| const RecentNote = require('../entities/recent_note'); | ||||
| const Option = require('../entities/option'); | ||||
| @@ -40,7 +40,7 @@ async function getHashes() { | ||||
|         options: await getHash(Option, "isSynced = 1"), | ||||
|         images: await getHash(Image), | ||||
|         note_images: await getHash(NoteImage), | ||||
|         labels: await getHash(Label), | ||||
|         attributes: await getHash(Attribute), | ||||
|         api_tokens: await getHash(ApiToken) | ||||
|     }; | ||||
|  | ||||
|   | ||||
| @@ -1,8 +1,7 @@ | ||||
| "use strict"; | ||||
|  | ||||
| const sql = require('./sql'); | ||||
| const noteService = require('./notes'); | ||||
| const labelService = require('./labels'); | ||||
| const attributeService = require('./attributes'); | ||||
| const dateUtils = require('./date_utils'); | ||||
| const repository = require('./repository'); | ||||
|  | ||||
| @@ -32,7 +31,7 @@ async function getNoteStartingWith(parentNoteId, startsWith) { | ||||
|  | ||||
| async function getRootCalendarNote() { | ||||
|     // some caching here could be useful (e.g. in CLS) | ||||
|     let rootNote = await labelService.getNoteWithLabel(CALENDAR_ROOT_LABEL); | ||||
|     let rootNote = await attributeService.getNoteWithLabel(CALENDAR_ROOT_LABEL); | ||||
|  | ||||
|     if (!rootNote) { | ||||
|         rootNote = (await noteService.createNewNote('root', { | ||||
| @@ -41,7 +40,8 @@ async function getRootCalendarNote() { | ||||
|             isProtected: false | ||||
|         })).note; | ||||
|  | ||||
|         await labelService.createLabel(rootNote.noteId, CALENDAR_ROOT_LABEL); | ||||
|         await attributeService.createLabel(rootNote.noteId, CALENDAR_ROOT_LABEL); | ||||
|         await attributeService.createLabel(rootNote.noteId, 'sorted'); | ||||
|     } | ||||
|  | ||||
|     return rootNote; | ||||
| @@ -50,7 +50,7 @@ async function getRootCalendarNote() { | ||||
| async function getYearNote(dateTimeStr, rootNote) { | ||||
|     const yearStr = dateTimeStr.substr(0, 4); | ||||
|  | ||||
|     let yearNote = await labelService.getNoteWithLabel(YEAR_LABEL, yearStr); | ||||
|     let yearNote = await attributeService.getNoteWithLabel(YEAR_LABEL, yearStr); | ||||
|  | ||||
|     if (!yearNote) { | ||||
|         yearNote = await getNoteStartingWith(rootNote.noteId, yearStr); | ||||
| @@ -59,7 +59,8 @@ async function getYearNote(dateTimeStr, rootNote) { | ||||
|             yearNote = await createNote(rootNote.noteId, yearStr); | ||||
|         } | ||||
|  | ||||
|         await labelService.createLabel(yearNote.noteId, YEAR_LABEL, yearStr); | ||||
|         await attributeService.createLabel(yearNote.noteId, YEAR_LABEL, yearStr); | ||||
|         await attributeService.createLabel(yearNote.noteId, 'sorted'); | ||||
|     } | ||||
|  | ||||
|     return yearNote; | ||||
| @@ -69,7 +70,7 @@ async function getMonthNote(dateTimeStr, rootNote) { | ||||
|     const monthStr = dateTimeStr.substr(0, 7); | ||||
|     const monthNumber = dateTimeStr.substr(5, 2); | ||||
|  | ||||
|     let monthNote = await labelService.getNoteWithLabel(MONTH_LABEL, monthStr); | ||||
|     let monthNote = await attributeService.getNoteWithLabel(MONTH_LABEL, monthStr); | ||||
|  | ||||
|     if (!monthNote) { | ||||
|         const yearNote = await getYearNote(dateTimeStr, rootNote); | ||||
| @@ -84,7 +85,8 @@ async function getMonthNote(dateTimeStr, rootNote) { | ||||
|             monthNote = await createNote(yearNote.noteId, noteTitle); | ||||
|         } | ||||
|  | ||||
|         await labelService.createLabel(monthNote.noteId, MONTH_LABEL, monthStr); | ||||
|         await attributeService.createLabel(monthNote.noteId, MONTH_LABEL, monthStr); | ||||
|         await attributeService.createLabel(monthNote.noteId, 'sorted'); | ||||
|     } | ||||
|  | ||||
|     return monthNote; | ||||
| @@ -96,7 +98,7 @@ async function getDateNote(dateTimeStr) { | ||||
|     const dateStr = dateTimeStr.substr(0, 10); | ||||
|     const dayNumber = dateTimeStr.substr(8, 2); | ||||
|  | ||||
|     let dateNote = await labelService.getNoteWithLabel(DATE_LABEL, dateStr); | ||||
|     let dateNote = await attributeService.getNoteWithLabel(DATE_LABEL, dateStr); | ||||
|  | ||||
|     if (!dateNote) { | ||||
|         const monthNote = await getMonthNote(dateTimeStr, rootNote); | ||||
| @@ -111,7 +113,7 @@ async function getDateNote(dateTimeStr) { | ||||
|             dateNote = await createNote(monthNote.noteId, noteTitle); | ||||
|         } | ||||
|  | ||||
|         await labelService.createLabel(dateNote.noteId, DATE_LABEL, dateStr); | ||||
|         await attributeService.createLabel(dateNote.noteId, DATE_LABEL, dateStr); | ||||
|     } | ||||
|  | ||||
|     return dateNote; | ||||
|   | ||||
| @@ -19,6 +19,5 @@ async function addNoteEvent(noteId, comment) { | ||||
| } | ||||
|  | ||||
| module.exports = { | ||||
|     addEvent, | ||||
|     addNoteEvent | ||||
|     addEvent | ||||
| }; | ||||
| @@ -1,3 +1,6 @@ | ||||
| const log = require('./log'); | ||||
|  | ||||
| const NOTE_TITLE_CHANGED = "NOTE_TITLE_CHANGED"; | ||||
| const ENTER_PROTECTED_SESSION = "ENTER_PROTECTED_SESSION"; | ||||
| const ENTITY_CHANGED = "ENTITY_CHANGED"; | ||||
|  | ||||
| @@ -8,13 +11,18 @@ function subscribe(eventType, listener) { | ||||
|     eventListeners[eventType].push(listener); | ||||
| } | ||||
|  | ||||
| function emit(eventType, data) { | ||||
| async function emit(eventType, data) { | ||||
|     const listeners = eventListeners[eventType]; | ||||
|  | ||||
|     if (listeners) { | ||||
|         for (const listener of listeners) { | ||||
|             // not awaiting for async processing | ||||
|             listener(data); | ||||
|             try { | ||||
|                 await listener(data); | ||||
|             } | ||||
|             catch (e) { | ||||
|                 log.error("Listener threw error: " + e.stack); | ||||
|                 // we won't stop execution because of listener | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @@ -23,6 +31,7 @@ module.exports = { | ||||
|     subscribe, | ||||
|     emit, | ||||
|     // event types: | ||||
|     NOTE_TITLE_CHANGED, | ||||
|     ENTER_PROTECTED_SESSION, | ||||
|     ENTITY_CHANGED | ||||
| }; | ||||
							
								
								
									
										40
									
								
								src/services/handlers.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										40
									
								
								src/services/handlers.js
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,40 @@ | ||||
| const eventService = require('./events'); | ||||
| const scriptService = require('./script'); | ||||
| const treeService = require('./tree'); | ||||
| const messagingService = require('./messaging'); | ||||
| const repository = require('./repository'); | ||||
|  | ||||
| async function runAttachedRelations(note, relationName, originEntity) { | ||||
|     const attributes = await note.getAttributes(); | ||||
|     const runRelations = attributes.filter(relation => relation.type === 'relation' && relation.name === relationName); | ||||
|  | ||||
|     for (const relation of runRelations) { | ||||
|         const scriptNote = await relation.getTargetNote(); | ||||
|  | ||||
|         await scriptService.executeNote(scriptNote, originEntity); | ||||
|     } | ||||
| } | ||||
|  | ||||
| eventService.subscribe(eventService.NOTE_TITLE_CHANGED, async note => { | ||||
|     await runAttachedRelations(note, 'runOnNoteTitleChange', note); | ||||
|  | ||||
|     if (!note.isRoot()) { | ||||
|         const parents = await note.getParentNotes(); | ||||
|  | ||||
|         for (const parent of parents) { | ||||
|             if (await parent.hasLabel("sorted")) { | ||||
|                 await treeService.sortNotesAlphabetically(parent.noteId); | ||||
|  | ||||
|                 messagingService.sendMessageToAllClients({ type: 'refresh-tree' }); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| }); | ||||
|  | ||||
| eventService.subscribe(eventService.ENTITY_CHANGED, async ({ entityId, entityName }) => { | ||||
|     if (entityName === 'attributes') { | ||||
|         const attribute = await repository.getEntityFromName(entityName, entityId); | ||||
|  | ||||
|         await runAttachedRelations(await attribute.getNote(), 'runOnAttributeChange', attribute); | ||||
|     } | ||||
| }); | ||||
| @@ -1,52 +0,0 @@ | ||||
| "use strict"; | ||||
|  | ||||
| const repository = require('./repository'); | ||||
| const Label = require('../entities/label'); | ||||
|  | ||||
| const BUILTIN_LABELS = [ | ||||
|     'disableVersioning', | ||||
|     'calendarRoot', | ||||
|     'archived', | ||||
|     'excludeFromExport', | ||||
|     'run', | ||||
|     'manualTransactionHandling', | ||||
|     'disableInclusion', | ||||
|     'appCss', | ||||
|     'hideChildrenOverview' | ||||
| ]; | ||||
|  | ||||
| async function getNotesWithLabel(name, value) { | ||||
|     let notes; | ||||
|  | ||||
|     if (value !== undefined) { | ||||
|         notes = await repository.getEntities(`SELECT notes.* FROM notes JOIN labels USING(noteId)  | ||||
|           WHERE notes.isDeleted = 0 AND labels.isDeleted = 0 AND labels.name = ? AND labels.value = ?`, [name, value]); | ||||
|     } | ||||
|     else { | ||||
|         notes = await repository.getEntities(`SELECT notes.* FROM notes JOIN labels USING(noteId)  | ||||
|           WHERE notes.isDeleted = 0 AND labels.isDeleted = 0 AND labels.name = ?`, [name]); | ||||
|     } | ||||
|  | ||||
|     return notes; | ||||
| } | ||||
|  | ||||
| async function getNoteWithLabel(name, value) { | ||||
|     const notes = await getNotesWithLabel(name, value); | ||||
|  | ||||
|     return notes.length > 0 ? notes[0] : null; | ||||
| } | ||||
|  | ||||
| async function createLabel(noteId, name, value = "") { | ||||
|     return await new Label({ | ||||
|         noteId: noteId, | ||||
|         name: name, | ||||
|         value: value | ||||
|     }).save(); | ||||
| } | ||||
|  | ||||
| module.exports = { | ||||
|     getNotesWithLabel, | ||||
|     getNoteWithLabel, | ||||
|     createLabel, | ||||
|     BUILTIN_LABELS | ||||
| }; | ||||
| @@ -2,8 +2,6 @@ const WebSocket = require('ws'); | ||||
| const utils = require('./utils'); | ||||
| const log = require('./log'); | ||||
| const sql = require('./sql'); | ||||
| const optionService = require('./options'); | ||||
| const syncSetup = require('./sync_setup'); | ||||
|  | ||||
| let webSocketServer; | ||||
|  | ||||
| @@ -65,15 +63,12 @@ async function sendMessageToAllClients(message) { | ||||
|  | ||||
| async function sendPing(client, lastSentSyncId) { | ||||
|     const syncData = await sql.getRows("SELECT * FROM sync WHERE id > ?", [lastSentSyncId]); | ||||
|  | ||||
|     const lastSyncedPush = await optionService.getOption('lastSyncedPush'); | ||||
|  | ||||
|     const changesToPushCount = await sql.getValue("SELECT COUNT(*) FROM sync WHERE id > ?", [lastSyncedPush]); | ||||
|     const stats = require('./sync').stats; | ||||
|  | ||||
|     await sendMessage(client, { | ||||
|         type: 'sync', | ||||
|         data: syncData, | ||||
|         changesToPushCount: syncSetup.isSyncSetup ? changesToPushCount : 0 | ||||
|         outstandingSyncs: stats.outstandingPushes + stats.outstandingPulls | ||||
|     }); | ||||
| } | ||||
|  | ||||
|   | ||||
| @@ -10,7 +10,7 @@ async function migrate() { | ||||
|     const migrations = []; | ||||
|  | ||||
|     // backup before attempting migration | ||||
|     await backupService.backupNow(); | ||||
|     await backupService.backupNow("before-migration"); | ||||
|  | ||||
|     const currentDbVersion = parseInt(await optionService.getOption('dbVersion')); | ||||
|  | ||||
| @@ -56,28 +56,23 @@ async function migrate() { | ||||
|                 else if (mig.type === 'js') { | ||||
|                     console.log("Migration with JS module"); | ||||
|  | ||||
|                     const migrationModule = require("../" + resourceDir.MIGRATIONS_DIR + "/" + mig.file); | ||||
|                     await migrationModule(db); | ||||
|                     const migrationModule = require(resourceDir.MIGRATIONS_DIR + "/" + mig.file); | ||||
|                     await migrationModule(); | ||||
|                 } | ||||
|                 else { | ||||
|                     throw new Error("Unknown migration type " + mig.type); | ||||
|                 } | ||||
|  | ||||
|                 await optionService.setOption("dbVersion", mig.dbVersion); | ||||
|  | ||||
|             }); | ||||
|  | ||||
|             log.info("Migration to version " + mig.dbVersion + " has been successful."); | ||||
|  | ||||
|             mig['success'] = true; | ||||
|         } | ||||
|         catch (e) { | ||||
|             mig['success'] = false; | ||||
|             mig['error'] = e.stack; | ||||
|  | ||||
|             log.error("error during migration to version " + mig.dbVersion + ": " + e.stack); | ||||
|             log.error("migration failed, crashing hard"); // this is not very user friendly :-/ | ||||
|  | ||||
|             break; | ||||
|             process.exit(1); | ||||
|         } | ||||
|         finally { | ||||
|             // make sure foreign keys are enabled even if migration script disables them | ||||
| @@ -85,11 +80,9 @@ async function migrate() { | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     if (sqlInit.isDbUpToDate()) { | ||||
|         sqlInit.setDbReadyAsResolved(); | ||||
|     if (await sqlInit.isDbUpToDate()) { | ||||
|         await sqlInit.initDbConnection(); | ||||
|     } | ||||
|  | ||||
|     return migrations; | ||||
| } | ||||
|  | ||||
| module.exports = { | ||||
|   | ||||
| @@ -5,12 +5,13 @@ const repository = require('./repository'); | ||||
| const protectedSessionService = require('./protected_session'); | ||||
| const utils = require('./utils'); | ||||
|  | ||||
| let loaded = false; | ||||
| let noteTitles; | ||||
| let protectedNoteTitles; | ||||
| let noteIds; | ||||
| let childParentToBranchId = {}; | ||||
| const childToParent = {}; | ||||
| const archived = {}; | ||||
| let archived = {}; | ||||
|  | ||||
| // key is 'childNoteId-parentNoteId' as a replacement for branchId which we don't use here | ||||
| let prefixes = {}; | ||||
| @@ -29,15 +30,13 @@ async function load() { | ||||
|         childParentToBranchId[`${rel.noteId}-${rel.parentNoteId}`] = rel.branchId; | ||||
|     } | ||||
|  | ||||
|     const hiddenLabels = await sql.getColumn(`SELECT noteId FROM labels WHERE isDeleted = 0 AND name = 'archived'`); | ||||
|     archived = await sql.getMap(`SELECT noteId, isInheritable FROM attributes WHERE isDeleted = 0 AND type = 'label' AND name = 'archived'`); | ||||
|  | ||||
|     for (const noteId of hiddenLabels) { | ||||
|         archived[noteId] = true; | ||||
|     } | ||||
|     loaded = true; | ||||
| } | ||||
|  | ||||
| function findNotes(query) { | ||||
|     if (!noteTitles || query.length <= 2) { | ||||
|     if (!noteTitles || !query.length) { | ||||
|         return []; | ||||
|     } | ||||
|  | ||||
| @@ -51,7 +50,8 @@ function findNotes(query) { | ||||
|     } | ||||
|  | ||||
|     for (const noteId of noteIds) { | ||||
|         if (archived[noteId]) { | ||||
|         // for leaf note it doesn't matter if "archived" label inheritable or not | ||||
|         if (noteId in archived) { | ||||
|             continue; | ||||
|         } | ||||
|  | ||||
| @@ -61,7 +61,8 @@ function findNotes(query) { | ||||
|         } | ||||
|  | ||||
|         for (const parentNoteId of parents) { | ||||
|             if (archived[parentNoteId]) { | ||||
|             // for parent note archived needs to be inheritable | ||||
|             if (archived[parentNoteId] === 1) { | ||||
|                 continue; | ||||
|             } | ||||
|  | ||||
| @@ -108,7 +109,7 @@ function search(noteId, tokens, path, results) { | ||||
|     } | ||||
|  | ||||
|     const parents = childToParent[noteId]; | ||||
|     if (!parents) { | ||||
|     if (!parents || noteId === 'root') { | ||||
|         return; | ||||
|     } | ||||
|  | ||||
| @@ -117,11 +118,12 @@ function search(noteId, tokens, path, results) { | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         if (parentNoteId === 'root' || archived[parentNoteId]) { | ||||
|         // archived must be inheritable | ||||
|         if (archived[parentNoteId] === 1) { | ||||
|             continue; | ||||
|         } | ||||
|  | ||||
|         const title = getNoteTitle(noteId, parentNoteId); | ||||
|         const title = getNoteTitle(noteId, parentNoteId).toLowerCase(); | ||||
|         const foundTokens = []; | ||||
|  | ||||
|         for (const token of tokens) { | ||||
| @@ -195,7 +197,8 @@ function getSomePath(noteId, path) { | ||||
|     } | ||||
|  | ||||
|     for (const parentNoteId of parents) { | ||||
|         if (archived[parentNoteId]) { | ||||
|         // archived applies here only if inheritable | ||||
|         if (archived[parentNoteId] === 1) { | ||||
|             continue; | ||||
|         } | ||||
|  | ||||
| @@ -226,6 +229,10 @@ function getNotePath(noteId) { | ||||
| } | ||||
|  | ||||
| eventService.subscribe(eventService.ENTITY_CHANGED, async ({entityName, entityId}) => { | ||||
|     if (!loaded) { | ||||
|         return; | ||||
|     } | ||||
|  | ||||
|     if (entityName === 'notes') { | ||||
|         const note = await repository.getNote(entityId); | ||||
|  | ||||
| @@ -258,25 +265,29 @@ eventService.subscribe(eventService.ENTITY_CHANGED, async ({entityName, entityId | ||||
|             childParentToBranchId[branch.noteId + '-' + branch.parentNoteId] = branch.branchId; | ||||
|         } | ||||
|     } | ||||
|     else if (entityName === 'labels') { | ||||
|         const label = await repository.getLabel(entityId); | ||||
|     else if (entityName === 'attributes') { | ||||
|         const attribute = await repository.getAttribute(entityId); | ||||
|  | ||||
|         if (label.name === 'archived') { | ||||
|         if (attribute.type === 'label' && attribute.name === 'archived') { | ||||
|             // we're not using label object directly, since there might be other non-deleted archived label | ||||
|             const hideLabel = await repository.getEntity(`SELECT * FROM labels WHERE isDeleted = 0  | ||||
|                                  AND name = 'archived' AND noteId = ?`, [label.noteId]); | ||||
|             const hideLabel = await repository.getEntity(`SELECT * FROM attributes WHERE isDeleted = 0 AND type = 'label'  | ||||
|                                  AND name = 'archived' AND noteId = ?`, [attribute.noteId]); | ||||
|  | ||||
|             if (hideLabel) { | ||||
|                 archived[label.noteId] = true; | ||||
|                 archived[attribute.noteId] = hideLabel.isInheritable ? 1 : 0; | ||||
|             } | ||||
|             else { | ||||
|                 delete archived[label.noteId]; | ||||
|                 delete archived[attribute.noteId]; | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| }); | ||||
|  | ||||
| eventService.subscribe(eventService.ENTER_PROTECTED_SESSION, async () => { | ||||
|     if (!loaded) { | ||||
|         return; | ||||
|     } | ||||
|  | ||||
|     protectedNoteTitles = await sql.getMap(`SELECT noteId, title FROM notes WHERE isDeleted = 0 AND isProtected = 1`); | ||||
|  | ||||
|     for (const noteId in protectedNoteTitles) { | ||||
|   | ||||
| @@ -2,7 +2,8 @@ const sql = require('./sql'); | ||||
| const optionService = require('./options'); | ||||
| const dateUtils = require('./date_utils'); | ||||
| const syncTableService = require('./sync_table'); | ||||
| const labelService = require('./labels'); | ||||
| const attributeService = require('./attributes'); | ||||
| const eventService = require('./events'); | ||||
| const repository = require('./repository'); | ||||
| const Note = require('../entities/note'); | ||||
| const NoteImage = require('../entities/note_image'); | ||||
| @@ -34,6 +35,10 @@ async function getNewNotePosition(parentNoteId, noteData) { | ||||
|     return newNotePos; | ||||
| } | ||||
|  | ||||
| async function triggerNoteTitleChanged(note) { | ||||
|     await eventService.emit(eventService.NOTE_TITLE_CHANGED, note); | ||||
| } | ||||
|  | ||||
| async function createNewNote(parentNoteId, noteData) { | ||||
|     const newNotePos = await getNewNotePosition(parentNoteId, noteData); | ||||
|  | ||||
| @@ -60,6 +65,8 @@ async function createNewNote(parentNoteId, noteData) { | ||||
|         isExpanded: 0 | ||||
|     }).save(); | ||||
|  | ||||
|     await triggerNoteTitleChanged(note); | ||||
|  | ||||
|     return { | ||||
|         note, | ||||
|         branch | ||||
| @@ -86,12 +93,17 @@ async function createNote(parentNoteId, title, content = "", extraOptions = {}) | ||||
|  | ||||
|     const {note, branch} = await createNewNote(parentNoteId, noteData); | ||||
|  | ||||
|     if (extraOptions.labels) { | ||||
|         for (const labelName in extraOptions.labels) { | ||||
|             await labelService.createLabel(note.noteId, labelName, extraOptions.labels[labelName]); | ||||
|         } | ||||
|     for (const attr of extraOptions.attributes || []) { | ||||
|         await attributeService.createAttribute({ | ||||
|             noteId: note.noteId, | ||||
|             type: attr.type, | ||||
|             name: attr.name, | ||||
|             value: attr.value | ||||
|         }); | ||||
|     } | ||||
|  | ||||
|     await triggerNoteTitleChanged(note); | ||||
|  | ||||
|     return {note, branch}; | ||||
| } | ||||
|  | ||||
| @@ -159,8 +171,6 @@ async function saveNoteImages(note) { | ||||
| } | ||||
|  | ||||
| async function saveNoteRevision(note) { | ||||
|     const labelsMap = await note.getLabelMap(); | ||||
|  | ||||
|     const now = new Date(); | ||||
|     const noteRevisionSnapshotTimeInterval = parseInt(await optionService.getOption('noteRevisionSnapshotTimeInterval')); | ||||
|  | ||||
| @@ -172,7 +182,7 @@ async function saveNoteRevision(note) { | ||||
|     const msSinceDateCreated = now.getTime() - dateUtils.parseDateTime(note.dateCreated).getTime(); | ||||
|  | ||||
|     if (note.type !== 'file' | ||||
|         && labelsMap.disableVersioning !== 'true' | ||||
|         && await note.hasLabel('disableVersioning') | ||||
|         && !existingnoteRevisionId | ||||
|         && msSinceDateCreated >= noteRevisionSnapshotTimeInterval * 1000) { | ||||
|  | ||||
| @@ -183,7 +193,7 @@ async function saveNoteRevision(note) { | ||||
|             content: note.content, | ||||
|             type: note.type, | ||||
|             mime: note.mime, | ||||
|             isProtected: 0, // will be fixed in the protectNoteRevisions() call | ||||
|             isProtected: false, // will be fixed in the protectNoteRevisions() call | ||||
|             dateModifiedFrom: note.dateModified, | ||||
|             dateModifiedTo: dateUtils.nowDate() | ||||
|         }).save(); | ||||
| @@ -200,18 +210,24 @@ async function updateNote(noteId, noteUpdates) { | ||||
|  | ||||
|     await saveNoteRevision(note); | ||||
|  | ||||
|     const noteTitleChanged = note.title !== noteUpdates.title; | ||||
|  | ||||
|     note.title = noteUpdates.title; | ||||
|     note.setContent(noteUpdates.content); | ||||
|     note.isProtected = noteUpdates.isProtected; | ||||
|     await note.save(); | ||||
|  | ||||
|     if (noteTitleChanged) { | ||||
|         await triggerNoteTitleChanged(note); | ||||
|     } | ||||
|  | ||||
|     await saveNoteImages(note); | ||||
|  | ||||
|     await protectNoteRevisions(note); | ||||
| } | ||||
|  | ||||
| async function deleteNote(branch) { | ||||
|     if (!branch || branch.isDeleted === 1) { | ||||
|     if (!branch || branch.isDeleted) { | ||||
|         return; | ||||
|     } | ||||
|  | ||||
| @@ -223,8 +239,14 @@ async function deleteNote(branch) { | ||||
|  | ||||
|     if (notDeletedBranches.length === 0) { | ||||
|         note.isDeleted = true; | ||||
|         note.content = ''; | ||||
|         await note.save(); | ||||
|  | ||||
|         for (const noteRevision of await note.getRevisions()) { | ||||
|             noteRevision.content = ''; | ||||
|             await noteRevision.save(); | ||||
|         } | ||||
|  | ||||
|         for (const childBranch of await note.getChildBranches()) { | ||||
|             await deleteNote(childBranch); | ||||
|         } | ||||
|   | ||||
Some files were not shown because too many files have changed in this diff Show More
		Reference in New Issue
	
	Block a user