Compare commits

1 Commits

Author SHA1 Message Date
3c80ac3125 Fix bug with error when decoding 2020-07-10 18:54:32 +02:00
27 changed files with 5103 additions and 5023 deletions

7753
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -4,34 +4,48 @@
"description": "",
"main": "index.js",
"scripts": {
"build": "parcel build src/index.html",
"dev": "parcel src/index.html"
"build": "webpack --mode=production",
"watch": "webpack --mode=development --watch",
"start": "webpack-dev-server --mode=production",
"start:prod": "webpack-dev-server --mode=production",
"start:dev": "webpack-dev-server --mode=development"
},
"author": "Fabian Stamm <dev@fabianstamm.de>",
"license": "MIT",
"browserslist": [
"last 2 Chrome versions"
],
"dependencies": {
"@hibas123/secure-file-wrapper": "^2.5.1",
"@hibas123/theme": "^1.2.14",
"@hibas123/utils": "^2.2.3",
"@hibas123/secure-file-wrapper": "^2.5.0",
"@hibas123/theme": "^1.0.5",
"@hibas123/utils": "^2.1.0",
"aes-js": "^3.1.2",
"feather-icons": "^4.26.0",
"feather-icons": "^4.22.1",
"idb": "^4.0.3",
"js-sha256": "^0.9.0",
"lodash.clonedeep": "^4.5.0",
"parcel": "^1.12.4",
"uuid": "^3.4.0"
"secure-file-wrapper": "git+https://git.stamm.me/OpenServer/OSSecureFileWrapper.git",
"uuid": "^3.3.2"
},
"devDependencies": {
"@types/lodash.clonedeep": "^4.5.6",
"@types/uikit": "^2.27.7",
"@types/uuid": "^3.4.7",
"node-sass": "^4.13.1",
"parcel-bundler": "^1.12.4",
"preact": "^10.3.1",
"ts-loader": "^6.2.1",
"typescript": "^3.7.5"
"@types/uuid": "^3.4.5",
"copy-webpack-plugin": "^5.0.3",
"css-loader": "^3.0.0",
"file-loader": "^4.0.0",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.7.0",
"node-sass": "^4.12.0",
"preact": "^8.3.1",
"preact-svg-loader": "^0.2.1",
"raw-loader": "^3.0.0",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"ts-loader": "^6.0.4",
"typescript": "^3.5.2",
"webpack": "^4.35.2",
"webpack-bundle-analyzer": "^3.3.2",
"webpack-cli": "^3.3.5",
"webpack-dev-server": "^3.7.2",
"webpack-visualizer-plugin": "^0.1.11",
"worker-loader": "^2.0.0"
}
}

View File

@ -5,9 +5,16 @@
* @fileoverview Global |this| required for resolving indexes in node.
* @suppress {globalThis}
*/
(function (global) {
(function(global) {
'use strict';
// If we're in node require encoding-indexes and attach it to the global.
if (typeof module !== "undefined" && module.exports &&
!global["encoding-indexes"]) {
global["encoding-indexes"] =
require("./encoding-indexes.js")["encoding-indexes"];
}
//
// Utilities
//
@ -195,7 +202,7 @@
/**
* @return {boolean} True if end-of-stream has been hit.
*/
endOfStream: function () {
endOfStream: function() {
return !this.tokens.length;
},
@ -207,7 +214,7 @@
* @return {number} Get the next token from the stream, or
* end_of_stream.
*/
read: function () {
read: function() {
if (!this.tokens.length)
return end_of_stream;
return this.tokens.pop();
@ -221,7 +228,7 @@
* @param {(number|!Array.<number>)} token The token(s) to prepend to the
* stream.
*/
prepend: function (token) {
prepend: function(token) {
if (Array.isArray(token)) {
var tokens = /**@type {!Array.<number>}*/(token);
while (tokens.length)
@ -239,7 +246,7 @@
* @param {(number|!Array.<number>)} token The tokens(s) to push to the
* stream.
*/
push: function (token) {
push: function(token) {
if (Array.isArray(token)) {
var tokens = /**@type {!Array.<number>}*/(token);
while (tokens.length)
@ -279,7 +286,7 @@
}
/** @interface */
function Decoder() { }
function Decoder() {}
Decoder.prototype = {
/**
* @param {Stream} stream The stream of bytes being decoded.
@ -288,18 +295,18 @@
* decoded, or null if not enough data exists in the input
* stream to decode a complete code point, or |finished|.
*/
handler: function (stream, bite) { }
handler: function(stream, bite) {}
};
/** @interface */
function Encoder() { }
function Encoder() {}
Encoder.prototype = {
/**
* @param {Stream} stream The stream of code points being encoded.
* @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit, or |finished|.
*/
handler: function (stream, code_point) { }
handler: function(stream, code_point) {}
};
// 5.2 Names and labels
@ -791,9 +798,9 @@
// Label to encoding registry.
/** @type {Object.<string,{name:string,labels:Array.<string>}>} */
var label_to_encoding = {};
encodings.forEach(function (category) {
category.encodings.forEach(function (encoding) {
encoding.labels.forEach(function (label) {
encodings.forEach(function(category) {
category.encodings.forEach(function(encoding) {
encoding.labels.forEach(function(label) {
label_to_encoding[label] = encoding;
});
});
@ -922,7 +929,7 @@
// 1. Let index be index jis0208 excluding all entries whose
// pointer is in the range 8272 to 8835, inclusive.
shift_jis_index = shift_jis_index ||
index('jis0208').map(function (code_point, pointer) {
index('jis0208').map(function(code_point, pointer) {
return inRange(pointer, 8272, 8835) ? null : code_point;
});
var index_ = shift_jis_index;
@ -941,7 +948,7 @@
function indexBig5PointerFor(code_point) {
// 1. Let index be index Big5 excluding all entries whose pointer
big5_index_no_hkscs = big5_index_no_hkscs ||
index('big5').map(function (code_point, pointer) {
index('big5').map(function(code_point, pointer) {
return (pointer < (0xA1 - 0x81) * 157) ? null : code_point;
});
var index_ = big5_index_no_hkscs;
@ -1043,21 +1050,21 @@
// The encoding attribute's getter must return encoding's name.
Object.defineProperty(TextDecoder.prototype, 'encoding', {
/** @this {TextDecoder} */
get: function () { return this._encoding.name.toLowerCase(); }
get: function() { return this._encoding.name.toLowerCase(); }
});
// The fatal attribute's getter must return true if error mode
// is fatal, and false otherwise.
Object.defineProperty(TextDecoder.prototype, 'fatal', {
/** @this {TextDecoder} */
get: function () { return this._error_mode === 'fatal'; }
get: function() { return this._error_mode === 'fatal'; }
});
// The ignoreBOM attribute's getter must return true if ignore
// BOM flag is set, and false otherwise.
Object.defineProperty(TextDecoder.prototype, 'ignoreBOM', {
/** @this {TextDecoder} */
get: function () { return this._ignoreBOM; }
get: function() { return this._ignoreBOM; }
});
}
@ -1086,8 +1093,7 @@
// BOM seen flag.
if (!this._do_not_flush) {
this._decoder = decoders[this._encoding.name]({
fatal: this._error_mode === 'fatal'
});
fatal: this._error_mode === 'fatal'});
this._BOMseen = false;
}
@ -1253,7 +1259,7 @@
// The encoding attribute's getter must return encoding's name.
Object.defineProperty(TextEncoder.prototype, 'encoding', {
/** @this {TextEncoder} */
get: function () { return this._encoding.name.toLowerCase(); }
get: function() { return this._encoding.name.toLowerCase(); }
});
}
@ -1271,8 +1277,7 @@
// the input is a USVString so streaming is not necessary.
if (!this._do_not_flush)
this._encoder = encoders[this._encoding.name]({
fatal: this._fatal === 'fatal'
});
fatal: this._fatal === 'fatal'});
this._do_not_flush = Boolean(options['stream']);
// 1. Convert input to a stream.
@ -1351,7 +1356,7 @@
* decoded, or null if not enough data exists in the input
* stream to decode a complete code point.
*/
this.handler = function (stream, bite) {
this.handler = function(stream, bite) {
// 1. If byte is end-of-stream and utf-8 bytes needed is not 0,
// set utf-8 bytes needed to 0 and return error.
if (bite === end_of_stream && utf8_bytes_needed !== 0) {
@ -1479,7 +1484,7 @@
* @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit.
*/
this.handler = function (stream, code_point) {
this.handler = function(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished;
@ -1533,11 +1538,11 @@
}
/** @param {{fatal: boolean}} options */
encoders['UTF-8'] = function (options) {
encoders['UTF-8'] = function(options) {
return new UTF8Encoder(options);
};
/** @param {{fatal: boolean}} options */
decoders['UTF-8'] = function (options) {
decoders['UTF-8'] = function(options) {
return new UTF8Decoder(options);
};
@ -1561,7 +1566,7 @@
* decoded, or null if not enough data exists in the input
* stream to decode a complete code point.
*/
this.handler = function (stream, bite) {
this.handler = function(stream, bite) {
// 1. If byte is end-of-stream, return finished.
if (bite === end_of_stream)
return finished;
@ -1598,7 +1603,7 @@
* @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit.
*/
this.handler = function (stream, code_point) {
this.handler = function(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished;
@ -1621,21 +1626,21 @@
};
}
(function () {
(function() {
if (!('encoding-indexes' in global))
return;
encodings.forEach(function (category) {
encodings.forEach(function(category) {
if (category.heading !== 'Legacy single-byte encodings')
return;
category.encodings.forEach(function (encoding) {
category.encodings.forEach(function(encoding) {
var name = encoding.name;
var idx = index(name.toLowerCase());
/** @param {{fatal: boolean}} options */
decoders[name] = function (options) {
decoders[name] = function(options) {
return new SingleByteDecoder(idx, options);
};
/** @param {{fatal: boolean}} options */
encoders[name] = function (options) {
encoders[name] = function(options) {
return new SingleByteEncoder(idx, options);
};
});
@ -1651,14 +1656,14 @@
// 11.1.1 gbk decoder
// gbk's decoder is gb18030's decoder.
/** @param {{fatal: boolean}} options */
decoders['GBK'] = function (options) {
decoders['GBK'] = function(options) {
return new GB18030Decoder(options);
};
// 11.1.2 gbk encoder
// gbk's encoder is gb18030's encoder with its gbk flag set.
/** @param {{fatal: boolean}} options */
encoders['GBK'] = function (options) {
encoders['GBK'] = function(options) {
return new GB18030Encoder(options, true);
};
@ -1684,7 +1689,7 @@
* decoded, or null if not enough data exists in the input
* stream to decode a complete code point.
*/
this.handler = function (stream, bite) {
this.handler = function(stream, bite) {
// 1. If byte is end-of-stream and gb18030 first, gb18030
// second, and gb18030 third are 0x00, return finished.
if (bite === end_of_stream && gb18030_first === 0x00 &&
@ -1836,7 +1841,7 @@
* @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit.
*/
this.handler = function (stream, code_point) {
this.handler = function(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished;
@ -1911,11 +1916,11 @@
}
/** @param {{fatal: boolean}} options */
encoders['gb18030'] = function (options) {
encoders['gb18030'] = function(options) {
return new GB18030Encoder(options);
};
/** @param {{fatal: boolean}} options */
decoders['gb18030'] = function (options) {
decoders['gb18030'] = function(options) {
return new GB18030Decoder(options);
};
@ -1944,7 +1949,7 @@
* decoded, or null if not enough data exists in the input
* stream to decode a complete code point.
*/
this.handler = function (stream, bite) {
this.handler = function(stream, bite) {
// 1. If byte is end-of-stream and Big5 lead is not 0x00, set
// Big5 lead to 0x00 and return error.
if (bite === end_of_stream && Big5_lead !== 0x00) {
@ -2039,7 +2044,7 @@
* @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit.
*/
this.handler = function (stream, code_point) {
this.handler = function(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished;
@ -2076,11 +2081,11 @@
}
/** @param {{fatal: boolean}} options */
encoders['Big5'] = function (options) {
encoders['Big5'] = function(options) {
return new Big5Encoder(options);
};
/** @param {{fatal: boolean}} options */
decoders['Big5'] = function (options) {
decoders['Big5'] = function(options) {
return new Big5Decoder(options);
};
@ -2112,7 +2117,7 @@
* decoded, or null if not enough data exists in the input
* stream to decode a complete code point.
*/
this.handler = function (stream, bite) {
this.handler = function(stream, bite) {
// 1. If byte is end-of-stream and euc-jp lead is not 0x00, set
// euc-jp lead to 0x00, and return error.
if (bite === end_of_stream && eucjp_lead !== 0x00) {
@ -2207,7 +2212,7 @@
* @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit.
*/
this.handler = function (stream, code_point) {
this.handler = function(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished;
@ -2255,11 +2260,11 @@
}
/** @param {{fatal: boolean}} options */
encoders['EUC-JP'] = function (options) {
encoders['EUC-JP'] = function(options) {
return new EUCJPEncoder(options);
};
/** @param {{fatal: boolean}} options */
decoders['EUC-JP'] = function (options) {
decoders['EUC-JP'] = function(options) {
return new EUCJPDecoder(options);
};
@ -2298,7 +2303,7 @@
* decoded, or null if not enough data exists in the input
* stream to decode a complete code point.
*/
this.handler = function (stream, bite) {
this.handler = function(stream, bite) {
// switching on iso-2022-jp decoder state:
switch (iso2022jp_decoder_state) {
default:
@ -2597,7 +2602,7 @@
* @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit.
*/
this.handler = function (stream, code_point) {
this.handler = function(stream, code_point) {
// 1. If code point is end-of-stream and iso-2022-jp encoder
// state is not ASCII, prepend code point to stream, set
// iso-2022-jp encoder state to ASCII, and return three bytes
@ -2706,11 +2711,11 @@
}
/** @param {{fatal: boolean}} options */
encoders['ISO-2022-JP'] = function (options) {
encoders['ISO-2022-JP'] = function(options) {
return new ISO2022JPEncoder(options);
};
/** @param {{fatal: boolean}} options */
decoders['ISO-2022-JP'] = function (options) {
decoders['ISO-2022-JP'] = function(options) {
return new ISO2022JPDecoder(options);
};
@ -2734,7 +2739,7 @@
* decoded, or null if not enough data exists in the input
* stream to decode a complete code point.
*/
this.handler = function (stream, bite) {
this.handler = function(stream, bite) {
// 1. If byte is end-of-stream and Shift_JIS lead is not 0x00,
// set Shift_JIS lead to 0x00 and return error.
if (bite === end_of_stream && Shift_JIS_lead !== 0x00) {
@ -2828,7 +2833,7 @@
* @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit.
*/
this.handler = function (stream, code_point) {
this.handler = function(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished;
@ -2883,11 +2888,11 @@
}
/** @param {{fatal: boolean}} options */
encoders['Shift_JIS'] = function (options) {
encoders['Shift_JIS'] = function(options) {
return new ShiftJISEncoder(options);
};
/** @param {{fatal: boolean}} options */
decoders['Shift_JIS'] = function (options) {
decoders['Shift_JIS'] = function(options) {
return new ShiftJISDecoder(options);
};
@ -2915,7 +2920,7 @@
* decoded, or null if not enough data exists in the input
* stream to decode a complete code point.
*/
this.handler = function (stream, bite) {
this.handler = function(stream, bite) {
// 1. If byte is end-of-stream and euc-kr lead is not 0x00, set
// euc-kr lead to 0x00 and return error.
if (bite === end_of_stream && euckr_lead !== 0) {
@ -2989,7 +2994,7 @@
* @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit.
*/
this.handler = function (stream, code_point) {
this.handler = function(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished;
@ -3019,11 +3024,11 @@
}
/** @param {{fatal: boolean}} options */
encoders['EUC-KR'] = function (options) {
encoders['EUC-KR'] = function(options) {
return new EUCKREncoder(options);
};
/** @param {{fatal: boolean}} options */
decoders['EUC-KR'] = function (options) {
decoders['EUC-KR'] = function(options) {
return new EUCKRDecoder(options);
};
@ -3076,7 +3081,7 @@
* decoded, or null if not enough data exists in the input
* stream to decode a complete code point.
*/
this.handler = function (stream, bite) {
this.handler = function(stream, bite) {
// 1. If byte is end-of-stream and either utf-16 lead byte or
// utf-16 lead surrogate is not null, set utf-16 lead byte and
// utf-16 lead surrogate to null, and return error.
@ -3166,7 +3171,7 @@
* @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit.
*/
this.handler = function (stream, code_point) {
this.handler = function(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished;
@ -3195,24 +3200,24 @@
// 15.3 utf-16be
// 15.3.1 utf-16be decoder
/** @param {{fatal: boolean}} options */
encoders['UTF-16BE'] = function (options) {
encoders['UTF-16BE'] = function(options) {
return new UTF16Encoder(true, options);
};
// 15.3.2 utf-16be encoder
/** @param {{fatal: boolean}} options */
decoders['UTF-16BE'] = function (options) {
decoders['UTF-16BE'] = function(options) {
return new UTF16Decoder(true, options);
};
// 15.4 utf-16le
// 15.4.1 utf-16le decoder
/** @param {{fatal: boolean}} options */
encoders['UTF-16LE'] = function (options) {
encoders['UTF-16LE'] = function(options) {
return new UTF16Encoder(false, options);
};
// 15.4.2 utf-16le encoder
/** @param {{fatal: boolean}} options */
decoders['UTF-16LE'] = function (options) {
decoders['UTF-16LE'] = function(options) {
return new UTF16Decoder(false, options);
};
@ -3233,7 +3238,7 @@
* decoded, or null if not enough data exists in the input
* stream to decode a complete code point.
*/
this.handler = function (stream, bite) {
this.handler = function(stream, bite) {
// 1. If byte is end-of-stream, return finished.
if (bite === end_of_stream)
return finished;
@ -3261,7 +3266,7 @@
* @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit.
*/
this.handler = function (stream, code_point) {
this.handler = function(stream, code_point) {
// 1.If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished;
@ -3282,11 +3287,11 @@
}
/** @param {{fatal: boolean}} options */
encoders['x-user-defined'] = function (options) {
encoders['x-user-defined'] = function(options) {
return new XUserDefinedEncoder(options);
};
/** @param {{fatal: boolean}} options */
decoders['x-user-defined'] = function (options) {
decoders['x-user-defined'] = function(options) {
return new XUserDefinedDecoder(options);
};
@ -3303,6 +3308,6 @@
};
}
// For strict environments where `this` inside the global scope
// is `undefined`, take a pure object instead
// For strict environments where `this` inside the global scope
// is `undefined`, take a pure object instead
}(this || {}));

View File

@ -7,8 +7,6 @@ export default function AddButton({ onClick }: { onClick: () => void }) {
class="fab btn-primary"
onClick={() => onClick()}
>
<img src={Plus} />
<Plus width={undefined} height={undefined} />
</button>
}
// <Plus width={undefined} height={undefined} />

View File

@ -4,7 +4,10 @@ import Refresh from "feather-icons/dist/icons/refresh-cw.svg";
import "./footer.scss";
import Notifications from "../notifications";
export class Footer extends Component<{}, { synced: boolean, syncing: boolean }> {
export class Footer extends Component<
{},
{ synced: boolean; syncing: boolean }
> {
constructor(props) {
super(props);
this.state = { synced: false, syncing: false };
@ -15,7 +18,7 @@ export class Footer extends Component<{}, { synced: boolean, syncing: boolean }>
async componentWillMount() {
Notes.syncedObservable.subscribe(this.onSyncedChange);
Notes.syncObservable.subscribe(this.onSyncChange);
this.setState({ synced: await Notes.isSynced() })
this.setState({ synced: await Notes.isSynced() });
}
componentWillUnmount() {
@ -25,18 +28,18 @@ export class Footer extends Component<{}, { synced: boolean, syncing: boolean }>
onSyncChange(state: boolean) {
console.log("sync", state);
this.setState({ syncing: state })
this.setState({ syncing: state });
}
onSyncedChange(state: boolean) {
console.log("synced", state);
this.setState({ synced: state })
this.setState({ synced: state });
}
onSyncClick() {
Notes.sync().then(() => {
Notifications.sendInfo("Finished Synchronisation");
})
});
}
render() {
@ -46,7 +49,7 @@ export class Footer extends Component<{}, { synced: boolean, syncing: boolean }>
if (this.state.syncing) {
color = "orange";
text = "syncing";
extrac = "reloading"
extrac = "reloading";
} else {
if (this.state.synced) {
color = "green";
@ -56,12 +59,12 @@ export class Footer extends Component<{}, { synced: boolean, syncing: boolean }>
text = "not synced";
}
}
return <footer class="elv-8">
return (
<footer class="elv-8">
<span>
<span class={extrac} >
<a onClick={() => this.onSyncClick()} >
<img src={Refresh} style="height: 1em; width: 1em;" />
{/* <Refresh style="height: 1em; width: 1em;"></Refresh> */}
<span class={extrac}>
<a onClick={() => this.onSyncClick()}>
<Refresh style="height: 1em; width: 1em;"></Refresh>
</a>
</span>
<span style={"margin-left: 8px; color:" + color}>{text}</span>
@ -69,9 +72,8 @@ export class Footer extends Component<{}, { synced: boolean, syncing: boolean }>
<span>
Welcome <b>{Notes.name}</b>
</span>
<span style="color: lightgrey;">
v1.4
</span>
<span style="color: lightgrey;">v1.5</span>
</footer>
);
}
}

View File

@ -1,4 +1,4 @@
import { h, Component, JSX } from 'preact';
import { h, Component } from 'preact';
import Navigation from '../navigation';
import "./routing.scss"

View File

@ -1,4 +1,4 @@
import { h, JSX } from "preact";
import { h } from "preact";
import "./context.scss";
export default function ContextMenu({ children, event }: { children: JSX.Element | JSX.Element[], event: MouseEvent }) {

View File

@ -1,5 +1,5 @@
import { Observable } from "@hibas123/utils";
import { h, Component, JSX } from "preact";
import { h, Component } from "preact";
import CloseIcon from "feather-icons/dist/icons/x.svg";
export default abstract class Modal<T> {
@ -70,8 +70,7 @@ export default abstract class Modal<T> {
<h3>{this.props.modal.title}</h3>
{/* <div> */}
{!this.props.modal.noClose ?
<img src={CloseIcon} onClick={() => this.props.modal.result(null)} />
// <CloseIcon onClick={() => this.props.modal.result(null)} width={undefined} height={undefined} />
<CloseIcon onClick={() => this.props.modal.result(null)} width={undefined} height={undefined} />
: undefined
}
{/* </div> */}

View File

@ -1,7 +1,7 @@
import { h } from "preact";
import { Page } from "../../page";
import Theme, { ThemeStates } from "../../theme";
import Navigation from "../../navigation";
import { Page } from "../../../page";
import Theme, { ThemeStates } from "../../../theme";
import Navigation from "../../../navigation";
import ArrowLeft from "feather-icons/dist/icons/arrow-left.svg";
export default class SettingsPage extends Page<{ state: any }, { vault: string }> {
@ -13,7 +13,7 @@ export default class SettingsPage extends Page<{ state: any }, { vault: string }
let active = Theme.active();
return <div>
<header class="header">
<a class="header-icon-button" onClick={() => history.back()}><img src={ArrowLeft} height={undefined} width={undefined} /></a>
<a class="header-icon-button" onClick={() => history.back()}><ArrowLeft height={undefined} width={undefined} /></a>
<h3 style="display:inline" class="header-title" onClick={() => Navigation.setPage("/")}>Settings</h3>
<span></span>
</header>

View File

@ -1,7 +1,7 @@
import { h } from "preact";
import { Page } from "../../page";
import VaultsPage from "../Vaults/Vaults";
import Navigation from "../../navigation";
import { Page } from "../../../page";
import VaultsPage from "../vaults/Vaults";
import Navigation from "../../../navigation";
export default class SharePage extends Page<{ state: any }, { vault: string }> {
text: string;

View File

@ -1,12 +1,12 @@
import { h, Component } from "preact"
import { IVault, ViewNote } from "../../notes";
import { IVault, ViewNote } from "../../../notes";
import Trash from "feather-icons/dist/icons/trash-2.svg"
import X from "feather-icons/dist/icons/x.svg"
import Save from "feather-icons/dist/icons/save.svg"
import Navigation from "../../navigation";
import { YesNoModal } from "../../components/modals/YesNoModal";
import Notifications, { MessageType } from "../../notifications";
import Navigation from "../../../navigation";
import { YesNoModal } from "../../modals/YesNoModal";
import Notifications, { MessageType } from "../../../notifications";
const minRows = 3;
export default class EntryComponent extends Component<{ vault: Promise<IVault>, id: string | undefined, note: string | undefined }, { title: string, changed: boolean }> {
@ -166,10 +166,10 @@ export default class EntryComponent extends Component<{ vault: Promise<IVault>,
return <div>
<header class="header">
<a class="header-icon-button" onClick={() => this.exitHandler()}><img src={X} height={undefined} width={undefined} /></a>
{this.state.changed ? <a class="header-icon-button" style="margin-left: 0.5em;" onClick={() => save_handler()}><img src={Save} height={undefined} width={undefined} /></a> : undefined}
<a class="header-icon-button" onClick={() => this.exitHandler()}><X height={undefined} width={undefined} /></a>
{this.state.changed ? <a class="header-icon-button" style="margin-left: 0.5em;" onClick={() => save_handler()}><Save height={undefined} width={undefined} /></a> : undefined}
<h3 style="display:inline" class="button header-title">{this.state.title}</h3>
<a class="header-icon-button" onClick={() => delete_handler()}><img src={Trash} height={undefined} width={undefined} /></a>
<a class="header-icon-button" onClick={() => delete_handler()}><Trash height={undefined} width={undefined} /></a>
</header>
<div class="container">
<textarea

View File

@ -1,11 +1,11 @@
import { h, Component, JSX } from "preact"
import Notes, { IVault, BaseNote } from "../../notes";
import AddButton from "../../components/AddButton";
import Navigation from "../../navigation";
import { h, Component } from "preact"
import Notes, { IVault, BaseNote } from "../../../notes";
import AddButton from "../../AddButton";
import Navigation from "../../../navigation";
import ArrowLeft from "feather-icons/dist/icons/arrow-left.svg"
import Search from "feather-icons/dist/icons/search.svg"
import ContextMenu from "../../components/context";
import Notifications from "../../notifications";
import ContextMenu from "../../context";
import Notifications from "../../../notifications";
import { Observable, Lock } from "@hibas123/utils";
@ -266,7 +266,7 @@ export default class EntryList extends Component<{ vault: Promise<IVault> }, { n
return <div>
{this.state.context}
<header class="header">
<a class="header-icon-button" onClick={() => history.back()}><img src={ArrowLeft} height={undefined} width={undefined} /></a>
<a class="header-icon-button" onClick={() => history.back()}><ArrowLeft height={undefined} width={undefined} /></a>
<h3 style="display:inline" class="header-title" onClick={() => Navigation.setPage("/")}>{this.vault ? this.vault.name : ""}</h3>
<span></span>
{/* <a class="button header_icon_button"><MoreVertival height={undefined} width={undefined} /></a> */}
@ -276,7 +276,7 @@ export default class EntryList extends Component<{ vault: Promise<IVault> }, { n
<div style="display:flex;">
<input class="inp" type="text" style="width: 100%; height: 40px;" onKeyUp={this.searchChanged} ref={elm => this.searchInput = elm} />
<button class="btn btn-primary" style="padding: 5px 10px; margin: 0; height: 40px; width: 40px;">
<img src={Search} />
<Search />
</button>
</div>

View File

@ -1,7 +1,7 @@
import { h } from "preact"
import { Page } from "../../page";
import Notes, { IVault, BaseNote } from "../../notes";
import Navigation from "../../navigation";
import { Page } from "../../../page";
import Notes, { IVault, BaseNote } from "../../../notes";
import Navigation from "../../../navigation";
import EntryComponent from "./Entry";
import EntryList from "./EntryList";

View File

@ -1,16 +1,16 @@
import { h, JSX } from "preact"
import { Page } from "../../page";
import Notes, { VaultList } from "../../notes";
import { h } from "preact"
import { Page } from "../../../page";
import Notes, { VaultList } from "../../../notes";
import "./vaults.scss"
import Lock from "feather-icons/dist/icons/lock.svg";
import Unlock from "feather-icons/dist/icons/unlock.svg";
import Settings from "feather-icons/dist/icons/settings.svg"
import Navigation from "../../navigation";
import { InputModal } from "../../components/modals/InputModal";
import { YesNoModal } from "../../components/modals/YesNoModal";
import AddButton from "../../components/AddButton";
import ContextMenu from "../../components/context";
import Notifications from "../../notifications";
import Navigation from "../../../navigation";
import { InputModal } from "../../modals/InputModal";
import { YesNoModal } from "../../modals/YesNoModal";
import AddButton from "../../AddButton";
import ContextMenu from "../../context";
import Notifications from "../../../notifications";
export interface VaultsProps {
state: any;
@ -206,13 +206,9 @@ export default class VaultsPage extends Page<VaultsProps, { vaults: VaultList, m
}
render() {
// <Unlock height={undefined} width={undefined} />}
// <Lock height={undefined} width={undefined} />
let elms = this.state.vaults.map(vault => {
return <li class="vaults_vault" onClick={() => this.openVault(vault)} onContextMenu={(evt) => this.onContext(evt, vault)}>
{vault.encrypted ? <img src={Lock} /> : <img src={Unlock} />}
{vault.encrypted ? <Lock height={undefined} width={undefined} /> : <Unlock height={undefined} width={undefined} />}
<span>
{vault.name}
</span>
@ -225,10 +221,7 @@ export default class VaultsPage extends Page<VaultsProps, { vaults: VaultList, m
<header class="header">
<span></span>
<h3 style="display:inline" onClick={() => Navigation.setPage("/")}>{this.props.selectVault ? "Select Vault for share" : "Your vaults:"}</h3>
<a class="header-icon-button" onClick={() => Navigation.setPage("/settings")}>
<img src={Settings} />
{/* <Settings height={undefined} width={undefined} /> */}
</a>
<a class="header-icon-button" onClick={() => Navigation.setPage("/settings")}><Settings height={undefined} width={undefined} /></a>
</header>
<AddButton onClick={() => this.addButtonClick()} />
<div class="container">

View File

@ -6,7 +6,7 @@
<meta charset="utf8" />
<meta name="Description" content="Notes app">
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="manifest" href="./manifest.json">
<link rel="manifest" href="/manifest.json">
<!-- <link rel="shortcut icon" href="/public/icon-72x72.png"> -->
<!-- Add to home screen for Safari on iOS -->
@ -15,9 +15,9 @@
<meta name="apple-mobile-web-app-title" content="Secure Notes">
<!-- <link rel="apple-touch-icon" sizes="180x180" href="../public/apple-touch-icon.png"> -->
<!-- <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#1E88E5"> -->
<script src="./encoding.js"></script>
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#1E88E5">
<script src="encoding.js"></script>
<meta name="msapplication-TileColor" content="#1E88E5">
<meta name="theme-color" content="#1E88E5">
</head>
@ -45,7 +45,7 @@
console.warn("Disabling Service Worker in debug mode!")
} else {
// Register the ServiceWorker
navigator.serviceWorker.register('./serviceworker.ts', {
navigator.serviceWorker.register('/serviceworker.js', {
scope: '/'
}).then(function (reg) {
console.log('Service worker has been registered for scope:' + reg.scope);
@ -56,7 +56,6 @@
}
}
</script>
<script src="./index.tsx"></script>
</body>
</html>

View File

@ -9,48 +9,48 @@ body {
// display: flex;
// }
$header-margin: .5em;
// $header-margin: .5em;
// $header-icon-size: calc(1.5rem * 1);
// $header-icon-size: 100%;
header {
display: flex;
justify-content: space-between;
margin-bottom: $header-margin;
align-content: center;
padding: 0.75em;
border-bottom: solid var(--border-color) 1px;
background-color: var(--primary);
// header {
// display: flex;
// justify-content: space-between;
// margin-bottom: $header-margin;
// align-content: center;
// padding: 0.75em;
// border-bottom: solid var(--border-color) 1px;
// background-color: var(--primary);
>* {
margin: 0;
color: white;
background: var(--primary);
}
// >* {
// margin: 0;
// color: white;
// background: var(--primary);
// }
>.header-title {
overflow: hidden;
text-overflow: ellipsis;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
flex-grow: 1;
margin: 0 1em;
}
// >.header-title {
// overflow: hidden;
// text-overflow: ellipsis;
// text-overflow: ellipsis;
// white-space: nowrap;
// overflow: hidden;
// flex-grow: 1;
// margin: 0 1em;
// }
.header-icon-button {
display: block;
margin-top: auto;
margin-bottom: auto;
// min-width: $header-icon-size;
// .header-icon-button {
// display: block;
// margin-top: auto;
// margin-bottom: auto;
// min-width: $header-icon-size;
// >svg {
// height: $header-icon-size;
// width: $header-icon-size;
// }
}
// >svg {
// height: $header-icon-size;
// width: $header-icon-size;
// }
// }
}
// }
body {

View File

@ -72,16 +72,16 @@ import "@hibas123/theme/out/base.css"
import "./index.scss";
import Navigation from './navigation';
import VaultsPage from './Views/Vaults/Vaults';
import VaultsPage from './components/routes/vaults/Vaults';
import { Page } from './page';
import Notes from "./notes"
import DemoPage from './components/demo';
import VaultPage from './Views/Vault/Vault';
import SharePage from './Views/Share/Share';
import VaultPage from './components/routes/vault/Vault';
import SharePage from './components/routes/share/Share';
import Notifications from './notifications';
import Error404Page from './Views/404';
import SettingsPage from './Views/Settings/Settings';
import Error404Page from './components/routes/404';
import SettingsPage from './components/routes/settings/Settings';
window.debug.notes = Notes;

View File

@ -1,6 +1,6 @@
import { Observable } from "@hibas123/utils";
import { Page, PageProps } from "./page";
import { h, VNode, JSX } from "preact";
import { h, VNode } from "preact";
function serializQuery(obj: any) {
var str = [];

View File

@ -3,13 +3,12 @@ import { Lock, Observable } from "@hibas123/utils";
import * as aesjs from "aes-js";
import { IDBPTransaction } from "idb";
import { sha256 } from "js-sha256";
import uuidv4 from "uuid/v4";
import * as uuidv4 from "uuid/v4";
import * as config from "../config.json";
import * as b64 from "./helper/base64";
import IDB from "./helper/indexeddb";
import Notifications, { MessageType } from "./notifications";
export class HttpError extends Error {
constructor(public status: number, public statusText: string) {
super(statusText);
@ -39,7 +38,6 @@ export interface ViewNote extends BaseNote {
}
import clonedeep = require("lodash.clonedeep");
import uuid = require("uuid");
const Encoder = new TextEncoder();
const Decoder = new TextDecoder();
@ -47,7 +45,7 @@ const Decoder = new TextDecoder();
enum OpLogType {
CREATE,
CHANGE,
DELETE
DELETE,
}
interface OpLog {
@ -60,8 +58,8 @@ interface OpLog {
* The value
*/
values: {
value: Uint8Array,
preview: Uint8Array
value: Uint8Array;
preview: Uint8Array;
};
/**
@ -70,42 +68,43 @@ interface OpLog {
date: Date;
}
export type VaultList = { name: string, encrypted: boolean, id: string }[];
export type VaultList = { name: string; encrypted: boolean; id: string }[];
export interface IVault {
name: string;
id: string;
encrypted: boolean;
getAllNotes(): Promise<BaseNote[]>;
searchNote(term: string): Promise<BaseNote[]>
searchNote(term: string): Promise<BaseNote[]>;
newNote(): ViewNote;
saveNote(note: ViewNote, date?: Date): Promise<void>;
getNote(id: string): Promise<ViewNote>;
deleteNote(id: string): Promise<void>;
// type: string; //Defines type of plugin, that is required to handle this vault
}
const awaitTimeout = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));
const awaitTimeout = (ms: number) =>
new Promise<void>((resolve) => setTimeout(resolve, ms));
class NotesProvider {
private notesObservableServer = new Observable<Note>()
public notesObservable = this.notesObservableServer.getPublicApi()
private notesObservableServer = new Observable<Note>();
public notesObservable = this.notesObservableServer.getPublicApi();
private syncObservableServer = new Observable<boolean>()
private syncObservableServer = new Observable<boolean>();
/**
* Will send false once finished and true on start
*/
public syncObservable = this.syncObservableServer.getPublicApi()
public syncObservable = this.syncObservableServer.getPublicApi();
private database = new IDB("notes", ["notes", "oplog"]);
private noteDB = this.database.getStore<DBNote>("notes");
private oplogDB = this.database.getStore<{ id: string, logs: OpLog[] }>("oplog");
private oplogDB = this.database.getStore<{ id: string; logs: OpLog[] }>(
"oplog"
);
private vaultKeys = new Map<string, Uint8Array>();
public apiLock = new Lock();
public apiLockRls = this.apiLock.getLock()
public apiLockRls = this.apiLock.getLock();
private syncLock = new Lock();
@ -117,7 +116,7 @@ class NotesProvider {
public syncedObservable = this.syncedObservableServer.getPublicApi();
public async isSynced() {
return (await this.oplogDB.getAll()).length <= 0
return (await this.oplogDB.getAll()).length <= 0;
}
private _name;
@ -130,11 +129,17 @@ class NotesProvider {
}
login() {
window.location.href = `${config.auth_server}/auth?client_id=${config.client_id}&scope=${config.permission}&redirect_uri=${encodeURIComponent(config.callback_url)}&response_type=code`
window.location.href = `${config.auth_server}/auth?client_id=${
config.client_id
}&scope=${config.permission}&redirect_uri=${encodeURIComponent(
config.callback_url
)}&response_type=code`;
}
async getToken(code: string) {
let req = await fetch(`${config.auth_server}/api/oauth/refresh?grant_type=authorization_code&client_id=${config.client_id}&code=${code}`);
let req = await fetch(
`${config.auth_server}/api/oauth/refresh?grant_type=authorization_code&client_id=${config.client_id}&code=${code}`
);
let res = await req.json();
if (!res.error) {
localStorage.setItem("refreshtoken", res.token);
@ -142,9 +147,9 @@ class NotesProvider {
this._name = res.profile.name;
let kb = this.passwordToKey(res.profile.enc_key);
localStorage.setItem("enc_key", b64.encode(kb));
this.generalEncryption = kb
this.generalEncryption = kb;
} else {
return "Invalid Code"
return "Invalid Code";
}
}
@ -157,11 +162,11 @@ class NotesProvider {
} catch (err) {
callback(err, null);
}
})
});
let key = localStorage.getItem("enc_key");
if (key) {
this.generalEncryption = b64.decode(key)
this.generalEncryption = b64.decode(key);
}
this._name = localStorage.getItem("name");
}
@ -170,34 +175,42 @@ class NotesProvider {
const next = () => {
setTimeout(() => {
this.sync().then(next);
}, 30000)
}
this.syncedObservableServer.send((await this.oplogDB.getAll()).length <= 0);
let prs = this.apiLockRls.then(lock => lock.release());
prs.then(() => awaitTimeout(2000)).then(() => this.sync()).then(() => next());
}, 30000);
};
this.syncedObservableServer.send(
(await this.oplogDB.getAll()).length <= 0
);
let prs = this.apiLockRls.then((lock) => lock.release());
prs.then(() => awaitTimeout(2000))
.then(() => this.sync())
.then(() => next());
return prs;
}
private async getJWT() {
let lock = await this.apiLock.getLock()
let lock = await this.apiLock.getLock();
try {
console.log("Getting JWT");
let req = await fetch(config.auth_server + "/api/oauth/jwt?refreshtoken=" + localStorage.getItem("refreshtoken"));
let req = await fetch(
config.auth_server +
"/api/oauth/jwt?refreshtoken=" +
localStorage.getItem("refreshtoken")
);
if (req.status !== 200) {
Notifications.sendNotification("offline", MessageType.INFO);
throw new Error("Offline")
throw new Error("Offline");
}
let res = await req.json();
if (res.error) {
console.log("Refresh token invalid, forward to login")
console.log("Refresh token invalid, forward to login");
localStorage.removeItem("refreshtoken");
this.login()
throw new Error("Need login!")
this.login();
throw new Error("Need login!");
} else {
return res.token
return res.token;
}
} finally {
lock.release()
lock.release();
}
}
@ -207,29 +220,38 @@ class NotesProvider {
}
async sync() {
const lock = await this.syncLock.getLock()
const lock = await this.syncLock.getLock();
const log = (...message: any[]) => {
console.log("[SYNC]: ", ...message)
}
console.log("[SYNC]: ", ...message);
};
this.syncObservableServer.send(true);
log("Start")
log("Start");
try {
log("Fetching");
let [remotes, locals, oplogs] = await Promise.all([this._secureFile.list(), this.noteDB.getAll(), this.oplogDB.getAll()]);
let [remotes, locals, oplogs] = await Promise.all([
this._secureFile.list(),
this.noteDB.getAll(),
this.oplogDB.getAll(),
]);
log("Fetched");
// Create sync pairs (remote & local)
log("Building pairs");
let pairs: { local: DBNote, remote: IFile, id: string, oplog: OpLog[] }[] = [];
remotes.map(r => {
let lIdx = locals.findIndex(e => e._id === r._id);
let pairs: {
local: DBNote;
remote: IFile;
id: string;
oplog: OpLog[];
}[] = [];
remotes.map((r) => {
let lIdx = locals.findIndex((e) => e._id === r._id);
let l: DBNote = undefined;
if (lIdx >= 0) {
l = locals[lIdx];
locals.splice(lIdx, 1);
}
let oIdx = oplogs.findIndex(e => e.id === r._id);
let oIdx = oplogs.findIndex((e) => e.id === r._id);
let oplog: OpLog[];
if (oIdx >= 0) {
oplog = oplogs[oIdx].logs;
@ -240,12 +262,12 @@ class NotesProvider {
remote: r,
local: l,
oplog,
id: r._id
})
})
id: r._id,
});
});
locals.forEach(l => {
let oIdx = oplogs.findIndex(e => e.id === l._id);
locals.forEach((l) => {
let oIdx = oplogs.findIndex((e) => e.id === l._id);
let oplog: OpLog[] = undefined;
if (oIdx >= 0) {
oplog = oplogs[oIdx].logs;
@ -257,20 +279,20 @@ class NotesProvider {
remote: undefined,
local: l,
oplog,
id: l._id
})
})
id: l._id,
});
});
oplogs.forEach(oplog => {
oplogs.forEach((oplog) => {
if (!oplog) return;
if (oplog.logs.length > 0)
pairs.push({
remote: undefined,
local: undefined,
oplog: oplog.logs,
id: oplog.id
})
})
id: oplog.id,
});
});
log("Pairs builded");
@ -281,8 +303,8 @@ class NotesProvider {
local_change: 0,
local_delete: 0,
do_nothing: 0,
error: 0
}
error: 0,
};
log("Start inspection");
for (let { local, remote, oplog, id } of pairs) {
@ -293,13 +315,19 @@ class NotesProvider {
case OpLogType.CHANGE:
log(id, "REMOTE CHANGE");
stats.remote_change++;
await this._secureFile.update(id, op.values.value, b64.encode(op.values.preview), op.date, old);
await this._secureFile.update(
id,
op.values.value,
b64.encode(op.values.preview),
op.date,
old
);
break;
case OpLogType.DELETE:
log(id, "REMOTE DELETE");
stats.remote_delete++;
if (old) break; // if the deletion is old, just ignore
await this._secureFile.delete(id)
await this._secureFile.delete(id);
break;
case OpLogType.CREATE:
log(id, "REMOTE CREATE");
@ -316,11 +344,11 @@ class NotesProvider {
break;
}
}
}
};
const localChange = (id: string) => {
//TODO implement
}
};
const create = async () => {
log(id, "LOCAL CREATAE/UPDATE");
@ -329,42 +357,43 @@ class NotesProvider {
let note: DBNote = {
_id: remote._id,
folder: remote.folder,
preview: b64.decode(remote.active.preview),
preview: b64.decode(remote.active.preview || ""),
time: remote.active.time,
__value: new Uint8Array(value)
}
__value: new Uint8Array(value),
};
await this.noteDB.set(id, note);
localChange(id);
}
};
try {
// log(id, "LRO: ", !!local, !!remote, !!oplog)
if (remote && !oplog) {
if (local) {
let old = remote.active.time.valueOf() > local.time.valueOf();
if (old)
await create()
let old =
remote.active.time.valueOf() > local.time.valueOf();
if (old) await create();
else {
stats.do_nothing++;
log(id, "DO NOTHING");
}
} else {
await create()
await create();
}
} else if (!remote && local && !oplog) { // No local changes, but remote deleted
} else if (!remote && local && !oplog) {
// No local changes, but remote deleted
log("LOCAL DELETE");
stats.local_delete++;
await this.noteDB.delete(id);
localChange(id);
} else if (!remote && oplog) { // Remote does not exist, but oplog, just apply all changes including possible delete
await apply()
} else if (!remote && oplog) {
// Remote does not exist, but oplog, just apply all changes including possible delete
await apply();
} else if (remote && oplog) {
let last = oplog[oplog.length - 1]
let last = oplog[oplog.length - 1];
let old = remote.active.time.valueOf() > last.date.valueOf();
if (old)
await create() // Will recreate local entry
await apply(old) // Will apply changes to remote
if (old) await create(); // Will recreate local entry
await apply(old); // Will apply changes to remote
} else {
log(id, "DO NOTHING");
stats.do_nothing++;
@ -372,15 +401,20 @@ class NotesProvider {
} catch (err) {
console.error(err);
stats.error++;
Notifications.sendNotification("Error syncing: " + id, MessageType.ERROR);
Notifications.sendNotification(
"Error syncing: " + id,
MessageType.ERROR
);
}
await this.oplogDB.delete(id);
}
log("Stats", stats);
this.syncedObservableServer.send((await this.oplogDB.getAll()).length <= 0)
this.syncedObservableServer.send(
(await this.oplogDB.getAll()).length <= 0
);
} finally {
log("Finished")
lock.release()
log("Finished");
lock.release();
this.syncObservableServer.send(false);
}
}
@ -410,53 +444,62 @@ class NotesProvider {
}
public getVaults(): Promise<VaultList> {
return this.noteDB.getAll()
.then(notes => notes
.filter(e => Decoder.decode(e.preview) === "__VAULT__")
.map(e => {
return this.noteDB.getAll().then((notes) =>
notes
.filter((e) => Decoder.decode(e.preview) === "__VAULT__")
.map((e) => {
let value = e.__value;
let encrypted = false;
if (this.decrypt(value) !== "__BASELINE__") encrypted = true;
return { name: e.folder, encrypted, id: e._id }
}));
return { name: e.folder, encrypted, id: e._id };
})
);
}
public async createVault(name: string, key?: Uint8Array) {
// console.log(uuidv4, uuid);
let vault: DBNote = {
__value: this.encrypt("__BASELINE__", key),
_id: uuidv4(),
folder: name,
preview: Encoder.encode("__VAULT__"),
time: new Date()
}
time: new Date(),
};
let tx = this.database.transaction();
await Promise.all([
this.addop(vault._id, OpLogType.CREATE, {
this.addop(
vault._id,
OpLogType.CREATE,
{
value: vault.__value,
preview: vault.preview
}, vault.time, tx),
this.noteDB.set(vault._id, vault)
preview: vault.preview,
},
vault.time,
tx
),
this.noteDB.set(vault._id, vault),
]);
}
public async getVault(vault_id: string, key?: Uint8Array): Promise<IVault> {
let vault = await this.noteDB.get(vault_id);
if (!vault) throw new Error("Vault not found!");
if (this.decrypt(vault.__value, key) !== "__BASELINE__") throw new Error("Invalid password!");
return new NotesProvider.Vault(vault, key)
if (this.decrypt(vault.__value, key) !== "__BASELINE__")
throw new Error("Invalid password!");
return new NotesProvider.Vault(vault, key);
}
public async deleteVault(vault_id: string) {
let vault = await this.noteDB.get(vault_id);
if (!vault) throw new Error("Vault not found!");
let v = new NotesProvider.Vault(vault);
await Promise.all((await v.getAllNotes()).map(note => this.delete(note._id)));
await Promise.all(
(await v.getAllNotes()).map((note) => this.delete(note._id))
);
await this.delete(v.id); // This can also delete a vault
}
public passwordToKey(password: string) {
return new Uint8Array(sha256.arrayBuffer(password + config.client_id))
return new Uint8Array(sha256.arrayBuffer(password + config.client_id));
}
private _encrypt(value: Uint8Array, key?: Uint8Array): Uint8Array {
@ -467,42 +510,48 @@ class NotesProvider {
}
private encrypt(value: string, key?: Uint8Array): Uint8Array {
let msg = this._encrypt(Encoder.encode(value), key)
return new Uint8Array(this._encrypt(msg, this.generalEncryption))
let msg = this._encrypt(Encoder.encode(value), key);
return new Uint8Array(this._encrypt(msg, this.generalEncryption));
}
private _decrypt(value: ArrayBuffer, key?: Uint8Array): Uint8Array {
if (!key) return new Uint8Array(value);
var aesCtr = new aesjs.ModeOfOperation.ctr(key);
var decryptedBytes = aesCtr.decrypt(value);
return new Uint8Array(decryptedBytes)
return new Uint8Array(decryptedBytes);
}
private decrypt(value: ArrayBuffer, key?: Uint8Array): string {
let msg = this._decrypt(value, key)
return Decoder.decode(this._decrypt(msg, this.generalEncryption))
let msg = this._decrypt(value, key);
return Decoder.decode(this._decrypt(msg, this.generalEncryption));
}
async addop(note_id: string, type: OpLogType, values: { value: Uint8Array, preview: Uint8Array }, date: Date, transaction?: IDBPTransaction<unknown, string[]>) {
async addop(
note_id: string,
type: OpLogType,
values: { value: Uint8Array; preview: Uint8Array },
date: Date,
transaction?: IDBPTransaction<unknown, string[]>
) {
let tx = transaction || this.oplogDB.transaction();
let oplog = await this.oplogDB.get(note_id, tx);
if (!oplog) oplog = { logs: [], id: note_id };
oplog.logs.push({
date: date,
type,
values
})
values,
});
this.syncedObservableServer.send(false);
await this.oplogDB.set(note_id, oplog, tx);
}
async delete(id: string) {
let lock = await this.syncLock.getLock();
let tx = this.database.transaction(this.oplogDB, this.noteDB)
let tx = this.database.transaction(this.oplogDB, this.noteDB);
await Promise.all([
this.addop(id, OpLogType.DELETE, null, new Date(), tx),
this.noteDB.delete(id, tx)
])
this.noteDB.delete(id, tx),
]);
lock.release();
}
@ -525,15 +574,17 @@ class NotesProvider {
}
async getAllNotes() {
return Notes.noteDB.getAll()
.then(all => all.filter(e => e.folder === this.vault._id)
return Notes.noteDB.getAll().then((all) =>
all
.filter((e) => e.folder === this.vault._id)
.sort(this.sort)
.map<BaseNote>(e => {
let new_note = clonedeep(<Note>e) as BaseNote
delete (<any>new_note).__value
new_note.preview = this.decrypt(e.preview)
.map<BaseNote>((e) => {
let new_note = clonedeep(<Note>e) as BaseNote;
delete (<any>new_note).__value;
new_note.preview = this.decrypt(e.preview);
return new_note;
}));
})
);
}
private sort(a: DBNote, b: DBNote) {
@ -542,7 +593,7 @@ class NotesProvider {
async searchNote(term: string) {
let all = await this.getAllNotes();
return all.filter(e => e.preview.indexOf(term) >= 0)
return all.filter((e) => e.preview.indexOf(term) >= 0);
}
newNote(): ViewNote {
@ -551,8 +602,8 @@ class NotesProvider {
folder: this.vault._id,
time: new Date(),
__value: "",
preview: ""
}
preview: "",
};
}
async saveNote(note: ViewNote, date = new Date()) {
@ -561,20 +612,26 @@ class NotesProvider {
let old_note = await Notes.noteDB.get(note._id, tx);
let new_note = clonedeep(<Note>note) as DBNote;
new_note.__value = this.encrypt(note.__value)
new_note.__value = this.encrypt(note.__value);
let [title, preview] = note.__value.split("\n");
if (preview) preview = "\n" + preview;
else preview = ""
new_note.preview = this.encrypt((title + preview).substr(0, 128))
else preview = "";
new_note.preview = this.encrypt((title + preview).substr(0, 128));
new_note.time = date;
await Promise.all([
Notes.addop(note._id, !old_note ? OpLogType.CREATE : OpLogType.CHANGE, {
Notes.addop(
note._id,
!old_note ? OpLogType.CREATE : OpLogType.CHANGE,
{
value: new_note.__value,
preview: new_note.preview
}, date, tx),
Notes.noteDB.set(note._id, new_note, tx)
])
preview: new_note.preview,
},
date,
tx
),
Notes.noteDB.set(note._id, new_note, tx),
]);
lock.release();
}
@ -589,10 +646,10 @@ class NotesProvider {
deleteNote(id: string) {
return Notes.delete(id);
}
}
};
}
const Notes = new NotesProvider()
const Notes = new NotesProvider();
export default Notes;
(<any>window).api = Notes
(<any>window).api = Notes;

View File

@ -1,7 +1,5 @@
import { readFileSync } from "fs";
const light = readFileSync("./node_modules/@hibas123/theme/out/light.css", "utf8")
const dark = readFileSync("./node_modules/@hibas123/theme/out/dark.css", "utf8")
const light = require("!!raw-loader!@hibas123/theme/out/light.css").default;
const dark = require("!!raw-loader!@hibas123/theme/out/dark.css").default;
export enum ThemeStates {
AUTO,

17
src/types.d.ts vendored
View File

@ -1,15 +1,10 @@
// declare module "*.svg" {
// const SVG: (props: {
// width?: number | undefined
// height?: number | undefined
// onClick?: (evt: MouseEvent) => void;
// style?: string;
// }) => JSX.Element;
// export default SVG;
// }
declare module "*.svg" {
const SVG: string;
const SVG: (props: {
width?: number | undefined
height?: number | undefined
onClick?: (evt: MouseEvent) => void;
style?: string;
}) => JSX.Element;
export default SVG;
}

View File

@ -13,8 +13,7 @@
"dom",
"esnext"
],
"resolveJsonModule": true,
"esModuleInterop": true
"resolveJsonModule": true
},
"include": [
"./src/types.d.ts",