@jr2804/livesync-cli 1.0.23-cli.1 → 1.0.28-cli.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1919 -1457
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -126,49 +126,71 @@ var EventHub = class {
|
|
|
126
126
|
});
|
|
127
127
|
this._emitter = emitter ?? new EventTarget();
|
|
128
128
|
}
|
|
129
|
-
_issueSignal(key, callback) {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
129
|
+
_issueSignal(key, callback, sourceSignal) {
|
|
130
|
+
const controller = new AbortController();
|
|
131
|
+
const controllerRef = new FallbackWeakRef(controller);
|
|
132
|
+
const assigned = this._assigned.get(key) ?? /* @__PURE__ */ new WeakMap();
|
|
133
|
+
const callbackControllers = assigned.get(callback) ?? /* @__PURE__ */ new Set();
|
|
134
|
+
const allAssigned = this._allAssigned.get(key) ?? /* @__PURE__ */ new Set();
|
|
135
|
+
const abortFromSource = () => controller.abort();
|
|
136
|
+
controller.signal.addEventListener("abort", () => {
|
|
137
|
+
sourceSignal?.removeEventListener("abort", abortFromSource);
|
|
138
|
+
callbackControllers.delete(controllerRef);
|
|
139
|
+
if (callbackControllers.size === 0) assigned.delete(callback);
|
|
140
|
+
allAssigned.delete(controllerRef);
|
|
141
|
+
if (allAssigned.size === 0) {
|
|
142
|
+
this._assigned.delete(key);
|
|
143
|
+
this._allAssigned.delete(key);
|
|
144
|
+
}
|
|
145
|
+
}, { once: true });
|
|
146
|
+
callbackControllers.add(controllerRef);
|
|
147
|
+
assigned.set(callback, callbackControllers);
|
|
148
|
+
this._assigned.set(key, assigned);
|
|
149
|
+
allAssigned.add(controllerRef);
|
|
150
|
+
this._allAssigned.set(key, allAssigned);
|
|
151
|
+
if (sourceSignal) {
|
|
152
|
+
sourceSignal.addEventListener("abort", abortFromSource, { once: true });
|
|
153
|
+
if (sourceSignal.aborted) controller.abort();
|
|
146
154
|
}
|
|
147
155
|
return controller;
|
|
148
156
|
}
|
|
157
|
+
_listen(key, callback, listener, options) {
|
|
158
|
+
const controller = this._issueSignal(key, callback, options?.signal);
|
|
159
|
+
const controlledListener = options?.once ? (event) => {
|
|
160
|
+
try {
|
|
161
|
+
listener(event);
|
|
162
|
+
} finally {
|
|
163
|
+
controller.abort();
|
|
164
|
+
}
|
|
165
|
+
} : listener;
|
|
166
|
+
this._emitter.addEventListener(key, controlledListener, {
|
|
167
|
+
...options,
|
|
168
|
+
signal: controller.signal
|
|
169
|
+
});
|
|
170
|
+
return controller;
|
|
171
|
+
}
|
|
149
172
|
emitEvent(event, data) {
|
|
150
173
|
this._emitter.dispatchEvent(new CustomEvent(`${event.toString()}`, { detail: data ?? void 0 }));
|
|
151
174
|
}
|
|
152
175
|
on(event, callback, options) {
|
|
153
176
|
const onEvent = (e) => void callback(e, e instanceof CustomEvent ? e?.detail : void 0);
|
|
154
177
|
const key = event;
|
|
155
|
-
const controller = this.
|
|
156
|
-
|
|
157
|
-
...options,
|
|
158
|
-
signal: controller.signal
|
|
159
|
-
});
|
|
160
|
-
return () => this.off(event, callback);
|
|
178
|
+
const controller = this._listen(key, callback, onEvent, options);
|
|
179
|
+
return () => controller.abort();
|
|
161
180
|
}
|
|
162
181
|
/**
|
|
163
|
-
* Removes
|
|
164
|
-
*
|
|
165
|
-
*
|
|
182
|
+
* Removes current event registrations in bulk.
|
|
183
|
+
*
|
|
184
|
+
* Prefer the disposer returned by `on`, `onEvent`, `once`, or `onceEvent` when removing one registration.
|
|
185
|
+
*
|
|
186
|
+
* @param event - The event whose registrations should be removed.
|
|
187
|
+
* @param callback - The callback whose registrations should be removed. Omit it to remove every registration for the event.
|
|
166
188
|
*/
|
|
167
189
|
off(event, callback) {
|
|
168
190
|
const key = event;
|
|
169
|
-
if (callback) (
|
|
170
|
-
else this._allAssigned.get(key)?.forEach((
|
|
171
|
-
|
|
191
|
+
if (callback) (this._assigned.get(key)?.get(callback))?.forEach((controllerRef) => controllerRef.deref()?.abort());
|
|
192
|
+
else this._allAssigned.get(key)?.forEach((controllerRef) => {
|
|
193
|
+
controllerRef.deref()?.abort();
|
|
172
194
|
});
|
|
173
195
|
}
|
|
174
196
|
/**
|
|
@@ -180,18 +202,20 @@ var EventHub = class {
|
|
|
180
202
|
onEvent(event, callback, options) {
|
|
181
203
|
const onEvent = (e) => void callback(e instanceof CustomEvent ? e?.detail : void 0);
|
|
182
204
|
const key = event;
|
|
183
|
-
const controller = this.
|
|
184
|
-
|
|
205
|
+
const controller = this._listen(key, callback, onEvent, options);
|
|
206
|
+
return () => controller.abort();
|
|
207
|
+
}
|
|
208
|
+
once(event, callback, options) {
|
|
209
|
+
return this.on(event, callback, {
|
|
185
210
|
...options,
|
|
186
|
-
|
|
211
|
+
once: true
|
|
187
212
|
});
|
|
188
|
-
return () => this.off(event, callback);
|
|
189
|
-
}
|
|
190
|
-
once(event, callback) {
|
|
191
|
-
return this.on(event, callback, { once: true });
|
|
192
213
|
}
|
|
193
|
-
onceEvent(event, callback) {
|
|
194
|
-
return this.on(event, (_, data) => callback(data), {
|
|
214
|
+
onceEvent(event, callback, options) {
|
|
215
|
+
return this.on(event, (_, data) => callback(data), {
|
|
216
|
+
...options,
|
|
217
|
+
once: true
|
|
218
|
+
});
|
|
195
219
|
}
|
|
196
220
|
waitFor(event) {
|
|
197
221
|
return new Promise((resolve) => {
|
|
@@ -909,7 +933,6 @@ function isLockAcquired(key) {
|
|
|
909
933
|
var RESULT_TIMED_OUT = Symbol("timed out");
|
|
910
934
|
//#endregion
|
|
911
935
|
//#region ../../../node_modules/octagonal-wheels/dist/bureau/SlipBoard.js
|
|
912
|
-
var GENERIC_COMPATIBILITY_VALUE = "x-compatibility-value";
|
|
913
936
|
var SlipBoard = class {
|
|
914
937
|
constructor() {
|
|
915
938
|
Object.defineProperty(this, "_clip", {
|
|
@@ -1035,15 +1058,7 @@ var SlipBoard = class {
|
|
|
1035
1058
|
if (taskPromise) taskPromise.reject(reason);
|
|
1036
1059
|
}
|
|
1037
1060
|
};
|
|
1038
|
-
|
|
1039
|
-
/**
|
|
1040
|
-
* Sends a value to the specified ID.
|
|
1041
|
-
* @param id - The ID to send the value to.
|
|
1042
|
-
* @param result - The value to send.
|
|
1043
|
-
*/
|
|
1044
|
-
function sendValue(id, result) {
|
|
1045
|
-
globalSlipBoard.submit(GENERIC_COMPATIBILITY_VALUE, id, result);
|
|
1046
|
-
}
|
|
1061
|
+
new SlipBoard();
|
|
1047
1062
|
//#endregion
|
|
1048
1063
|
//#region ../../../node_modules/octagonal-wheels/dist/concurrency/task.js
|
|
1049
1064
|
function unwrapTaskResult(result) {
|
|
@@ -4612,38 +4627,114 @@ var DEFAULT_SYNC_PARAMETERS = {
|
|
|
4612
4627
|
};
|
|
4613
4628
|
//#endregion
|
|
4614
4629
|
//#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/common/models/tweak.definition.js
|
|
4615
|
-
var
|
|
4616
|
-
|
|
4617
|
-
|
|
4618
|
-
|
|
4619
|
-
|
|
4620
|
-
|
|
4621
|
-
|
|
4622
|
-
|
|
4623
|
-
|
|
4624
|
-
|
|
4625
|
-
|
|
4626
|
-
|
|
4627
|
-
|
|
4628
|
-
|
|
4629
|
-
|
|
4630
|
-
|
|
4631
|
-
|
|
4632
|
-
|
|
4633
|
-
|
|
4634
|
-
|
|
4635
|
-
|
|
4636
|
-
|
|
4637
|
-
|
|
4638
|
-
|
|
4639
|
-
|
|
4640
|
-
|
|
4641
|
-
|
|
4642
|
-
|
|
4643
|
-
|
|
4644
|
-
|
|
4645
|
-
|
|
4646
|
-
|
|
4630
|
+
var TweakCompatibilityRules = Object.freeze([
|
|
4631
|
+
{
|
|
4632
|
+
key: "minimumChunkSize",
|
|
4633
|
+
templateValue: 20,
|
|
4634
|
+
reconstruction: "none"
|
|
4635
|
+
},
|
|
4636
|
+
{
|
|
4637
|
+
key: "longLineThreshold",
|
|
4638
|
+
templateValue: 250,
|
|
4639
|
+
reconstruction: "none"
|
|
4640
|
+
},
|
|
4641
|
+
{
|
|
4642
|
+
key: "encrypt",
|
|
4643
|
+
templateValue: false,
|
|
4644
|
+
reconstruction: "required"
|
|
4645
|
+
},
|
|
4646
|
+
{
|
|
4647
|
+
key: "usePathObfuscation",
|
|
4648
|
+
templateValue: false,
|
|
4649
|
+
reconstruction: "required"
|
|
4650
|
+
},
|
|
4651
|
+
{
|
|
4652
|
+
key: "enableCompression",
|
|
4653
|
+
templateValue: false,
|
|
4654
|
+
reconstruction: "none"
|
|
4655
|
+
},
|
|
4656
|
+
{
|
|
4657
|
+
key: "useEden",
|
|
4658
|
+
templateValue: false,
|
|
4659
|
+
reconstruction: "none"
|
|
4660
|
+
},
|
|
4661
|
+
{
|
|
4662
|
+
key: "customChunkSize",
|
|
4663
|
+
templateValue: 0,
|
|
4664
|
+
reconstruction: "recommended",
|
|
4665
|
+
compatibleLossyOrder: 1
|
|
4666
|
+
},
|
|
4667
|
+
{
|
|
4668
|
+
key: "useDynamicIterationCount",
|
|
4669
|
+
templateValue: false,
|
|
4670
|
+
reconstruction: "required"
|
|
4671
|
+
},
|
|
4672
|
+
{
|
|
4673
|
+
key: "hashAlg",
|
|
4674
|
+
templateValue: "xxhash64",
|
|
4675
|
+
reconstruction: "recommended",
|
|
4676
|
+
compatibleLossyOrder: 0
|
|
4677
|
+
},
|
|
4678
|
+
{
|
|
4679
|
+
key: "enableChunkSplitterV2",
|
|
4680
|
+
templateValue: false,
|
|
4681
|
+
reconstruction: "none"
|
|
4682
|
+
},
|
|
4683
|
+
{
|
|
4684
|
+
key: "maxChunksInEden",
|
|
4685
|
+
templateValue: 10,
|
|
4686
|
+
reconstruction: "none"
|
|
4687
|
+
},
|
|
4688
|
+
{
|
|
4689
|
+
key: "maxTotalLengthInEden",
|
|
4690
|
+
templateValue: 1024,
|
|
4691
|
+
reconstruction: "none"
|
|
4692
|
+
},
|
|
4693
|
+
{
|
|
4694
|
+
key: "maxAgeInEden",
|
|
4695
|
+
templateValue: 10,
|
|
4696
|
+
reconstruction: "none"
|
|
4697
|
+
},
|
|
4698
|
+
{
|
|
4699
|
+
key: "usePluginSyncV2",
|
|
4700
|
+
templateValue: false,
|
|
4701
|
+
reconstruction: "none",
|
|
4702
|
+
knownDefault: false
|
|
4703
|
+
},
|
|
4704
|
+
{
|
|
4705
|
+
key: "handleFilenameCaseSensitive",
|
|
4706
|
+
templateValue: false,
|
|
4707
|
+
reconstruction: "required",
|
|
4708
|
+
knownDefault: false
|
|
4709
|
+
},
|
|
4710
|
+
{
|
|
4711
|
+
key: "useSegmenter",
|
|
4712
|
+
templateValue: false,
|
|
4713
|
+
reconstruction: "none"
|
|
4714
|
+
},
|
|
4715
|
+
{
|
|
4716
|
+
key: "E2EEAlgorithm",
|
|
4717
|
+
templateValue: E2EEAlgorithms.V2,
|
|
4718
|
+
reconstruction: "none",
|
|
4719
|
+
knownDefault: DEFAULT_SETTINGS.E2EEAlgorithm
|
|
4720
|
+
},
|
|
4721
|
+
{
|
|
4722
|
+
key: "chunkSplitterVersion",
|
|
4723
|
+
templateValue: ChunkAlgorithms.RabinKarp,
|
|
4724
|
+
reconstruction: "recommended",
|
|
4725
|
+
knownDefault: DEFAULT_SETTINGS.chunkSplitterVersion,
|
|
4726
|
+
compatibleLossyOrder: 2
|
|
4727
|
+
}
|
|
4728
|
+
]);
|
|
4729
|
+
var TweakValuesShouldMatchedTemplate = Object.fromEntries(TweakCompatibilityRules.map(({ key, templateValue }) => [key, templateValue]));
|
|
4730
|
+
[...TweakCompatibilityRules.filter(({ reconstruction }) => reconstruction === "required").map(({ key }) => key)];
|
|
4731
|
+
TweakCompatibilityRules.filter((rule) => "compatibleLossyOrder" in rule).slice().sort((left, right) => left.compatibleLossyOrder - right.compatibleLossyOrder).map(({ key }) => key);
|
|
4732
|
+
TweakCompatibilityRules.flatMap((rule) => (rule.specificPatterns ?? []).map((pattern) => ({
|
|
4733
|
+
key: rule.key,
|
|
4734
|
+
...Object.prototype.hasOwnProperty.call(pattern, "from") ? { from: pattern.from } : {},
|
|
4735
|
+
...Object.prototype.hasOwnProperty.call(pattern, "to") ? { to: pattern.to } : {},
|
|
4736
|
+
...pattern.reconstruction === "recommended" ? { isRecommendation: true } : {}
|
|
4737
|
+
})));
|
|
4647
4738
|
var TweakValuesRecommendedTemplate = {
|
|
4648
4739
|
useIgnoreFiles: false,
|
|
4649
4740
|
useCustomRequestHandler: false,
|
|
@@ -4663,12 +4754,7 @@ var TweakValuesRecommendedTemplate = {
|
|
|
4663
4754
|
E2EEAlgorithm: E2EEAlgorithms.V2,
|
|
4664
4755
|
chunkSplitterVersion: ChunkAlgorithms.RabinKarp
|
|
4665
4756
|
};
|
|
4666
|
-
|
|
4667
|
-
usePluginSyncV2: false,
|
|
4668
|
-
E2EEAlgorithm: DEFAULT_SETTINGS.E2EEAlgorithm,
|
|
4669
|
-
chunkSplitterVersion: DEFAULT_SETTINGS.chunkSplitterVersion,
|
|
4670
|
-
tweakModified: DEFAULT_SETTINGS.tweakModified
|
|
4671
|
-
};
|
|
4757
|
+
({ ...Object.fromEntries(TweakCompatibilityRules.filter((rule) => "knownDefault" in rule && rule.key !== "handleFilenameCaseSensitive").map(({ key, knownDefault }) => [key, knownDefault])) }), DEFAULT_SETTINGS.tweakModified;
|
|
4672
4758
|
var TweakValuesTemplate = {
|
|
4673
4759
|
...TweakValuesRecommendedTemplate,
|
|
4674
4760
|
...TweakValuesShouldMatchedTemplate,
|
|
@@ -6526,6 +6612,28 @@ var AllHandler = class extends BooleanHandlerBase {
|
|
|
6526
6612
|
return true;
|
|
6527
6613
|
}
|
|
6528
6614
|
};
|
|
6615
|
+
var AllWithResultHandler = class extends MultiBinder {
|
|
6616
|
+
/**
|
|
6617
|
+
* Invokes every handler in order. The first non-boolean continuation result
|
|
6618
|
+
* is retained, but every remaining handler can still reject the operation.
|
|
6619
|
+
* @param args The arguments to pass to the handlers.
|
|
6620
|
+
* @returns False after any failure, otherwise the retained result or true.
|
|
6621
|
+
*/
|
|
6622
|
+
async invoke(...args) {
|
|
6623
|
+
let aggregateResult = true;
|
|
6624
|
+
const callbacks = [...this._callbacks];
|
|
6625
|
+
for (const callback of callbacks) try {
|
|
6626
|
+
const result = await Promise.resolve(callback(...args));
|
|
6627
|
+
if (result === false) return false;
|
|
6628
|
+
if (aggregateResult === true && result !== true) aggregateResult = result;
|
|
6629
|
+
} catch (error) {
|
|
6630
|
+
Logger(`AllWithResultHandler ${this._name} treated error as failure!`, 16);
|
|
6631
|
+
Logger(error, 16);
|
|
6632
|
+
return false;
|
|
6633
|
+
}
|
|
6634
|
+
return aggregateResult;
|
|
6635
|
+
}
|
|
6636
|
+
};
|
|
6529
6637
|
var SettledAllHandler = class extends BooleanHandlerBase {
|
|
6530
6638
|
/**
|
|
6531
6639
|
* Invokes every handler in order, treating a false result or an exception
|
|
@@ -6619,6 +6727,9 @@ function allSettledFunction(name) {
|
|
|
6619
6727
|
function bailFirstFailureFunction(name) {
|
|
6620
6728
|
return getMultipleBound(new AllHandler(name ?? "bailFirstFailureFunction"));
|
|
6621
6729
|
}
|
|
6730
|
+
function bailFirstFailureWithResultFunction(name) {
|
|
6731
|
+
return getMultipleBound(new AllWithResultHandler(name ?? "bailFirstFailureWithResultFunction"));
|
|
6732
|
+
}
|
|
6622
6733
|
function allParallelFunction(name) {
|
|
6623
6734
|
return getMultipleBound(new ParallelAllHandler(name ?? "allParallelFunction"));
|
|
6624
6735
|
}
|
|
@@ -6683,6 +6794,16 @@ function handlers() {
|
|
|
6683
6794
|
return bailFirstFailureFunction(String(name));
|
|
6684
6795
|
},
|
|
6685
6796
|
/**
|
|
6797
|
+
* Create a handler that preserves a non-boolean continuation result, but
|
|
6798
|
+
* still invokes later handlers so that false results and exceptions
|
|
6799
|
+
* can reject the operation.
|
|
6800
|
+
* @param name
|
|
6801
|
+
* @returns
|
|
6802
|
+
*/
|
|
6803
|
+
bailFirstFailureWithResult(name) {
|
|
6804
|
+
return bailFirstFailureWithResultFunction(String(name));
|
|
6805
|
+
},
|
|
6806
|
+
/**
|
|
6686
6807
|
* Create a handler that invokes all added handler functions sequentially until one returns true.
|
|
6687
6808
|
* @param name
|
|
6688
6809
|
* @returns
|
|
@@ -6925,7 +7046,7 @@ var DatabaseEventService = class extends ServiceBase {
|
|
|
6925
7046
|
* @param reopenDatabase Whether to reopen the database if it is already open.
|
|
6926
7047
|
* @param ignoreSuspending Whether to ignore any suspending state.
|
|
6927
7048
|
*/
|
|
6928
|
-
initialiseDatabase = handlers().
|
|
7049
|
+
initialiseDatabase = handlers().bailFirstFailureWithResult("initialiseDatabase");
|
|
6929
7050
|
};
|
|
6930
7051
|
//#endregion
|
|
6931
7052
|
//#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/services/implements/injectable/InjectableDatabaseEventService.js
|
|
@@ -7132,7 +7253,7 @@ function createReplicationReadinessEvaluator(dependencies) {
|
|
|
7132
7253
|
name: "application-ready",
|
|
7133
7254
|
evaluate: () => {
|
|
7134
7255
|
if (gates.isApplicationReady()) return true;
|
|
7135
|
-
diagnostics.log("
|
|
7256
|
+
diagnostics.log("Replication is not ready because application initialisation has not completed.");
|
|
7136
7257
|
return false;
|
|
7137
7258
|
}
|
|
7138
7259
|
},
|
|
@@ -7623,29 +7744,32 @@ var ReplicationService = class extends ServiceBase {
|
|
|
7623
7744
|
*
|
|
7624
7745
|
* Each attempt owns a separate reservation. Compatibility recovery runs
|
|
7625
7746
|
* between those reservations, and a retry is admitted only when the exact
|
|
7626
|
-
* first-attempt context remains active.
|
|
7627
|
-
*
|
|
7747
|
+
* first-attempt context remains active. Each attempt uses a detached settings
|
|
7748
|
+
* snapshot, and a compatibility retry captures its snapshot after recovery.
|
|
7628
7749
|
*/
|
|
7629
7750
|
async performDirectionalReplication(direction, showingNotice, admission = DIRECTIONAL_REPLICATION_ADMISSION.ORDINARY) {
|
|
7630
7751
|
if (direction === DIRECTIONAL_REPLICATION.UPLOAD && !await this.onBeforeReplicate(showingNotice)) {
|
|
7631
7752
|
this._log(this.context.translate("Replicator.Message.SomeModuleFailed"), 64);
|
|
7632
7753
|
return false;
|
|
7633
7754
|
}
|
|
7634
|
-
const
|
|
7635
|
-
|
|
7636
|
-
|
|
7755
|
+
const captureSetting = () => {
|
|
7756
|
+
const detachedSetting = asCopy(this.settingService.currentSettings());
|
|
7757
|
+
if (admission === DIRECTIONAL_REPLICATION_ADMISSION.EXPLICIT_REBUILD) detachedSetting.versionUpFlash = "";
|
|
7758
|
+
return Object.freeze(detachedSetting);
|
|
7759
|
+
};
|
|
7760
|
+
const setting = captureSetting();
|
|
7637
7761
|
let expectedContext;
|
|
7638
|
-
const run = async () => {
|
|
7762
|
+
const run = async (attemptSetting) => {
|
|
7639
7763
|
const admitted = await this.replicatorService.runWithActiveReplicatorContext((context) => {
|
|
7640
7764
|
if (expectedContext && context !== expectedContext) return replicationBlocked("not-ready");
|
|
7641
7765
|
expectedContext ??= context;
|
|
7642
|
-
return runDirectionalReplication(context,
|
|
7766
|
+
return runDirectionalReplication(context, attemptSetting, direction, showingNotice);
|
|
7643
7767
|
});
|
|
7644
7768
|
if (admitted) return admitted;
|
|
7645
7769
|
this._log(`Active replicator not found during directional ${direction}`, 64);
|
|
7646
7770
|
return replicationBlocked("no-active-replicator");
|
|
7647
7771
|
};
|
|
7648
|
-
const outcome = await run();
|
|
7772
|
+
const outcome = await run(setting);
|
|
7649
7773
|
if (isReplicationCompleted(outcome)) return true;
|
|
7650
7774
|
if (outcome.status !== "failed") return false;
|
|
7651
7775
|
const failedContext = expectedContext;
|
|
@@ -7655,7 +7779,7 @@ var ReplicationService = class extends ServiceBase {
|
|
|
7655
7779
|
setting,
|
|
7656
7780
|
outcome
|
|
7657
7781
|
});
|
|
7658
|
-
return await this.checkConnectionFailure(failure) === "CHECKAGAIN" && isReplicationCompleted(await run());
|
|
7782
|
+
return await this.checkConnectionFailure(failure) === "CHECKAGAIN" && isReplicationCompleted(await run(captureSetting()));
|
|
7659
7783
|
}
|
|
7660
7784
|
async replicateAllToRemote(showingNotice = false) {
|
|
7661
7785
|
if (!this.appLifecycleService.isReady()) return false;
|
|
@@ -8285,7 +8409,7 @@ var VaultService = class extends ServiceBase {
|
|
|
8285
8409
|
* @param showingNotice Whether to show a notice to the user.
|
|
8286
8410
|
* @param ignoreSuspending Whether to ignore any suspending state.
|
|
8287
8411
|
*/
|
|
8288
|
-
scanVault = handlers().
|
|
8412
|
+
scanVault = handlers().bailFirstFailureWithResult("scanVault");
|
|
8289
8413
|
/**
|
|
8290
8414
|
* Check if a file is ignored by the ignore file (e.g., .gitignore, .obsidianignore).
|
|
8291
8415
|
* @param file The file path or file info stub to check.
|
|
@@ -8294,7 +8418,7 @@ var VaultService = class extends ServiceBase {
|
|
|
8294
8418
|
/**
|
|
8295
8419
|
* Check if a file is a target file for synchronisation.
|
|
8296
8420
|
* @param file The file path or file info stub to check.
|
|
8297
|
-
* @param
|
|
8421
|
+
* @param options Optional selection inspection without filename collision rejection.
|
|
8298
8422
|
*/
|
|
8299
8423
|
isTargetFile = handlers().bailFirstFailure("isTargetFile");
|
|
8300
8424
|
/**
|
|
@@ -8466,10 +8590,18 @@ var PathServiceCompat = class extends PathService {
|
|
|
8466
8590
|
//#endregion
|
|
8467
8591
|
//#region ../../../node_modules/fflate/lib/node.cjs
|
|
8468
8592
|
var require_node = /* @__PURE__ */ require_stream_collector.__commonJSMin(((exports) => {
|
|
8593
|
+
exports.deflate = deflate;
|
|
8594
|
+
exports.inflate = inflate;
|
|
8595
|
+
exports.gzip = gzip;
|
|
8596
|
+
exports.compress = gzip;
|
|
8597
|
+
exports.gzip = gzip;
|
|
8598
|
+
exports.compress = gzip;
|
|
8599
|
+
var _a;
|
|
8469
8600
|
var Worker;
|
|
8601
|
+
var isMarkedAsUntransferable;
|
|
8470
8602
|
var workerAdd = ";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global";
|
|
8471
8603
|
try {
|
|
8472
|
-
|
|
8604
|
+
_a = require("worker_threads"), Worker = _a.Worker, isMarkedAsUntransferable = _a.isMarkedAsUntransferable;
|
|
8473
8605
|
} catch (e) {}
|
|
8474
8606
|
var node_worker_1 = {};
|
|
8475
8607
|
node_worker_1["default"] = Worker ? function(c, _, msg, transfer, cb) {
|
|
@@ -8481,6 +8613,9 @@ var require_node = /* @__PURE__ */ require_stream_collector.__commonJSMin(((expo
|
|
|
8481
8613
|
}).on("exit", function(c) {
|
|
8482
8614
|
if (c && !done) cb(/* @__PURE__ */ new Error("exited with code " + c), null);
|
|
8483
8615
|
});
|
|
8616
|
+
if (isMarkedAsUntransferable) transfer = transfer.filter(function(t) {
|
|
8617
|
+
return !isMarkedAsUntransferable(t);
|
|
8618
|
+
});
|
|
8484
8619
|
w.postMessage(msg, transfer);
|
|
8485
8620
|
w.terminate = function() {
|
|
8486
8621
|
done = true;
|
|
@@ -9099,6 +9234,28 @@ var require_node = /* @__PURE__ */ require_stream_collector.__commonJSMin(((expo
|
|
|
9099
9234
|
}
|
|
9100
9235
|
return slc(o, 0, pre + shft(pos) + post);
|
|
9101
9236
|
};
|
|
9237
|
+
var crct = /*#__PURE__*/ (function() {
|
|
9238
|
+
var t = new Int32Array(256);
|
|
9239
|
+
for (var i = 0; i < 256; ++i) {
|
|
9240
|
+
var c = i, k = 9;
|
|
9241
|
+
while (--k) c = (c & 1 && -306674912) ^ c >>> 1;
|
|
9242
|
+
t[i] = c;
|
|
9243
|
+
}
|
|
9244
|
+
return t;
|
|
9245
|
+
})();
|
|
9246
|
+
var crc = function() {
|
|
9247
|
+
var c = -1;
|
|
9248
|
+
return {
|
|
9249
|
+
p: function(d) {
|
|
9250
|
+
var cr = c;
|
|
9251
|
+
for (var i = 0; i < d.length; ++i) cr = crct[cr & 255 ^ d[i]] ^ cr >>> 8;
|
|
9252
|
+
c = cr;
|
|
9253
|
+
},
|
|
9254
|
+
d: function() {
|
|
9255
|
+
return ~c;
|
|
9256
|
+
}
|
|
9257
|
+
};
|
|
9258
|
+
};
|
|
9102
9259
|
var dopt = function(dat, opt, pre, post, st) {
|
|
9103
9260
|
if (!st) {
|
|
9104
9261
|
st = { l: 1 };
|
|
@@ -9219,6 +9376,15 @@ var require_node = /* @__PURE__ */ require_stream_collector.__commonJSMin(((expo
|
|
|
9219
9376
|
pbf
|
|
9220
9377
|
];
|
|
9221
9378
|
};
|
|
9379
|
+
var gze = function() {
|
|
9380
|
+
return [
|
|
9381
|
+
gzh,
|
|
9382
|
+
gzhl,
|
|
9383
|
+
wbytes,
|
|
9384
|
+
crc,
|
|
9385
|
+
crct
|
|
9386
|
+
];
|
|
9387
|
+
};
|
|
9222
9388
|
var pbf = function(msg) {
|
|
9223
9389
|
return postMessage(msg, [msg.buffer]);
|
|
9224
9390
|
};
|
|
@@ -9238,6 +9404,21 @@ var require_node = /* @__PURE__ */ require_stream_collector.__commonJSMin(((expo
|
|
|
9238
9404
|
w.terminate();
|
|
9239
9405
|
};
|
|
9240
9406
|
};
|
|
9407
|
+
var wbytes = function(d, b, v) {
|
|
9408
|
+
for (; v; ++b) d[b] = v, v >>>= 8;
|
|
9409
|
+
};
|
|
9410
|
+
var gzh = function(c, o) {
|
|
9411
|
+
var fn = o.filename;
|
|
9412
|
+
c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3;
|
|
9413
|
+
if (o.mtime != 0) wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1e3));
|
|
9414
|
+
if (fn) {
|
|
9415
|
+
c[3] = 8;
|
|
9416
|
+
for (var i = 0; i <= fn.length; ++i) c[i + 10] = fn.charCodeAt(i);
|
|
9417
|
+
}
|
|
9418
|
+
};
|
|
9419
|
+
var gzhl = function(o) {
|
|
9420
|
+
return 10 + (o.filename ? o.filename.length + 1 : 0);
|
|
9421
|
+
};
|
|
9241
9422
|
function deflate(data, opts, cb) {
|
|
9242
9423
|
if (!cb) cb = opts, opts = {};
|
|
9243
9424
|
if (typeof cb != "function") err(7);
|
|
@@ -9245,7 +9426,6 @@ var require_node = /* @__PURE__ */ require_stream_collector.__commonJSMin(((expo
|
|
|
9245
9426
|
return pbf(deflateSync(ev.data[0], ev.data[1]));
|
|
9246
9427
|
}, 0, cb);
|
|
9247
9428
|
}
|
|
9248
|
-
exports.deflate = deflate;
|
|
9249
9429
|
/**
|
|
9250
9430
|
* Compresses data with DEFLATE without any wrapper
|
|
9251
9431
|
* @param data The data to compress
|
|
@@ -9262,16 +9442,35 @@ var require_node = /* @__PURE__ */ require_stream_collector.__commonJSMin(((expo
|
|
|
9262
9442
|
return pbf(inflateSync(ev.data[0], gopt(ev.data[1])));
|
|
9263
9443
|
}, 1, cb);
|
|
9264
9444
|
}
|
|
9265
|
-
exports.inflate = inflate;
|
|
9266
|
-
/**
|
|
9267
|
-
* Expands DEFLATE data with no wrapper
|
|
9268
|
-
* @param data The data to decompress
|
|
9269
|
-
* @param opts The decompression options
|
|
9270
|
-
* @returns The decompressed version of the data
|
|
9271
|
-
*/
|
|
9272
9445
|
function inflateSync(data, opts) {
|
|
9273
9446
|
return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
|
|
9274
9447
|
}
|
|
9448
|
+
function gzip(data, opts, cb) {
|
|
9449
|
+
if (!cb) cb = opts, opts = {};
|
|
9450
|
+
if (typeof cb != "function") err(7);
|
|
9451
|
+
return cbify(data, opts, [
|
|
9452
|
+
bDflt,
|
|
9453
|
+
gze,
|
|
9454
|
+
function() {
|
|
9455
|
+
return [gzipSync];
|
|
9456
|
+
}
|
|
9457
|
+
], function(ev) {
|
|
9458
|
+
return pbf(gzipSync(ev.data[0], ev.data[1]));
|
|
9459
|
+
}, 2, cb);
|
|
9460
|
+
}
|
|
9461
|
+
/**
|
|
9462
|
+
* Compresses data with GZIP
|
|
9463
|
+
* @param data The data to compress
|
|
9464
|
+
* @param opts The compression options
|
|
9465
|
+
* @returns The gzipped version of the data
|
|
9466
|
+
*/
|
|
9467
|
+
function gzipSync(data, opts) {
|
|
9468
|
+
if (!opts) opts = {};
|
|
9469
|
+
var c = crc(), l = data.length;
|
|
9470
|
+
c.p(data);
|
|
9471
|
+
var d = dopt(data, opts, gzhl(opts), 8), s = d.length;
|
|
9472
|
+
return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;
|
|
9473
|
+
}
|
|
9275
9474
|
var td = typeof TextDecoder != "undefined" && /*#__PURE__*/ new TextDecoder();
|
|
9276
9475
|
try {
|
|
9277
9476
|
td.decode(et, { stream: true });
|
|
@@ -11360,10 +11559,10 @@ var HeadlessAPIService = class extends InjectableAPIService {
|
|
|
11360
11559
|
return "headless-app";
|
|
11361
11560
|
}
|
|
11362
11561
|
getAppVersion() {
|
|
11363
|
-
return `1.0.
|
|
11562
|
+
return `1.0.28`;
|
|
11364
11563
|
}
|
|
11365
11564
|
getPluginVersion() {
|
|
11366
|
-
return `1.0.
|
|
11565
|
+
return `1.0.28`;
|
|
11367
11566
|
}
|
|
11368
11567
|
getPlatform() {
|
|
11369
11568
|
return "server";
|
|
@@ -20670,15 +20869,7 @@ var allMessages = {
|
|
|
20670
20869
|
zh: "(正则表达式)如果已设置,则所有匹配此模式的本地和远端文件变更都会被跳过。",
|
|
20671
20870
|
"zh-tw": "(正則表示式)若已設定,所有符合此模式的本機與遠端檔案變更都會被略過。"
|
|
20672
20871
|
},
|
|
20673
|
-
"(Select this if you
|
|
20674
|
-
def: "(Select this if you are already using synchronisation on another computer or smartphone.) This option is suitable if you are new to LiveSync and want to set it up from scratch.",
|
|
20675
|
-
es: "(Seleccione esto si ya utiliza la sincronización en otro ordenador o teléfono). Esta opción es adecuada si desea añadir este dispositivo a una configuración de LiveSync existente。",
|
|
20676
|
-
ja: "(別の PC やスマートフォンですでに同期を利用している場合に選択してください。)この端末を既存の LiveSync 構成に追加する場合に適しています。",
|
|
20677
|
-
ko: "(다른 컴퓨터나 스마트폰에서 이미 동기화를 사용 중이라면 선택하세요.) 이 기기를 기존 LiveSync 구성에 추가하려는 경우에 적합합니다.",
|
|
20678
|
-
ru: "(Выберите этот вариант, если вы уже используете синхронизацию на другом компьютере или смартфоне.) Он подходит, если вы хотите добавить это устройство к уже существующей конфигурации LiveSync。",
|
|
20679
|
-
zh: "(如果你已经在另一台电脑或手机上使用同步,请选择此项。)此选项适合将当前设备加入现有 LiveSync 配置的用户。",
|
|
20680
|
-
"zh-tw": "(如果你已經在另一台電腦或手機上使用同步,請選擇此項。)此選項適合將目前裝置加入既有 LiveSync 設定的使用者。"
|
|
20681
|
-
},
|
|
20872
|
+
"(Select this if you already have another synchronising device.) This option adds this device to the same synchronisation.": { def: "(Select this if you already have another synchronising device.) This option adds this device to the same synchronisation." },
|
|
20682
20873
|
"(Select this if you are configuring this device as the first synchronisation device.) This option is suitable if you are new to LiveSync and want to set it up from scratch.": {
|
|
20683
20874
|
def: "(Select this if you are configuring this device as the first synchronisation device.) This option is suitable if you are new to LiveSync and want to set it up from scratch.",
|
|
20684
20875
|
es: "(Seleccione esto si está configurando este dispositivo como el primer dispositivo de sincronización). Esta opción es adecuada si es nuevo en LiveSync y desea configurarlo desde cero。",
|
|
@@ -21242,6 +21433,10 @@ var allMessages = {
|
|
|
21242
21433
|
zh: "检查尚未转换为路径混淆 ID 的文档,并在需要时将其转换。",
|
|
21243
21434
|
"zh-tw": "檢查尚未轉換為路徑混淆 ID 的文件,並在需要時進行轉換。"
|
|
21244
21435
|
},
|
|
21436
|
+
"Check server requirements": {
|
|
21437
|
+
def: "Check server requirements",
|
|
21438
|
+
es: "Comprobar los requisitos del servidor"
|
|
21439
|
+
},
|
|
21245
21440
|
"Checking connection... Please wait.": {
|
|
21246
21441
|
def: "Checking connection... Please wait.",
|
|
21247
21442
|
es: "Comprobando la conexión... Espera un momento.",
|
|
@@ -21494,6 +21689,10 @@ var allMessages = {
|
|
|
21494
21689
|
ko: "연결",
|
|
21495
21690
|
"zh-tw": "連線"
|
|
21496
21691
|
},
|
|
21692
|
+
"Connect to existing database and continue": {
|
|
21693
|
+
def: "Connect to existing database and continue",
|
|
21694
|
+
es: "Conectar a la base de datos existente y continuar"
|
|
21695
|
+
},
|
|
21497
21696
|
"Connected to Signaling Server (as Peer ID: ${peerId})": {
|
|
21498
21697
|
def: "Connected to Signaling Server (as Peer ID: ${peerId})",
|
|
21499
21698
|
es: "Conectado al servidor de señalización (como ID de par: ${peerId})",
|
|
@@ -21595,6 +21794,14 @@ var allMessages = {
|
|
|
21595
21794
|
zh: "CouchDB 连接调优",
|
|
21596
21795
|
"zh-tw": "CouchDB 連線調校"
|
|
21597
21796
|
},
|
|
21797
|
+
"CouchDB validates the database name when you connect. The name must not be empty.": {
|
|
21798
|
+
def: "CouchDB validates the database name when you connect. The name must not be empty.",
|
|
21799
|
+
es: "CouchDB valida el nombre de la base de datos al conectar. El nombre no puede estar vacío."
|
|
21800
|
+
},
|
|
21801
|
+
"Create or connect to database and continue": {
|
|
21802
|
+
def: "Create or connect to database and continue",
|
|
21803
|
+
es: "Crear o conectar a la base de datos y continuar"
|
|
21804
|
+
},
|
|
21598
21805
|
"Create P2P remote": {
|
|
21599
21806
|
def: "Create P2P remote",
|
|
21600
21807
|
es: "Crear remoto P2P",
|
|
@@ -21932,7 +22139,7 @@ var allMessages = {
|
|
|
21932
22139
|
},
|
|
21933
22140
|
"dialog.yourLanguageAvailable": {
|
|
21934
22141
|
def: "Self-hosted LiveSync had translations for your language, so the %{Display language} setting was enabled.\n\nNote: Not all messages are translated. We are waiting for your contributions!\nNote 2: If you create an Issue, **please revert to Default** and then take screenshots, messages and logs. This can be done in the setting dialogue.\nMay you find it easy to use!",
|
|
21935
|
-
es: "Self-hosted LiveSync tenía traducciones para tu idioma, así que se ha activado el ajuste
|
|
22142
|
+
es: "Self-hosted LiveSync tenía traducciones para tu idioma, así que se ha activado el ajuste Idioma de visualización.\n\nNota: no todos los mensajes están traducidos. ¡Esperamos tus contribuciones!\nNota 2: si abres una incidencia, **vuelve antes a Predeterminado** y luego haz las capturas de pantalla y recoge los mensajes y registros. Puedes hacerlo desde el diálogo de ajustes.\n¡Que lo disfrutes!",
|
|
21936
22143
|
fr: "Self-hosted LiveSync dispose d'une traduction pour votre langue, le paramètre %{Display language} a donc été activé.\n\nNote : Tous les messages ne sont pas traduits. Nous attendons vos contributions !\nNote 2 : Si vous créez un ticket, **veuillez revenir à Par défaut** puis prendre des captures d'écran, messages et journaux. Cela peut être fait dans la boîte de dialogue des paramètres.\nBonne utilisation !",
|
|
21937
22144
|
he: "ל-Self-hosted LiveSync יש תרגום לשפתך, ולכן הגדרת %{Display language} הופעלה.\n\nהערה: לא כל ההודעות מתורגמות. אנחנו ממתינים לתרומותיך!\nהערה 2: אם אתה פותח Issue, **אנא חזור ל-%{lang-def}** ואז צלם צילומי מסך, הודעות ויומנים. ניתן לעשות זאת בדיאלוג ההגדרות.\nנקווה שתמצא/י את הפלאגין נוח לשימוש!",
|
|
21938
22145
|
ja: "Self-hosted LiveSync に設定されている言語の翻訳がありましたので、インターフェースの表示言語が適用されました。\n\n注意: 全てのメッセージは翻訳されていません。あなたの貢献をお待ちしています!\nGithubにIssueを作成する際には、 インターフェースの表示言語 を一旦 Default に戻してから、スクショやメッセージ、ログを収集してください。これは設定から変更できます。\n\n便利に使用できれば幸いです。",
|
|
@@ -22527,6 +22734,10 @@ var allMessages = {
|
|
|
22527
22734
|
zh: "增大块大小",
|
|
22528
22735
|
"zh-tw": "擴大 chunk 大小"
|
|
22529
22736
|
},
|
|
22737
|
+
"Enter a complete HTTP or HTTPS URL.": {
|
|
22738
|
+
def: "Enter a complete HTTP or HTTPS URL.",
|
|
22739
|
+
es: "Introduce una URL HTTP o HTTPS completa."
|
|
22740
|
+
},
|
|
22530
22741
|
"Enter a folder prefix (optional)": {
|
|
22531
22742
|
def: "Enter a folder prefix (optional)",
|
|
22532
22743
|
es: "Introduce un prefijo de carpeta (opcional)",
|
|
@@ -23018,6 +23229,10 @@ var allMessages = {
|
|
|
23018
23229
|
ko: "해당 없는 항목 숨기기",
|
|
23019
23230
|
"zh-tw": "隱藏不適用的項目"
|
|
23020
23231
|
},
|
|
23232
|
+
"Hide password": {
|
|
23233
|
+
def: "Hide password",
|
|
23234
|
+
es: "Ocultar contraseña"
|
|
23235
|
+
},
|
|
23021
23236
|
"Higher (${local} > ${remote})": {
|
|
23022
23237
|
def: "Higher (${local} > ${remote})",
|
|
23023
23238
|
es: "Superior (${local} > ${remote})",
|
|
@@ -24651,6 +24866,7 @@ var allMessages = {
|
|
|
24651
24866
|
zh: "等待就绪...",
|
|
24652
24867
|
"zh-tw": "正在等待就緒⋯"
|
|
24653
24868
|
},
|
|
24869
|
+
"moduleLog.pathComponentTooLong": { def: "This path contains a file or folder name longer than ${maxBytes} UTF-8 bytes. It may not work on some Android and Linux file systems." },
|
|
24654
24870
|
"moduleLog.showLog": {
|
|
24655
24871
|
def: "Show Log",
|
|
24656
24872
|
es: "Mostrar registro",
|
|
@@ -25815,7 +26031,7 @@ var allMessages = {
|
|
|
25815
26031
|
},
|
|
25816
26032
|
"obsidianLiveSyncSettingTab.logConfiguredLiveSync": {
|
|
25817
26033
|
def: "Configured synchronization mode: LiveSync",
|
|
25818
|
-
es: "Modo de sincronización configurado: Sincronización en
|
|
26034
|
+
es: "Modo de sincronización configurado: Sincronización en vivo",
|
|
25819
26035
|
fr: "Mode de synchronisation configuré : LiveSync",
|
|
25820
26036
|
he: "מצב סנכרון שהוגדר: LiveSync",
|
|
25821
26037
|
ja: "設定された同期モード: LiveSync",
|
|
@@ -26424,7 +26640,7 @@ var allMessages = {
|
|
|
26424
26640
|
},
|
|
26425
26641
|
"obsidianLiveSyncSettingTab.nameTestDatabaseConnection": {
|
|
26426
26642
|
def: "Test Database Connection",
|
|
26427
|
-
es: "Probar
|
|
26643
|
+
es: "Probar conexión de base de datos",
|
|
26428
26644
|
fr: "Tester la connexion à la base de données",
|
|
26429
26645
|
he: "בדוק חיבור למסד נתונים",
|
|
26430
26646
|
ja: "データベース接続テスト",
|
|
@@ -26435,7 +26651,7 @@ var allMessages = {
|
|
|
26435
26651
|
},
|
|
26436
26652
|
"obsidianLiveSyncSettingTab.nameValidateDatabaseConfig": {
|
|
26437
26653
|
def: "Validate Database Configuration",
|
|
26438
|
-
es: "Validar
|
|
26654
|
+
es: "Validar configuración de la base de datos",
|
|
26439
26655
|
fr: "Valider la configuration de la base de données",
|
|
26440
26656
|
he: "אמת תצורת מסד נתונים",
|
|
26441
26657
|
ja: "データベース設定を検証",
|
|
@@ -26743,7 +26959,7 @@ var allMessages = {
|
|
|
26743
26959
|
},
|
|
26744
26960
|
"obsidianLiveSyncSettingTab.panelGeneralSettings": {
|
|
26745
26961
|
def: "General Settings",
|
|
26746
|
-
es: "Configuraciones
|
|
26962
|
+
es: "Configuraciones generales",
|
|
26747
26963
|
fr: "Paramètres généraux",
|
|
26748
26964
|
he: "הגדרות כלליות",
|
|
26749
26965
|
ja: "一般設定",
|
|
@@ -26754,7 +26970,7 @@ var allMessages = {
|
|
|
26754
26970
|
},
|
|
26755
26971
|
"obsidianLiveSyncSettingTab.panelPrivacyEncryption": {
|
|
26756
26972
|
def: "Privacy & Encryption",
|
|
26757
|
-
es: "Privacidad y
|
|
26973
|
+
es: "Privacidad y cifrado",
|
|
26758
26974
|
fr: "Confidentialité et chiffrement",
|
|
26759
26975
|
he: "פרטיות והצפנה",
|
|
26760
26976
|
ja: "プライバシーと暗号化",
|
|
@@ -27069,7 +27285,7 @@ var allMessages = {
|
|
|
27069
27285
|
},
|
|
27070
27286
|
"obsidianLiveSyncSettingTab.titleSyncSettings": {
|
|
27071
27287
|
def: "Sync Settings",
|
|
27072
|
-
es: "Configuraciones de
|
|
27288
|
+
es: "Configuraciones de sincronización",
|
|
27073
27289
|
fr: "Paramètres de synchronisation",
|
|
27074
27290
|
he: "הגדרות סנכרון",
|
|
27075
27291
|
ja: "同期設定",
|
|
@@ -28800,6 +29016,10 @@ var allMessages = {
|
|
|
28800
29016
|
zh: "将设置保存到一个 Markdown 文件中。当新设置到达时,您将收到通知。您可以根据平台设置不同的文件 ",
|
|
28801
29017
|
"zh-tw": "將設定儲存到 Markdown 檔案中。有新設定送達時會通知你,可依平台設定不同的檔案。"
|
|
28802
29018
|
},
|
|
29019
|
+
"Save without connecting": {
|
|
29020
|
+
def: "Save without connecting",
|
|
29021
|
+
es: "Guardar sin conectar"
|
|
29022
|
+
},
|
|
28803
29023
|
"Saving will be performed forcefully after this number of seconds.": {
|
|
28804
29024
|
def: "Saving will be performed forcefully after this number of seconds.",
|
|
28805
29025
|
es: "Guardado forzado tras esta cantidad de segundos",
|
|
@@ -28811,6 +29031,10 @@ var allMessages = {
|
|
|
28811
29031
|
zh: "在此秒数后将强制执行保存 ",
|
|
28812
29032
|
"zh-tw": "經過這個秒數後,會強制執行儲存。"
|
|
28813
29033
|
},
|
|
29034
|
+
"Saving without a successful connection test keeps this profile, but automatic synchronisation may fail until the connection is corrected.": {
|
|
29035
|
+
def: "Saving without a successful connection test keeps this profile, but automatic synchronisation may fail until the connection is corrected.",
|
|
29036
|
+
es: "Guardar sin una prueba de conexión correcta conserva este perfil, pero la sincronización automática puede fallar hasta que se corrija la conexión."
|
|
29037
|
+
},
|
|
28814
29038
|
"Scan a QR Code (Recommended for mobile)": {
|
|
28815
29039
|
def: "Scan a QR Code (Recommended for mobile)",
|
|
28816
29040
|
es: "Escanear un código QR (recomendado para móviles)",
|
|
@@ -29817,6 +30041,10 @@ var allMessages = {
|
|
|
29817
30041
|
zh: "仅显示通知",
|
|
29818
30042
|
"zh-tw": "僅顯示通知"
|
|
29819
30043
|
},
|
|
30044
|
+
"Show password": {
|
|
30045
|
+
def: "Show password",
|
|
30046
|
+
es: "Mostrar contraseña"
|
|
30047
|
+
},
|
|
29820
30048
|
"Show status as icons only": {
|
|
29821
30049
|
def: "Show status as icons only",
|
|
29822
30050
|
es: "Mostrar estado solo con íconos",
|
|
@@ -30174,6 +30402,10 @@ var allMessages = {
|
|
|
30174
30402
|
zh: "目标模式",
|
|
30175
30403
|
"zh-tw": "目標模式"
|
|
30176
30404
|
},
|
|
30405
|
+
"Test connection and save": {
|
|
30406
|
+
def: "Test connection and save",
|
|
30407
|
+
es: "Probar la conexión y guardar"
|
|
30408
|
+
},
|
|
30177
30409
|
"Test Settings and Continue": {
|
|
30178
30410
|
def: "Test Settings and Continue",
|
|
30179
30411
|
es: "Probar los ajustes y continuar",
|
|
@@ -30384,6 +30616,10 @@ var allMessages = {
|
|
|
30384
30616
|
zh: "此功能可在设备之间直接同步,无需服务器;但同步时两台设备必须同时在线,且部分功能可能受限。互联网连接仅用于信令(发现对端),不用于数据传输。",
|
|
30385
30617
|
"zh-tw": "此功能可在裝置之間直接同步,無需伺服器;但同步時兩台裝置必須同時在線,且部分功能可能受限。網際網路連線僅用於訊號交換(偵測對端),不用於資料傳輸。"
|
|
30386
30618
|
},
|
|
30619
|
+
"This first setup has several short steps because it confirms encryption, the connection method, and which device provides the initial data. Once it is complete, additional devices can reuse a Setup URI.": {
|
|
30620
|
+
def: "This first setup has several short steps because it confirms encryption, the connection method, and which device provides the initial data. Once it is complete, additional devices can reuse a Setup URI.",
|
|
30621
|
+
es: "Esta primera configuración consta de varios pasos breves, ya que confirma el cifrado, el método de conexión y qué dispositivo aporta los datos iniciales. Una vez completada, los demás dispositivos podrán reutilizar un Setup URI."
|
|
30622
|
+
},
|
|
30387
30623
|
"This is an advanced option for users who do not have a URI or who wish to configure detailed settings.": {
|
|
30388
30624
|
def: "This is an advanced option for users who do not have a URI or who wish to configure detailed settings.",
|
|
30389
30625
|
es: "Esta es una opción avanzada para usuarios que no disponen de un URI o que desean configurar parámetros detallados。",
|
|
@@ -30408,6 +30644,10 @@ var allMessages = {
|
|
|
30408
30644
|
zh: "这是最符合当前设计的同步方式,所有功能均可用。你需要事先部署好 CouchDB 实例。",
|
|
30409
30645
|
"zh-tw": "這是最符合目前設計的同步方式,所有功能皆可使用。你需要事先部署好 CouchDB 實例。"
|
|
30410
30646
|
},
|
|
30647
|
+
"This optional check uses Obsidian's internal request API and sends the credentials above to the CouchDB server. Use it only with a server you trust; administrator access may be required.": {
|
|
30648
|
+
def: "This optional check uses Obsidian's internal request API and sends the credentials above to the CouchDB server. Use it only with a server you trust; administrator access may be required.",
|
|
30649
|
+
es: "Esta comprobación opcional usa la API interna de solicitudes de Obsidian y envía las credenciales anteriores al servidor CouchDB. Utilízala solo con un servidor de confianza; puede requerir acceso de administrador."
|
|
30650
|
+
},
|
|
30411
30651
|
"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.": {
|
|
30412
30652
|
def: "This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.",
|
|
30413
30653
|
es: "Esta frase no se copia a otros dispositivos. Usará `Default` hasta reconfigurar",
|
|
@@ -30741,6 +30981,7 @@ var allMessages = {
|
|
|
30741
30981
|
zh: "Use Remote Configuration",
|
|
30742
30982
|
"zh-tw": "使用遠端設定"
|
|
30743
30983
|
},
|
|
30984
|
+
"Ui.Common.LocalDatabaseInitialisationFailed": { def: "Self-hosted LiveSync cannot synchronise. Generate a report to review the detailed log." },
|
|
30744
30985
|
"Ui.Common.Signal.Caution": {
|
|
30745
30986
|
def: "CAUTION",
|
|
30746
30987
|
es: "PRECAUCIÓN",
|
|
@@ -30769,6 +31010,7 @@ var allMessages = {
|
|
|
30769
31010
|
zh: "警告",
|
|
30770
31011
|
"zh-tw": "警告"
|
|
30771
31012
|
},
|
|
31013
|
+
"Ui.Common.SomeFilesCouldNotBeSynchronised": { def: "Not all files could be synchronised. Check the affected files. Generate a report to review the detailed log." },
|
|
30772
31014
|
"Ui.Settings.Advanced.LocalDatabaseTweak": {
|
|
30773
31015
|
def: "Local Database Tweak",
|
|
30774
31016
|
es: "Ajuste fino de la base de datos local",
|
|
@@ -32990,6 +33232,18 @@ var allMessages = {
|
|
|
32990
33232
|
ko: "이 작업은 서버 데이터가 완전히 손상된 경우, 다른 모든 기기의 변경 사항이 더 이상 필요하지 않은 경우, 또는 데이터베이스 크기가 보관함 크기에 비해 비정상적으로 커진 경우처럼 예외적인 상황에서만 수행해야 합니다.",
|
|
32991
33233
|
"zh-tw": "只有在特殊情況下才應執行此操作,例如伺服器資料已完全損毀、其他所有裝置上的變更都已不再需要,或資料庫大小相對於 Vault 大小已變得異常龐大時。"
|
|
32992
33234
|
},
|
|
33235
|
+
"you wanted(Thank you)!": {
|
|
33236
|
+
def: "you wanted(Thank you)!",
|
|
33237
|
+
es: "tu solicitud (¡gracias!)"
|
|
33238
|
+
},
|
|
33239
|
+
"(Select this if another device is already using LiveSync.) This option adds this device to that existing synchronisation setup.": {
|
|
33240
|
+
es: "(Seleccione esto si ya utiliza la sincronización en otro ordenador o teléfono). Esta opción es adecuada si desea añadir este dispositivo a una configuración de LiveSync existente。",
|
|
33241
|
+
ja: "(別の PC やスマートフォンですでに同期を利用している場合に選択してください。)この端末を既存の LiveSync 構成に追加する場合に適しています。",
|
|
33242
|
+
ko: "(다른 컴퓨터나 스마트폰에서 이미 동기화를 사용 중이라면 선택하세요.) 이 기기를 기존 LiveSync 구성에 추가하려는 경우에 적합합니다.",
|
|
33243
|
+
ru: "(Выберите этот вариант, если вы уже используете синхронизацию на другом компьютере или смартфоне.) Он подходит, если вы хотите добавить это устройство к уже существующей конфигурации LiveSync。",
|
|
33244
|
+
zh: "(如果你已经在另一台电脑或手机上使用同步,请选择此项。)此选项适合将当前设备加入现有 LiveSync 配置的用户。",
|
|
33245
|
+
"zh-tw": "(如果你已經在另一台電腦或手機上使用同步,請選擇此項。)此選項適合將目前裝置加入既有 LiveSync 設定的使用者。"
|
|
33246
|
+
},
|
|
32993
33247
|
"Compute revisions for chunks (Previous behaviour)": { es: "Calcular revisiones para chunks (comportamiento anterior)" },
|
|
32994
33248
|
"Setup.> [!INFO]- The connected devices have been detected as follows:\n${devices}": { es: "> [!INFO]- Se detectaron los siguientes dispositivos conectados:\n${devices}" },
|
|
32995
33249
|
"Setup.All devices have the same progress value (${progress}). Your devices seem to be synchronised. And be able to proceed with Garbage Collection.": { es: "Todos los dispositivos tienen el mismo valor de progreso (${progress}). Parece que tus dispositivos están sincronizados y se puede continuar con la recolección de basura." },
|
|
@@ -33063,7 +33317,6 @@ var allMessages = {
|
|
|
33063
33317
|
* remove it from this map in the same change.
|
|
33064
33318
|
*/
|
|
33065
33319
|
var liveSyncProvisionalEnglishMessages = {
|
|
33066
|
-
"This first setup has several short steps because it confirms encryption, the connection method, and which device provides the initial data. Once it is complete, additional devices can reuse a Setup URI.": "This first setup has several short steps because it confirms encryption, the connection method, and which device provides the initial data. Once it is complete, additional devices can reuse a Setup URI.",
|
|
33067
33320
|
"Setup Complete: Preparing to Fetch from Another Device": "Setup Complete: Preparing to Fetch from Another Device",
|
|
33068
33321
|
"The P2P connection has been configured successfully. The initial synchronisation data must now be fetched from an online source device.": "The P2P connection has been configured successfully. The initial synchronisation data must now be fetched from an online source device.",
|
|
33069
33322
|
"After restarting, select an online source device for the initial Fetch. The local LiveSync database on this device will be rebuilt from that source. Unsynchronised files in this Vault may conflict with the fetched data.": "After restarting, select an online source device for the initial Fetch. The local LiveSync database on this device will be rebuilt from that source. Unsynchronised files in this Vault may conflict with the fetched data.",
|
|
@@ -33102,10 +33355,6 @@ var liveSyncProvisionalEnglishMessages = {
|
|
|
33102
33355
|
"Follow whenever this device connects": "Follow whenever this device connects",
|
|
33103
33356
|
"Include in the P2P synchronisation command": "Include in the P2P synchronisation command",
|
|
33104
33357
|
"More actions for ${DEVICE}": "More actions for ${DEVICE}",
|
|
33105
|
-
"Create or connect to database and continue": "Create or connect to database and continue",
|
|
33106
|
-
"Connect to existing database and continue": "Connect to existing database and continue",
|
|
33107
|
-
"Test connection and save": "Test connection and save",
|
|
33108
|
-
"Save without connecting": "Save without connecting",
|
|
33109
33358
|
"Use this device's settings": "Use this device's settings",
|
|
33110
33359
|
Retry: "Retry",
|
|
33111
33360
|
"No Synchronisation Settings Found": "No Synchronisation Settings Found",
|
|
@@ -33114,11 +33363,6 @@ var liveSyncProvisionalEnglishMessages = {
|
|
|
33114
33363
|
"Could not read the remote's synchronisation settings. Check the connection and credentials, then retry.": "Could not read the remote's synchronisation settings. Check the connection and credentials, then retry.",
|
|
33115
33364
|
"Could not read the remote's synchronisation settings. Retry, or continue the overwrite with this device's settings. A working connection is still required.": "Could not read the remote's synchronisation settings. Retry, or continue the overwrite with this device's settings. A working connection is still required.",
|
|
33116
33365
|
"Skips checking and applying synchronisation settings from the remote.": "Skips checking and applying synchronisation settings from the remote.",
|
|
33117
|
-
"Enter a complete HTTP or HTTPS URL.": "Enter a complete HTTP or HTTPS URL.",
|
|
33118
|
-
"CouchDB validates the database name when you connect. The name must not be empty.": "CouchDB validates the database name when you connect. The name must not be empty.",
|
|
33119
|
-
"Saving without a successful connection test keeps this profile, but automatic synchronisation may fail until the connection is corrected.": "Saving without a successful connection test keeps this profile, but automatic synchronisation may fail until the connection is corrected.",
|
|
33120
|
-
"This optional check uses Obsidian's internal request API and sends the credentials above to the CouchDB server. Use it only with a server you trust; administrator access may be required.": "This optional check uses Obsidian's internal request API and sends the credentials above to the CouchDB server. Use it only with a server you trust; administrator access may be required.",
|
|
33121
|
-
"Check server requirements": "Check server requirements",
|
|
33122
33366
|
"Change CouchDB server setting": "Change CouchDB server setting",
|
|
33123
33367
|
"Change CouchDB server setting '${SETTING}' to '${VALUE}'?": "Change CouchDB server setting '${SETTING}' to '${VALUE}'?",
|
|
33124
33368
|
"This file has unresolved conflicts.": "This file has unresolved conflicts.",
|
|
@@ -33478,7 +33722,8 @@ function isAcceptedInFilenameDuplicationFactory(host, log) {
|
|
|
33478
33722
|
return true;
|
|
33479
33723
|
}
|
|
33480
33724
|
});
|
|
33481
|
-
return async function isAcceptedInFilenameDuplication(file) {
|
|
33725
|
+
return async function isAcceptedInFilenameDuplication(file, options) {
|
|
33726
|
+
if (options?.skipCaseCollisionCheck) return true;
|
|
33482
33727
|
const fileCountMap = (await fileCountMapComputed.update(host.services.fileProcessing.totalStorageFileEventCount)).value;
|
|
33483
33728
|
const filepath = getStoragePathFromUXFileInfo(file);
|
|
33484
33729
|
const lc = filepath.toLowerCase();
|
|
@@ -33660,62 +33905,119 @@ var AbstractModule = class {
|
|
|
33660
33905
|
}
|
|
33661
33906
|
};
|
|
33662
33907
|
//#endregion
|
|
33663
|
-
//#region
|
|
33664
|
-
var
|
|
33665
|
-
|
|
33666
|
-
|
|
33667
|
-
|
|
33668
|
-
|
|
33669
|
-
|
|
33670
|
-
|
|
33671
|
-
|
|
33672
|
-
|
|
33673
|
-
|
|
33674
|
-
|
|
33675
|
-
|
|
33676
|
-
|
|
33677
|
-
|
|
33678
|
-
|
|
33679
|
-
|
|
33680
|
-
|
|
33681
|
-
|
|
33682
|
-
|
|
33683
|
-
|
|
33684
|
-
|
|
33685
|
-
|
|
33686
|
-
|
|
33687
|
-
|
|
33688
|
-
|
|
33689
|
-
|
|
33690
|
-
|
|
33908
|
+
//#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/common/models/tweak.compatibility.js
|
|
33909
|
+
var hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
|
|
33910
|
+
function snapshotTweakValues(values) {
|
|
33911
|
+
const snapshot = {};
|
|
33912
|
+
for (const key of Object.keys(TweakValuesTemplate)) if (hasOwn(values, key)) snapshot[key] = values[key];
|
|
33913
|
+
return Object.freeze(snapshot);
|
|
33914
|
+
}
|
|
33915
|
+
function assessedValue(values, key, knownDefault) {
|
|
33916
|
+
const present = hasOwn(values, key);
|
|
33917
|
+
const rawValue = values[key];
|
|
33918
|
+
return Object.freeze({
|
|
33919
|
+
present,
|
|
33920
|
+
rawValue,
|
|
33921
|
+
effectiveValue: rawValue === void 0 ? knownDefault : rawValue
|
|
33922
|
+
});
|
|
33923
|
+
}
|
|
33924
|
+
function highestReconstruction(current, next) {
|
|
33925
|
+
if (current === "required" || next === "required") return "required";
|
|
33926
|
+
return "recommended";
|
|
33927
|
+
}
|
|
33928
|
+
function reconstructionForTransition(key, from, to) {
|
|
33929
|
+
const rule = TweakCompatibilityRules.find((candidate) => candidate.key === key);
|
|
33930
|
+
if (!rule) return "none";
|
|
33931
|
+
let reconstruction = rule.reconstruction;
|
|
33932
|
+
const extensibleRule = rule;
|
|
33933
|
+
for (const pattern of extensibleRule.specificPatterns ?? []) {
|
|
33934
|
+
const matchesFrom = hasOwn(pattern, "from") && pattern.from === from;
|
|
33935
|
+
const matchesTo = hasOwn(pattern, "to") && pattern.to === to;
|
|
33936
|
+
if (matchesFrom || matchesTo) reconstruction = highestReconstruction(reconstruction, pattern.reconstruction);
|
|
33937
|
+
}
|
|
33938
|
+
return reconstruction;
|
|
33939
|
+
}
|
|
33940
|
+
function transition(entries, sourceSide, targetSide) {
|
|
33941
|
+
const changes = {};
|
|
33942
|
+
const reasons = [];
|
|
33943
|
+
let reconstruction = "none";
|
|
33944
|
+
for (const entry of entries) {
|
|
33945
|
+
const source = entry[sourceSide];
|
|
33946
|
+
const target = entry[targetSide];
|
|
33947
|
+
const sourceAdvertised = source.present && source.rawValue !== void 0;
|
|
33948
|
+
const targetAdvertised = target.present && target.rawValue !== void 0;
|
|
33949
|
+
const effectiveValueDiffers = source.effectiveValue !== target.effectiveValue;
|
|
33950
|
+
const shouldFillMissingTarget = !targetAdvertised && sourceAdvertised;
|
|
33951
|
+
if (source.effectiveValue === void 0 || !effectiveValueDiffers && !shouldFillMissingTarget) continue;
|
|
33952
|
+
changes[entry.key] = source.effectiveValue;
|
|
33953
|
+
if (entry.relation === "equal") continue;
|
|
33954
|
+
const effect = reconstructionForTransition(entry.key, target.effectiveValue, source.effectiveValue);
|
|
33955
|
+
if (effect === "none") continue;
|
|
33956
|
+
const reason = Object.freeze({
|
|
33957
|
+
key: entry.key,
|
|
33958
|
+
reconstruction: effect
|
|
33691
33959
|
});
|
|
33960
|
+
reasons.push(reason);
|
|
33961
|
+
reconstruction = highestReconstruction(reconstruction, reason.reconstruction);
|
|
33692
33962
|
}
|
|
33693
|
-
|
|
33694
|
-
|
|
33695
|
-
|
|
33696
|
-
|
|
33697
|
-
|
|
33698
|
-
|
|
33699
|
-
|
|
33700
|
-
|
|
33701
|
-
|
|
33702
|
-
|
|
33703
|
-
|
|
33704
|
-
|
|
33705
|
-
const
|
|
33706
|
-
|
|
33707
|
-
|
|
33708
|
-
|
|
33709
|
-
|
|
33710
|
-
|
|
33711
|
-
|
|
33712
|
-
|
|
33713
|
-
|
|
33714
|
-
|
|
33715
|
-
|
|
33716
|
-
|
|
33963
|
+
return Object.freeze({
|
|
33964
|
+
changes: Object.freeze(changes),
|
|
33965
|
+
reconstruction,
|
|
33966
|
+
reasons: Object.freeze(reasons)
|
|
33967
|
+
});
|
|
33968
|
+
}
|
|
33969
|
+
function assessTweakCompatibility(current, preferred) {
|
|
33970
|
+
const currentValues = snapshotTweakValues(current);
|
|
33971
|
+
const preferredValues = snapshotTweakValues(preferred);
|
|
33972
|
+
let representationDiffers = false;
|
|
33973
|
+
const entries = TweakCompatibilityRules.map((rule) => {
|
|
33974
|
+
const knownDefault = "knownDefault" in rule ? rule.knownDefault : void 0;
|
|
33975
|
+
const currentValue = assessedValue(currentValues, rule.key, knownDefault);
|
|
33976
|
+
const preferredValue = assessedValue(preferredValues, rule.key, knownDefault);
|
|
33977
|
+
const currentAdvertised = currentValue.present && currentValue.rawValue !== void 0;
|
|
33978
|
+
const preferredAdvertised = preferredValue.present && preferredValue.rawValue !== void 0;
|
|
33979
|
+
let relation;
|
|
33980
|
+
if ((!currentAdvertised || !preferredAdvertised) && knownDefault === void 0) relation = "unadvertised";
|
|
33981
|
+
else relation = currentValue.effectiveValue === preferredValue.effectiveValue ? "equal" : "different";
|
|
33982
|
+
if (currentValue.present !== preferredValue.present || currentValue.rawValue !== preferredValue.rawValue) representationDiffers = true;
|
|
33983
|
+
return Object.freeze({
|
|
33984
|
+
key: rule.key,
|
|
33985
|
+
current: currentValue,
|
|
33986
|
+
preferred: preferredValue,
|
|
33987
|
+
relation
|
|
33988
|
+
});
|
|
33989
|
+
});
|
|
33990
|
+
const frozenEntries = Object.freeze(entries);
|
|
33991
|
+
const differences = frozenEntries.filter(({ relation }) => relation === "different");
|
|
33992
|
+
const compatibleLossyKeys = new Set(TweakCompatibilityRules.filter((rule) => "compatibleLossyOrder" in rule).map(({ key }) => key));
|
|
33993
|
+
return Object.freeze({
|
|
33994
|
+
alignment: differences.length === 0 ? "matched" : "mismatched",
|
|
33995
|
+
representationDiffers,
|
|
33996
|
+
entries: frozenEntries,
|
|
33997
|
+
adoptPreferred: transition(frozenEntries, "preferred", "current"),
|
|
33998
|
+
adoptCurrent: transition(frozenEntries, "current", "preferred"),
|
|
33999
|
+
onlyCompatibleLossyDifferences: differences.length > 0 && differences.every(({ key }) => compatibleLossyKeys.has(key)) && !frozenEntries.some(({ relation }) => relation === "unadvertised"),
|
|
34000
|
+
currentValues,
|
|
34001
|
+
preferredValues
|
|
34002
|
+
});
|
|
34003
|
+
}
|
|
34004
|
+
//#endregion
|
|
34005
|
+
//#region ../../common/ownedRemoteResource.ts
|
|
34006
|
+
/**
|
|
34007
|
+
* Run a finite operation with a flow-owned remote resource and release it
|
|
34008
|
+
* after either success or failure.
|
|
34009
|
+
*
|
|
34010
|
+
* Resource implementations make `dispose()` idempotent. This helper makes the
|
|
34011
|
+
* caller's ownership boundary explicit and prevents finite flows from leaking
|
|
34012
|
+
* a provider-owned resource when their operation rejects.
|
|
34013
|
+
*/
|
|
34014
|
+
async function withOwnedRemoteResource(resource, operation) {
|
|
34015
|
+
try {
|
|
34016
|
+
return await operation(resource);
|
|
34017
|
+
} finally {
|
|
34018
|
+
await resource.dispose();
|
|
33717
34019
|
}
|
|
33718
|
-
}
|
|
34020
|
+
}
|
|
33719
34021
|
//#endregion
|
|
33720
34022
|
//#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/replication/RemoteResource.js
|
|
33721
34023
|
var REMOTE_RESOURCE_KINDS = Object.freeze({
|
|
@@ -33745,184 +34047,23 @@ var CENTRAL_COMPATIBILITY_REJECTION_REASONS = Object.freeze({
|
|
|
33745
34047
|
});
|
|
33746
34048
|
var CENTRAL_COMPATIBILITY_NOT_ASSESSED = Object.freeze({ status: CENTRAL_COMPATIBILITY_STATUSES.NOT_ASSESSED });
|
|
33747
34049
|
var CENTRAL_COMPATIBILITY_ACCEPTED = Object.freeze({ status: CENTRAL_COMPATIBILITY_STATUSES.ACCEPTED });
|
|
33748
|
-
function centralCompatibilityRejected(reason, preferredTweakValue) {
|
|
34050
|
+
function centralCompatibilityRejected(reason, preferredTweakValue, tweakAssessment) {
|
|
33749
34051
|
return Object.freeze({
|
|
33750
34052
|
status: CENTRAL_COMPATIBILITY_STATUSES.REJECTED,
|
|
33751
34053
|
reason,
|
|
33752
|
-
...preferredTweakValue === void 0 ? {} : { preferredTweakValue: Object.freeze({ ...preferredTweakValue }) }
|
|
34054
|
+
...preferredTweakValue === void 0 ? {} : { preferredTweakValue: Object.freeze({ ...preferredTweakValue }) },
|
|
34055
|
+
...tweakAssessment === void 0 ? {} : { tweakAssessment }
|
|
33753
34056
|
});
|
|
33754
34057
|
}
|
|
33755
34058
|
function centralCompatibilityRecoveryHint(decision) {
|
|
33756
34059
|
if (decision.status !== CENTRAL_COMPATIBILITY_STATUSES.REJECTED) return void 0;
|
|
33757
34060
|
return Object.freeze({
|
|
33758
34061
|
reason: decision.reason,
|
|
33759
|
-
...decision.preferredTweakValue === void 0 ? {} : { preferredTweakValue: decision.preferredTweakValue }
|
|
34062
|
+
...decision.preferredTweakValue === void 0 ? {} : { preferredTweakValue: decision.preferredTweakValue },
|
|
34063
|
+
...decision.tweakAssessment === void 0 ? {} : { tweakAssessment: decision.tweakAssessment }
|
|
33760
34064
|
});
|
|
33761
34065
|
}
|
|
33762
34066
|
//#endregion
|
|
33763
|
-
//#region ../../modules/coreFeatures/ModuleConflictResolver.ts
|
|
33764
|
-
var ModuleConflictResolver = class extends AbstractModule {
|
|
33765
|
-
async _resolveConflictByDeletingRev(path, deleteRevision, subTitle = "", showNotice = true) {
|
|
33766
|
-
const title = `Resolving ${subTitle ? `[${subTitle}]` : ""}:`;
|
|
33767
|
-
if (!await this.core.fileHandler.deleteRevisionFromDB(path, deleteRevision)) {
|
|
33768
|
-
this._log(`${title} Could not delete conflicted revision ${displayRev(deleteRevision)} of ${path}`, 64);
|
|
33769
|
-
return MISSING_OR_ERROR;
|
|
33770
|
-
}
|
|
33771
|
-
eventHub.emitEvent(EVENT_CONFLICT_CANCELLED, path);
|
|
33772
|
-
this._log(`${title} Conflicted revision has been deleted ${displayRev(deleteRevision)} ${path}`, 32);
|
|
33773
|
-
if ((await this.core.databaseFileAccess.getConflictedRevs(path)).length != 0) {
|
|
33774
|
-
this._log(`${title} some conflicts are left in ${path}`, 32);
|
|
33775
|
-
return AUTO_MERGED;
|
|
33776
|
-
}
|
|
33777
|
-
if (isPluginMetadata(path) || isCustomisationSyncMetadata(path)) {
|
|
33778
|
-
this._log(`${title} ${path} is a plugin metadata file, no need to write to storage`, 32);
|
|
33779
|
-
return AUTO_MERGED;
|
|
33780
|
-
}
|
|
33781
|
-
if (!await this.core.fileHandler.dbToStorage(path, stripAllPrefixes(path), true)) {
|
|
33782
|
-
this._log(`Could not write the resolved content to the storage: ${path}`, 64);
|
|
33783
|
-
return MISSING_OR_ERROR;
|
|
33784
|
-
}
|
|
33785
|
-
const level = subTitle.indexOf("same") !== -1 || !showNotice ? 32 : 64;
|
|
33786
|
-
this._log(`${path} has been merged automatically`, level);
|
|
33787
|
-
return AUTO_MERGED;
|
|
33788
|
-
}
|
|
33789
|
-
async checkConflictAndPerformAutoMerge(path) {
|
|
33790
|
-
const ret = await this.localDatabase.tryAutoMerge(path, !this.settings.disableMarkdownAutoMerge);
|
|
33791
|
-
if ("ok" in ret) return ret.ok;
|
|
33792
|
-
if ("result" in ret) {
|
|
33793
|
-
const p = ret.result;
|
|
33794
|
-
if (!await this.core.databaseFileAccess.storeContent(path, p)) {
|
|
33795
|
-
this._log(`Merged content cannot be stored:${path}`, 64);
|
|
33796
|
-
return MISSING_OR_ERROR;
|
|
33797
|
-
}
|
|
33798
|
-
return await this.services.conflict.resolveByDeletingRevision(path, ret.conflictedRev, "Sensible");
|
|
33799
|
-
}
|
|
33800
|
-
const { rightRev, leftLeaf, rightLeaf } = ret;
|
|
33801
|
-
if (leftLeaf == false) {
|
|
33802
|
-
this._log(`could not get current revisions:${path}`, 64);
|
|
33803
|
-
return MISSING_OR_ERROR;
|
|
33804
|
-
}
|
|
33805
|
-
if (rightLeaf == false) {
|
|
33806
|
-
this._log(`could not read conflicted revision ${rightRev}:${path}`, 64);
|
|
33807
|
-
return MISSING_OR_ERROR;
|
|
33808
|
-
}
|
|
33809
|
-
const isSame = leftLeaf.data == rightLeaf.data && leftLeaf.deleted == rightLeaf.deleted;
|
|
33810
|
-
const isBinary = !isPlainText(path);
|
|
33811
|
-
const alwaysNewer = this.settings.resolveConflictsByNewerFile;
|
|
33812
|
-
if (isSame || isBinary || alwaysNewer) {
|
|
33813
|
-
const result = compareMTime(leftLeaf.mtime, rightLeaf.mtime);
|
|
33814
|
-
let loser = leftLeaf;
|
|
33815
|
-
if (result != TARGET_IS_NEW) loser = rightLeaf;
|
|
33816
|
-
const subTitle = [
|
|
33817
|
-
`${isSame ? "same" : ""}`,
|
|
33818
|
-
`${isBinary ? "binary" : ""}`,
|
|
33819
|
-
`${alwaysNewer ? "alwaysNewer" : ""}`
|
|
33820
|
-
].filter((e) => e.trim()).join(",");
|
|
33821
|
-
return await this.services.conflict.resolveByDeletingRevision(path, loser.rev, subTitle);
|
|
33822
|
-
}
|
|
33823
|
-
const dmp = new import_diff_match_patch.default();
|
|
33824
|
-
const diff = dmp.diff_main(leftLeaf.data, rightLeaf.data);
|
|
33825
|
-
dmp.diff_cleanupSemantic(diff);
|
|
33826
|
-
this._log(`conflict(s) found:${path}`);
|
|
33827
|
-
return {
|
|
33828
|
-
left: leftLeaf,
|
|
33829
|
-
right: rightLeaf,
|
|
33830
|
-
diff
|
|
33831
|
-
};
|
|
33832
|
-
}
|
|
33833
|
-
async _resolveConflict(filename) {
|
|
33834
|
-
return await serialized(`conflict-resolve:${filename}`, async () => {
|
|
33835
|
-
const conflictCheckResult = await this.checkConflictAndPerformAutoMerge(filename);
|
|
33836
|
-
if (conflictCheckResult === NOT_CONFLICTED) {
|
|
33837
|
-
eventHub.emitEvent(EVENT_CONFLICT_CANCELLED, filename);
|
|
33838
|
-
this._log(`[conflict] Not conflicted or cancelled: ${filename}`, 16);
|
|
33839
|
-
return;
|
|
33840
|
-
}
|
|
33841
|
-
if (conflictCheckResult === MISSING_OR_ERROR || conflictCheckResult === CANCELLED) {
|
|
33842
|
-
this._log(`[conflict] Not conflicted or cancelled: ${filename}`, 16);
|
|
33843
|
-
return;
|
|
33844
|
-
}
|
|
33845
|
-
if (conflictCheckResult === AUTO_MERGED) {
|
|
33846
|
-
if (this.settings.syncAfterMerge && !this.services.appLifecycle.isSuspended()) await this.services.replication.replicateUnattendedByEvent({
|
|
33847
|
-
trigger: "merge",
|
|
33848
|
-
interaction: NO_INTERACTION
|
|
33849
|
-
});
|
|
33850
|
-
this._log("[conflict] Automatically merged, but we have to check it again");
|
|
33851
|
-
await this.services.conflict.queueCheckFor(filename);
|
|
33852
|
-
return;
|
|
33853
|
-
}
|
|
33854
|
-
if (this.settings.showMergeDialogOnlyOnActive) {
|
|
33855
|
-
const af = this.services.vault.getActiveFilePath();
|
|
33856
|
-
if (af && af != filename) {
|
|
33857
|
-
this._log(`[conflict] ${filename} is conflicted. Merging process has been postponed to the file have got opened.`, 64);
|
|
33858
|
-
return;
|
|
33859
|
-
}
|
|
33860
|
-
}
|
|
33861
|
-
this._log("[conflict] Manual merge required!");
|
|
33862
|
-
eventHub.emitEvent(EVENT_CONFLICT_CANCELLED, filename);
|
|
33863
|
-
await this.services.conflict.resolveByUserInteraction(filename, conflictCheckResult);
|
|
33864
|
-
});
|
|
33865
|
-
}
|
|
33866
|
-
async _anyResolveConflictByNewest(filename, showNotice = true) {
|
|
33867
|
-
const currentRev = await this.core.databaseFileAccess.fetchEntryMeta(filename, void 0, true);
|
|
33868
|
-
if (currentRev == false) {
|
|
33869
|
-
this._log(`Could not get current revision of ${filename}`);
|
|
33870
|
-
return Promise.resolve(false);
|
|
33871
|
-
}
|
|
33872
|
-
const revs = await this.core.databaseFileAccess.getConflictedRevs(filename);
|
|
33873
|
-
if (revs.length == 0) return Promise.resolve(true);
|
|
33874
|
-
const mTimeAndRev = [[currentRev.mtime, currentRev._rev], ...await Promise.all(revs.map(async (rev) => {
|
|
33875
|
-
const leaf = await this.core.databaseFileAccess.fetchEntryMeta(filename, rev);
|
|
33876
|
-
if (leaf == false) return [0, rev];
|
|
33877
|
-
return [leaf.mtime, rev];
|
|
33878
|
-
}))].sort((a, b) => {
|
|
33879
|
-
const diff = b[0] - a[0];
|
|
33880
|
-
if (diff == 0) return a[1].localeCompare(b[1], "en", { numeric: true });
|
|
33881
|
-
return diff;
|
|
33882
|
-
});
|
|
33883
|
-
this._log(`Resolving conflict by newest: ${filename} (Newest: ${new Date(mTimeAndRev[0][0]).toLocaleString()}) (${mTimeAndRev.length} revisions exists)`);
|
|
33884
|
-
for (let i = 1; i < mTimeAndRev.length; i++) {
|
|
33885
|
-
this._log(`conflict: Deleting the older revision ${mTimeAndRev[i][1]} (${new Date(mTimeAndRev[i][0]).toLocaleString()}) of ${filename}`);
|
|
33886
|
-
await this._resolveConflictByDeletingRev(filename, mTimeAndRev[i][1], "NEWEST", showNotice);
|
|
33887
|
-
}
|
|
33888
|
-
return true;
|
|
33889
|
-
}
|
|
33890
|
-
async _resolveAllConflictedFilesByNewerOnes() {
|
|
33891
|
-
this._log(`Resolving conflicts by newer ones`, 64);
|
|
33892
|
-
const files = await this.core.storageAccess.getFileNames();
|
|
33893
|
-
let i = 0;
|
|
33894
|
-
for (const file of files) {
|
|
33895
|
-
i++;
|
|
33896
|
-
if (i % 10 === 0) this._log(`Check and Processing ${i} / ${files.length}`, 64, "resolveAllConflictedFilesByNewerOnes");
|
|
33897
|
-
await this._anyResolveConflictByNewest(file, false);
|
|
33898
|
-
}
|
|
33899
|
-
this._log(`Done!`, 64, "resolveAllConflictedFilesByNewerOnes");
|
|
33900
|
-
}
|
|
33901
|
-
onBindFunction(core, services) {
|
|
33902
|
-
services.conflict.resolveByDeletingRevision.setHandler(this._resolveConflictByDeletingRev.bind(this));
|
|
33903
|
-
services.conflict.resolve.setHandler(this._resolveConflict.bind(this));
|
|
33904
|
-
services.conflict.resolveByNewest.setHandler(this._anyResolveConflictByNewest.bind(this));
|
|
33905
|
-
services.conflict.resolveAllConflictedFilesByNewerOnes.setHandler(this._resolveAllConflictedFilesByNewerOnes.bind(this));
|
|
33906
|
-
}
|
|
33907
|
-
};
|
|
33908
|
-
//#endregion
|
|
33909
|
-
//#region ../../common/ownedRemoteResource.ts
|
|
33910
|
-
/**
|
|
33911
|
-
* Run a finite operation with a flow-owned remote resource and release it
|
|
33912
|
-
* after either success or failure.
|
|
33913
|
-
*
|
|
33914
|
-
* Resource implementations make `dispose()` idempotent. This helper makes the
|
|
33915
|
-
* caller's ownership boundary explicit and prevents finite flows from leaking
|
|
33916
|
-
* a provider-owned resource when their operation rejects.
|
|
33917
|
-
*/
|
|
33918
|
-
async function withOwnedRemoteResource(resource, operation) {
|
|
33919
|
-
try {
|
|
33920
|
-
return await operation(resource);
|
|
33921
|
-
} finally {
|
|
33922
|
-
await resource.dispose();
|
|
33923
|
-
}
|
|
33924
|
-
}
|
|
33925
|
-
//#endregion
|
|
33926
34067
|
//#region ../../modules/coreFeatures/ModuleResolveMismatchedTweaks.ts
|
|
33927
34068
|
function canSetPreferredRemoteTweakSettings$1(replicator) {
|
|
33928
34069
|
return "setPreferredRemoteTweakSettings" in replicator && typeof replicator.setPreferredRemoteTweakSettings === "function";
|
|
@@ -33941,10 +34082,37 @@ function valueToString(value) {
|
|
|
33941
34082
|
if (typeof value === "object") return JSON.stringify(value);
|
|
33942
34083
|
return `${value}`;
|
|
33943
34084
|
}
|
|
34085
|
+
function definedTweaks(values) {
|
|
34086
|
+
return Object.fromEntries(Object.entries(values).filter(([key, value]) => key in TweakValuesTemplate && value !== void 0));
|
|
34087
|
+
}
|
|
34088
|
+
function settingsAfterAdoption(assessment, direction) {
|
|
34089
|
+
const comparedKeys = new Set(assessment.entries.map((entry) => entry.key));
|
|
34090
|
+
const source = direction === "adoptPreferred" ? assessment.preferredValues : assessment.currentValues;
|
|
34091
|
+
const target = direction === "adoptPreferred" ? assessment.currentValues : assessment.preferredValues;
|
|
34092
|
+
const recommendations = Object.fromEntries(Object.entries(source).filter(([key, value]) => !comparedKeys.has(key) && value !== void 0));
|
|
34093
|
+
return {
|
|
34094
|
+
...definedTweaks(target),
|
|
34095
|
+
...recommendations,
|
|
34096
|
+
...assessment[direction].changes
|
|
34097
|
+
};
|
|
34098
|
+
}
|
|
34099
|
+
function mismatchTable(assessment, direction) {
|
|
34100
|
+
const reasons = direction ? assessment[direction].reasons : [...assessment.adoptPreferred.reasons, ...assessment.adoptCurrent.reasons];
|
|
34101
|
+
const consequenceKeys = new Set(reasons.map((reason) => reason.key));
|
|
34102
|
+
return $msg("TweakMismatchResolve.Table", { rows: assessment.entries.filter((entry) => entry.relation === "different" || consequenceKeys.has(entry.key)).map((entry) => $msg("TweakMismatchResolve.Table.Row", {
|
|
34103
|
+
name: localisedConfName(entry.key),
|
|
34104
|
+
self: valueToString(escapeMarkdownValue(entry.current.effectiveValue)),
|
|
34105
|
+
remote: valueToString(escapeMarkdownValue(entry.preferred.effectiveValue))
|
|
34106
|
+
})).join("\n") });
|
|
34107
|
+
}
|
|
34108
|
+
/** Kept only while resolving a decision; this can contain credentials and must never be logged. */
|
|
34109
|
+
function resolutionSettingsSignature(settings) {
|
|
34110
|
+
return JSON.stringify({
|
|
34111
|
+
...settings,
|
|
34112
|
+
autoAcceptCompatibleTweak: settings.autoAcceptCompatibleTweak ?? true
|
|
34113
|
+
});
|
|
34114
|
+
}
|
|
33944
34115
|
var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
|
|
33945
|
-
_collectMismatchedTweakKeys(current, preferred) {
|
|
33946
|
-
return Object.keys(TweakValuesShouldMatchedTemplate).filter((key) => current[key] !== preferred[key]);
|
|
33947
|
-
}
|
|
33948
34116
|
_selectNewerTweakSide(current, preferred) {
|
|
33949
34117
|
Logger(`Modified: ${current.tweakModified} (current) vs ${preferred.tweakModified} (preferred)`);
|
|
33950
34118
|
const currentModified = current.tweakModified;
|
|
@@ -33957,9 +34125,8 @@ var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
|
|
|
33957
34125
|
if (preferredModified >= currentModified) return "REMOTE";
|
|
33958
34126
|
return "CURRENT";
|
|
33959
34127
|
}
|
|
33960
|
-
async _shouldAutoAcceptCompatibleLossy(
|
|
33961
|
-
if (
|
|
33962
|
-
if (!mismatchedKeys.every((key) => CompatibleButLossyChanges.indexOf(key) !== -1)) return void 0;
|
|
34128
|
+
async _shouldAutoAcceptCompatibleLossy(assessment) {
|
|
34129
|
+
if (!assessment.onlyCompatibleLossyDifferences) return void 0;
|
|
33963
34130
|
let autoAcceptCompatibleTweak = this.settings.autoAcceptCompatibleTweak;
|
|
33964
34131
|
if (this.settings.autoAcceptCompatibleTweak === void 0) {
|
|
33965
34132
|
this.settings.autoAcceptCompatibleTweak = true;
|
|
@@ -33968,7 +34135,7 @@ var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
|
|
|
33968
34135
|
Logger("Automatic alignment of compatible chunk settings has been enabled.");
|
|
33969
34136
|
}
|
|
33970
34137
|
if (autoAcceptCompatibleTweak !== true) return void 0;
|
|
33971
|
-
return this._selectNewerTweakSide(
|
|
34138
|
+
return this._selectNewerTweakSide(assessment.currentValues, assessment.preferredValues);
|
|
33972
34139
|
}
|
|
33973
34140
|
/**
|
|
33974
34141
|
* Hook before saving settings, to check if there are changes in tweak values, and if so,
|
|
@@ -33989,6 +34156,8 @@ var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
|
|
|
33989
34156
|
async _anyAfterConnectCheckFailed(failure) {
|
|
33990
34157
|
const recovery = failure.outcome.recoveryHint;
|
|
33991
34158
|
if (recovery?.reason !== CENTRAL_COMPATIBILITY_REJECTION_REASONS.TWEAK_MISMATCH || !recovery.preferredTweakValue) return false;
|
|
34159
|
+
if (!await this.services.replicator.runWithActiveReplicatorContext((activeContext) => activeContext === failure.context) || resolutionSettingsSignature(failure.setting) !== resolutionSettingsSignature(this.settings)) return true;
|
|
34160
|
+
const assessment = recovery.tweakAssessment ?? assessTweakCompatibility(failure.setting, recovery.preferredTweakValue);
|
|
33992
34161
|
const ret = await this.services.tweakValue.askResolvingMismatched({ ...recovery.preferredTweakValue }, async (setting) => {
|
|
33993
34162
|
let updated = false;
|
|
33994
34163
|
await this.services.replicator.runWithActiveReplicatorContext(async (activeContext) => {
|
|
@@ -33998,103 +34167,83 @@ var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
|
|
|
33998
34167
|
updated = true;
|
|
33999
34168
|
});
|
|
34000
34169
|
return updated;
|
|
34001
|
-
});
|
|
34170
|
+
}, assessment);
|
|
34002
34171
|
if (ret == "OK") return false;
|
|
34003
34172
|
if (ret == "CHECKAGAIN") return "CHECKAGAIN";
|
|
34004
34173
|
if (ret == "IGNORE") return true;
|
|
34005
34174
|
}
|
|
34006
|
-
async _checkAndAskResolvingMismatchedTweaks(preferred) {
|
|
34007
|
-
|
|
34008
|
-
const
|
|
34009
|
-
const autoAcceptSide = await this._shouldAutoAcceptCompatibleLossy(
|
|
34010
|
-
if (autoAcceptSide === "REMOTE") return [
|
|
34011
|
-
...mine,
|
|
34012
|
-
...preferred
|
|
34013
|
-
}, false];
|
|
34175
|
+
async _checkAndAskResolvingMismatchedTweaks(preferred, assessment = assessTweakCompatibility(this.settings, preferred)) {
|
|
34176
|
+
if (assessment.alignment === "matched") return [false, false];
|
|
34177
|
+
const acceptedSettings = settingsAfterAdoption(assessment, "adoptPreferred");
|
|
34178
|
+
const autoAcceptSide = await this._shouldAutoAcceptCompatibleLossy(assessment);
|
|
34179
|
+
if (autoAcceptSide === "REMOTE") return [acceptedSettings, false];
|
|
34014
34180
|
if (autoAcceptSide === "CURRENT") return [true, false];
|
|
34015
|
-
const
|
|
34016
|
-
|
|
34017
|
-
|
|
34018
|
-
const
|
|
34019
|
-
|
|
34020
|
-
|
|
34021
|
-
const valueMine = escapeMarkdownValue(mine[key]);
|
|
34022
|
-
const valuePreferred = escapeMarkdownValue(preferred[key]);
|
|
34023
|
-
if (valueMine == valuePreferred) continue;
|
|
34024
|
-
if (IncompatibleChanges.indexOf(key) !== -1) rebuildRequired = true;
|
|
34025
|
-
for (const pattern of IncompatibleChangesInSpecificPattern) {
|
|
34026
|
-
if (pattern.key !== key) continue;
|
|
34027
|
-
const isFromConditionMet = "from" in pattern ? pattern.from === mine[key] : false;
|
|
34028
|
-
const isToConditionMet = "to" in pattern ? pattern.to === preferred[key] : false;
|
|
34029
|
-
if (isFromConditionMet || isToConditionMet) if (pattern.isRecommendation) rebuildRecommended = true;
|
|
34030
|
-
else rebuildRequired = true;
|
|
34031
|
-
}
|
|
34032
|
-
if (CompatibleButLossyChanges.indexOf(key) !== -1) rebuildRecommended = true;
|
|
34033
|
-
tableRows.push($msg("TweakMismatchResolve.Table.Row", {
|
|
34034
|
-
name: localisedConfName(key),
|
|
34035
|
-
self: valueToString(valueMine),
|
|
34036
|
-
remote: valueToString(valuePreferred)
|
|
34037
|
-
}));
|
|
34038
|
-
}
|
|
34039
|
-
const additionalMessage = rebuildRequired && this.core.settings.isConfigured ? $msg("TweakMismatchResolve.Message.WarningIncompatibleRebuildRequired") : "";
|
|
34040
|
-
const additionalMessage2 = rebuildRecommended && this.core.settings.isConfigured ? $msg("TweakMismatchResolve.Message.WarningIncompatibleRebuildRecommended") : "";
|
|
34181
|
+
const localImpact = assessment.adoptPreferred.reconstruction;
|
|
34182
|
+
const remoteImpact = assessment.adoptCurrent.reconstruction;
|
|
34183
|
+
const requiresRebuild = localImpact === "required" || remoteImpact === "required";
|
|
34184
|
+
const recommendsRebuild = localImpact === "recommended" || remoteImpact === "recommended";
|
|
34185
|
+
const additionalMessage = requiresRebuild && this.settings.isConfigured ? $msg("TweakMismatchResolve.Message.WarningIncompatibleRebuildRequired") : "";
|
|
34186
|
+
const additionalMessage2 = recommendsRebuild && this.settings.isConfigured ? $msg("TweakMismatchResolve.Message.WarningIncompatibleRebuildRecommended") : "";
|
|
34041
34187
|
const message = $msg("TweakMismatchResolve.Message.MainTweakResolving", {
|
|
34042
|
-
table:
|
|
34043
|
-
additionalMessage: [additionalMessage, additionalMessage2].filter(
|
|
34188
|
+
table: mismatchTable(assessment),
|
|
34189
|
+
additionalMessage: [additionalMessage, additionalMessage2].filter(Boolean).join("\n")
|
|
34044
34190
|
});
|
|
34045
|
-
const
|
|
34046
|
-
const
|
|
34047
|
-
|
|
34048
|
-
|
|
34049
|
-
|
|
34050
|
-
|
|
34051
|
-
const
|
|
34052
|
-
|
|
34053
|
-
|
|
34054
|
-
|
|
34055
|
-
|
|
34056
|
-
|
|
34057
|
-
|
|
34058
|
-
|
|
34059
|
-
|
|
34060
|
-
|
|
34061
|
-
|
|
34062
|
-
|
|
34063
|
-
} else {
|
|
34064
|
-
CHOICE_AND_VALUES.push([CHOICE_USE_REMOTE, [preferred, false]]);
|
|
34065
|
-
CHOICE_AND_VALUES.push([CHOICE_USE_MINE, [true, false]]);
|
|
34066
|
-
}
|
|
34067
|
-
CHOICE_AND_VALUES.push([CHOICE_DISMISS, [false, false]]);
|
|
34068
|
-
const CHOICES = Object.fromEntries(CHOICE_AND_VALUES);
|
|
34069
|
-
const retKey = await this.core.confirm.askSelectStringDialogue(message, Object.keys(CHOICES), {
|
|
34191
|
+
const choices = {};
|
|
34192
|
+
const remoteChoices = {
|
|
34193
|
+
ordinary: $msg("TweakMismatchResolve.Action.UseRemote"),
|
|
34194
|
+
rebuild: $msg("TweakMismatchResolve.Action.UseRemoteWithRebuild"),
|
|
34195
|
+
accept: $msg("TweakMismatchResolve.Action.UseRemoteAcceptIncompatible")
|
|
34196
|
+
};
|
|
34197
|
+
const localChoices = {
|
|
34198
|
+
ordinary: $msg("TweakMismatchResolve.Action.UseMine"),
|
|
34199
|
+
rebuild: $msg("TweakMismatchResolve.Action.UseMineWithRebuild"),
|
|
34200
|
+
accept: $msg("TweakMismatchResolve.Action.UseMineAcceptIncompatible")
|
|
34201
|
+
};
|
|
34202
|
+
choices[localImpact === "required" ? remoteChoices.rebuild : remoteChoices.ordinary] = [acceptedSettings, localImpact === "required"];
|
|
34203
|
+
choices[remoteImpact === "required" ? localChoices.rebuild : localChoices.ordinary] = [true, remoteImpact === "required"];
|
|
34204
|
+
if (localImpact !== "none") choices[localImpact === "required" ? remoteChoices.accept : remoteChoices.rebuild] = [acceptedSettings, localImpact !== "required"];
|
|
34205
|
+
if (remoteImpact !== "none") choices[remoteImpact === "required" ? localChoices.accept : localChoices.rebuild] = [true, remoteImpact !== "required"];
|
|
34206
|
+
const dismiss = $msg("TweakMismatchResolve.Action.Dismiss");
|
|
34207
|
+
choices[dismiss] = [false, false];
|
|
34208
|
+
const retKey = await this.core.confirm.askSelectStringDialogue(message, Object.keys(choices), {
|
|
34070
34209
|
title: $msg("TweakMismatchResolve.Title.TweakResolving"),
|
|
34071
34210
|
timeout: 60,
|
|
34072
|
-
defaultAction:
|
|
34211
|
+
defaultAction: dismiss
|
|
34073
34212
|
});
|
|
34074
|
-
|
|
34075
|
-
|
|
34076
|
-
|
|
34077
|
-
|
|
34078
|
-
const
|
|
34213
|
+
return retKey && choices[retKey] || [false, false];
|
|
34214
|
+
}
|
|
34215
|
+
async _askResolvingMismatchedTweaks(preferredSource, updatePreferredRemote, assessment = assessTweakCompatibility(this.settings, preferredSource)) {
|
|
34216
|
+
const signature = resolutionSettingsSignature(this.settings);
|
|
34217
|
+
const publication = await this.services.replicator.acquireActiveReplicatorContext();
|
|
34218
|
+
if (resolutionSettingsSignature(this.settings) !== signature) return "IGNORE";
|
|
34219
|
+
const currentTweaks = JSON.stringify(extractObject(TweakValuesTemplate, this.settings));
|
|
34220
|
+
if (JSON.stringify(extractObject(TweakValuesTemplate, assessment.currentValues)) !== currentTweaks) return "IGNORE";
|
|
34221
|
+
const [conf, rebuildRequired] = await this.services.tweakValue.checkAndAskResolvingMismatched(preferredSource, assessment);
|
|
34079
34222
|
if (!conf) return "IGNORE";
|
|
34080
|
-
|
|
34081
|
-
|
|
34223
|
+
if (await this.services.replicator.acquireActiveReplicatorContext() !== publication || resolutionSettingsSignature(this.settings) !== signature) return "IGNORE";
|
|
34224
|
+
const updateRemote = async (tweaks) => {
|
|
34225
|
+
const setting = {
|
|
34226
|
+
...this.settings,
|
|
34227
|
+
...definedTweaks(assessment.preferredValues),
|
|
34228
|
+
...definedTweaks(tweaks)
|
|
34229
|
+
};
|
|
34230
|
+
if (updatePreferredRemote) return await updatePreferredRemote(setting);
|
|
34082
34231
|
const candidate = this.core.replicator;
|
|
34083
34232
|
if (typeof candidate.setPreferredRemoteTweakSettings !== "function") return false;
|
|
34084
|
-
await candidate.setPreferredRemoteTweakSettings(
|
|
34233
|
+
await candidate.setPreferredRemoteTweakSettings(setting);
|
|
34085
34234
|
return true;
|
|
34086
34235
|
};
|
|
34087
34236
|
if (conf === true) {
|
|
34088
|
-
if (!await updateRemote()) return "IGNORE";
|
|
34237
|
+
if (!await updateRemote(settingsAfterAdoption(assessment, "adoptCurrent"))) return "IGNORE";
|
|
34089
34238
|
if (rebuildRequired) await this.core.rebuilder.$rebuildRemote();
|
|
34090
34239
|
Logger($msg("TweakMismatchResolve.Message.remoteUpdated"), 64);
|
|
34091
34240
|
return "CHECKAGAIN";
|
|
34092
34241
|
}
|
|
34093
34242
|
if (conf) {
|
|
34094
|
-
Object.assign(this.settings,
|
|
34243
|
+
Object.assign(this.settings, definedTweaks(conf));
|
|
34095
34244
|
await this.services.setting.saveSettingData();
|
|
34096
34245
|
if (!rebuildRequired) await this.localDatabase.managers.reinitialise();
|
|
34097
|
-
if (!await updateRemote()) return "IGNORE";
|
|
34246
|
+
if (!await updateRemote(this.settings)) return "IGNORE";
|
|
34098
34247
|
if (rebuildRequired) await this.core.rebuilder.$fetchLocal();
|
|
34099
34248
|
Logger($msg("TweakMismatchResolve.Message.mineUpdated"), 64);
|
|
34100
34249
|
return "CHECKAGAIN";
|
|
@@ -34122,7 +34271,12 @@ var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
|
|
|
34122
34271
|
result: false,
|
|
34123
34272
|
requireFetch: false
|
|
34124
34273
|
};
|
|
34274
|
+
const signature = JSON.stringify(trialSetting);
|
|
34125
34275
|
const preferred = await this.services.tweakValue.fetchRemotePreferred(trialSetting);
|
|
34276
|
+
if (JSON.stringify(trialSetting) !== signature) return {
|
|
34277
|
+
result: false,
|
|
34278
|
+
requireFetch: false
|
|
34279
|
+
};
|
|
34126
34280
|
if (preferred.status === RemotePreferredTweakStatuses.AVAILABLE) return await this.services.tweakValue.askUseRemoteConfiguration(trialSetting, preferred.values);
|
|
34127
34281
|
return {
|
|
34128
34282
|
result: false,
|
|
@@ -34130,87 +34284,61 @@ var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
|
|
|
34130
34284
|
};
|
|
34131
34285
|
}
|
|
34132
34286
|
async _askUseRemoteConfiguration(trialSetting, preferred) {
|
|
34133
|
-
const
|
|
34134
|
-
const
|
|
34135
|
-
const
|
|
34136
|
-
if (
|
|
34137
|
-
result: {
|
|
34138
|
-
...trialSetting,
|
|
34139
|
-
...preferred
|
|
34140
|
-
},
|
|
34141
|
-
requireFetch: false
|
|
34142
|
-
};
|
|
34143
|
-
if (autoAcceptSide === "CURRENT") return {
|
|
34144
|
-
result: false,
|
|
34145
|
-
requireFetch: false
|
|
34146
|
-
};
|
|
34147
|
-
const items = Object.entries(TweakValuesShouldMatchedTemplate);
|
|
34148
|
-
let rebuildRequired = false;
|
|
34149
|
-
let rebuildRecommended = false;
|
|
34150
|
-
let differenceCount = 0;
|
|
34151
|
-
const tableRows = [];
|
|
34152
|
-
for (const v of items) {
|
|
34153
|
-
const key = v[0];
|
|
34154
|
-
const remoteValueForDisplay = escapeMarkdownValue(valueToString(preferred[key]));
|
|
34155
|
-
const currentValueForDisplay = escapeMarkdownValue(valueToString(trialSetting?.[key]));
|
|
34156
|
-
if (trialSetting?.[key] !== preferred[key]) {
|
|
34157
|
-
if (IncompatibleChanges.indexOf(key) !== -1) rebuildRequired = true;
|
|
34158
|
-
for (const pattern of IncompatibleChangesInSpecificPattern) {
|
|
34159
|
-
if (pattern.key !== key) continue;
|
|
34160
|
-
const isFromConditionMet = "from" in pattern ? pattern.from === trialSetting?.[key] : false;
|
|
34161
|
-
const isToConditionMet = "to" in pattern ? pattern.to === preferred[key] : false;
|
|
34162
|
-
if (isFromConditionMet || isToConditionMet) if (pattern.isRecommendation) rebuildRecommended = true;
|
|
34163
|
-
else rebuildRequired = true;
|
|
34164
|
-
}
|
|
34165
|
-
if (CompatibleButLossyChanges.indexOf(key) !== -1) rebuildRecommended = true;
|
|
34166
|
-
} else continue;
|
|
34167
|
-
tableRows.push($msg("TweakMismatchResolve.Table.Row", {
|
|
34168
|
-
name: localisedConfName(key),
|
|
34169
|
-
self: currentValueForDisplay,
|
|
34170
|
-
remote: remoteValueForDisplay
|
|
34171
|
-
}));
|
|
34172
|
-
differenceCount++;
|
|
34173
|
-
}
|
|
34174
|
-
if (differenceCount === 0) {
|
|
34287
|
+
const trialSignature = JSON.stringify(trialSetting);
|
|
34288
|
+
const currentSignature = resolutionSettingsSignature(this.settings);
|
|
34289
|
+
const assessment = assessTweakCompatibility(trialSetting, preferred);
|
|
34290
|
+
if (assessment.alignment === "matched") {
|
|
34175
34291
|
this._log("The settings in the remote database are the same as the local database.", 64);
|
|
34176
34292
|
return {
|
|
34177
34293
|
result: false,
|
|
34178
34294
|
requireFetch: false
|
|
34179
34295
|
};
|
|
34180
34296
|
}
|
|
34181
|
-
const
|
|
34182
|
-
const
|
|
34183
|
-
|
|
34184
|
-
table: $msg("TweakMismatchResolve.Table", { rows: tableRows.join("\n") }),
|
|
34185
|
-
additionalMessage: [additionalMessage, additionalMessage2].filter((v) => v).join("\n")
|
|
34186
|
-
});
|
|
34187
|
-
const CHOICE_USE_REMOTE = $msg("TweakMismatchResolve.Action.UseConfigured");
|
|
34188
|
-
const CHOICE_DISMISS = $msg("TweakMismatchResolve.Action.Dismiss");
|
|
34189
|
-
const CHOICES = [CHOICE_USE_REMOTE, CHOICE_DISMISS];
|
|
34190
|
-
const retKey = await this.core.confirm.askSelectStringDialogue(message, CHOICES, {
|
|
34191
|
-
title: $msg("TweakMismatchResolve.Title.UseRemoteConfig"),
|
|
34192
|
-
timeout: 0,
|
|
34193
|
-
defaultAction: CHOICE_DISMISS
|
|
34194
|
-
});
|
|
34195
|
-
if (!retKey) return {
|
|
34297
|
+
const publication = await this.services.replicator.acquireActiveReplicatorContext();
|
|
34298
|
+
const settingsStillCurrent = () => JSON.stringify(trialSetting) === trialSignature && resolutionSettingsSignature(this.settings) === currentSignature;
|
|
34299
|
+
if (!settingsStillCurrent()) return {
|
|
34196
34300
|
result: false,
|
|
34197
34301
|
requireFetch: false
|
|
34198
34302
|
};
|
|
34199
|
-
|
|
34303
|
+
const stillCurrent = async () => await this.services.replicator.acquireActiveReplicatorContext() === publication && settingsStillCurrent();
|
|
34304
|
+
const acceptedSettings = {
|
|
34305
|
+
...trialSetting,
|
|
34306
|
+
...settingsAfterAdoption(assessment, "adoptPreferred")
|
|
34307
|
+
};
|
|
34308
|
+
const autoAcceptSide = await this._shouldAutoAcceptCompatibleLossy(assessment);
|
|
34309
|
+
if (!await stillCurrent()) return {
|
|
34200
34310
|
result: false,
|
|
34201
34311
|
requireFetch: false
|
|
34202
34312
|
};
|
|
34203
|
-
if (
|
|
34204
|
-
result:
|
|
34205
|
-
|
|
34206
|
-
...preferred
|
|
34207
|
-
},
|
|
34208
|
-
requireFetch: rebuildRequired
|
|
34313
|
+
if (autoAcceptSide === "REMOTE") return {
|
|
34314
|
+
result: acceptedSettings,
|
|
34315
|
+
requireFetch: false
|
|
34209
34316
|
};
|
|
34210
|
-
return {
|
|
34317
|
+
if (autoAcceptSide === "CURRENT") return {
|
|
34318
|
+
result: false,
|
|
34319
|
+
requireFetch: false
|
|
34320
|
+
};
|
|
34321
|
+
const impact = assessment.adoptPreferred.reconstruction;
|
|
34322
|
+
const additionalMessage = impact === "required" && this.settings.isConfigured ? $msg("TweakMismatchResolve.Message.UseRemote.WarningRebuildRequired") : "";
|
|
34323
|
+
const additionalMessage2 = impact === "recommended" && this.settings.isConfigured ? $msg("TweakMismatchResolve.Message.UseRemote.WarningRebuildRecommended") : "";
|
|
34324
|
+
const message = $msg("TweakMismatchResolve.Message.Main", {
|
|
34325
|
+
table: mismatchTable(assessment, "adoptPreferred"),
|
|
34326
|
+
additionalMessage: [additionalMessage, additionalMessage2].filter(Boolean).join("\n")
|
|
34327
|
+
});
|
|
34328
|
+
const useRemote = $msg("TweakMismatchResolve.Action.UseConfigured");
|
|
34329
|
+
const dismiss = $msg("TweakMismatchResolve.Action.Dismiss");
|
|
34330
|
+
if (await this.core.confirm.askSelectStringDialogue(message, [useRemote, dismiss], {
|
|
34331
|
+
title: $msg("TweakMismatchResolve.Title.UseRemoteConfig"),
|
|
34332
|
+
timeout: 0,
|
|
34333
|
+
defaultAction: dismiss
|
|
34334
|
+
}) !== useRemote || !await stillCurrent()) return {
|
|
34211
34335
|
result: false,
|
|
34212
34336
|
requireFetch: false
|
|
34213
34337
|
};
|
|
34338
|
+
return {
|
|
34339
|
+
result: acceptedSettings,
|
|
34340
|
+
requireFetch: impact === "required"
|
|
34341
|
+
};
|
|
34214
34342
|
}
|
|
34215
34343
|
onBindFunction(core, services) {
|
|
34216
34344
|
services.setting.onBeforeSaveSettingData.addHandler(this._onBeforeSaveSettingData.bind(this));
|
|
@@ -34224,407 +34352,710 @@ var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
|
|
|
34224
34352
|
};
|
|
34225
34353
|
//#endregion
|
|
34226
34354
|
//#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/common/coreEnvVars.js
|
|
34227
|
-
var manifestVersion = "1.0.
|
|
34228
|
-
var packageVersion = "1.0.
|
|
34355
|
+
var manifestVersion = "1.0.28";
|
|
34356
|
+
var packageVersion = "1.0.28";
|
|
34229
34357
|
//#endregion
|
|
34230
|
-
//#region
|
|
34231
|
-
|
|
34232
|
-
|
|
34233
|
-
|
|
34234
|
-
|
|
34235
|
-
|
|
34236
|
-
|
|
34237
|
-
|
|
34238
|
-
|
|
34239
|
-
|
|
34240
|
-
|
|
34241
|
-
|
|
34242
|
-
|
|
34243
|
-
|
|
34244
|
-
|
|
34245
|
-
|
|
34246
|
-
|
|
34247
|
-
|
|
34248
|
-
|
|
34249
|
-
|
|
34250
|
-
|
|
34358
|
+
//#region ../../../node_modules/octagonal-wheels/dist/iterable/map.js
|
|
34359
|
+
/**
|
|
34360
|
+
* apply a function to each element of an iterable asynchronously with a concurrency limit.
|
|
34361
|
+
* Note that the order of the elements is not guaranteed.
|
|
34362
|
+
* @param iterable An iterable items to be processed.
|
|
34363
|
+
* @param callback A function to be applied to each element of the iterable.
|
|
34364
|
+
* @param concurrency The number of concurrent processes.
|
|
34365
|
+
*/
|
|
34366
|
+
async function* withConcurrency(iterable, callback, concurrency) {
|
|
34367
|
+
const processes = /* @__PURE__ */ new Set();
|
|
34368
|
+
const mapTaskToPromise = /* @__PURE__ */ new Map();
|
|
34369
|
+
let serial = 0;
|
|
34370
|
+
const enqueue = (item) => {
|
|
34371
|
+
const idx = serial++;
|
|
34372
|
+
const promise = (async () => [idx, await callback(item)])();
|
|
34373
|
+
processes.add(promise);
|
|
34374
|
+
mapTaskToPromise.set(idx, promise);
|
|
34375
|
+
};
|
|
34376
|
+
const consume = async () => {
|
|
34377
|
+
const r = await Promise.race(processes);
|
|
34378
|
+
const item = mapTaskToPromise.get(r[0]);
|
|
34379
|
+
processes.delete(item);
|
|
34380
|
+
mapTaskToPromise.delete(r[0]);
|
|
34381
|
+
return r[1];
|
|
34382
|
+
};
|
|
34383
|
+
for await (const t of iterable) {
|
|
34384
|
+
while (processes.size >= concurrency) yield await consume();
|
|
34385
|
+
enqueue(t);
|
|
34386
|
+
}
|
|
34387
|
+
while (processes.size > 0) yield await consume();
|
|
34388
|
+
}
|
|
34389
|
+
//#endregion
|
|
34390
|
+
//#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/services/base/VaultScanResult.js
|
|
34391
|
+
var VaultScanResults = {
|
|
34392
|
+
FAILED: false,
|
|
34393
|
+
COMPLETED: true,
|
|
34394
|
+
COMPLETED_WITH_FILE_FAILURES: "completed-with-file-failures"
|
|
34395
|
+
};
|
|
34396
|
+
//#endregion
|
|
34397
|
+
//#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/serviceFeatures/offlineScanner.js
|
|
34398
|
+
var FilePairProcessResults = {
|
|
34399
|
+
COMPLETED: "completed",
|
|
34400
|
+
SKIPPED: "skipped",
|
|
34401
|
+
FAILED: "failed"
|
|
34402
|
+
};
|
|
34403
|
+
var MetadataDocumentNamespaces = {
|
|
34404
|
+
NORMAL: "normal",
|
|
34405
|
+
INTERNAL: "internal",
|
|
34406
|
+
CUSTOMISATION: "customisation",
|
|
34407
|
+
PLUGIN_STORAGE: "plugin-storage"
|
|
34408
|
+
};
|
|
34409
|
+
var MetadataDocumentIdentityStatuses = {
|
|
34410
|
+
CONSISTENT: "consistent",
|
|
34411
|
+
EXCLUDED: "excluded",
|
|
34412
|
+
UNRESOLVED: "unresolved"
|
|
34413
|
+
};
|
|
34414
|
+
var OfflineScanUnresolvedReasons = {
|
|
34415
|
+
DOCUMENT_ID_MISMATCH: "document-id-mismatch",
|
|
34416
|
+
NAMESPACE_MISMATCH: "namespace-mismatch"
|
|
34417
|
+
};
|
|
34418
|
+
function getMetadataDocumentNamespace(value) {
|
|
34419
|
+
if (value.startsWith("ix:")) return MetadataDocumentNamespaces.CUSTOMISATION;
|
|
34420
|
+
if (value.startsWith("i:")) return MetadataDocumentNamespaces.INTERNAL;
|
|
34421
|
+
if (value.startsWith("ps:")) return MetadataDocumentNamespaces.PLUGIN_STORAGE;
|
|
34422
|
+
return MetadataDocumentNamespaces.NORMAL;
|
|
34423
|
+
}
|
|
34424
|
+
async function inspectMetadataDocumentIdentity(host, doc) {
|
|
34425
|
+
const actualDocumentId = doc._id;
|
|
34426
|
+
const declaredPath = getPathFromEntry(host, doc);
|
|
34427
|
+
const actualNamespace = getMetadataDocumentNamespace(actualDocumentId);
|
|
34428
|
+
const declaredPathNamespace = getMetadataDocumentNamespace(declaredPath);
|
|
34429
|
+
if (actualNamespace !== MetadataDocumentNamespaces.NORMAL || declaredPathNamespace !== MetadataDocumentNamespaces.NORMAL) {
|
|
34430
|
+
if (actualNamespace === declaredPathNamespace) return {
|
|
34431
|
+
status: MetadataDocumentIdentityStatuses.EXCLUDED,
|
|
34432
|
+
actualDocumentId,
|
|
34433
|
+
declaredPath,
|
|
34434
|
+
namespace: actualNamespace
|
|
34435
|
+
};
|
|
34436
|
+
return {
|
|
34437
|
+
status: MetadataDocumentIdentityStatuses.UNRESOLVED,
|
|
34438
|
+
diagnostic: {
|
|
34439
|
+
reason: OfflineScanUnresolvedReasons.NAMESPACE_MISMATCH,
|
|
34440
|
+
actualDocumentId,
|
|
34441
|
+
declaredPath,
|
|
34442
|
+
actualNamespace,
|
|
34443
|
+
declaredPathNamespace
|
|
34251
34444
|
}
|
|
34252
|
-
}
|
|
34253
|
-
if (!await this.services.databaseEvents.initialiseDatabase(false, false)) return false;
|
|
34254
|
-
if (!await this.core.services.appLifecycle.onFirstInitialise()) return false;
|
|
34255
|
-
await this.services.control.applySettings();
|
|
34256
|
-
fireAndForget(async () => {
|
|
34257
|
-
this._log($msg("moduleLiveSyncMain.logAdditionalSafetyScan"), 16);
|
|
34258
|
-
if (!await this.services.appLifecycle.onScanningStartupIssues()) this._log($msg("moduleLiveSyncMain.logSafetyScanFailed"), 64);
|
|
34259
|
-
else this._log($msg("moduleLiveSyncMain.logSafetyScanCompleted"), 16);
|
|
34260
|
-
});
|
|
34261
|
-
return true;
|
|
34445
|
+
};
|
|
34262
34446
|
}
|
|
34263
|
-
|
|
34264
|
-
|
|
34265
|
-
|
|
34266
|
-
|
|
34267
|
-
|
|
34268
|
-
|
|
34269
|
-
|
|
34270
|
-
|
|
34271
|
-
|
|
34272
|
-
|
|
34273
|
-
|
|
34447
|
+
const expectedDocumentId = await host.services.path.path2id(declaredPath);
|
|
34448
|
+
if (actualDocumentId !== expectedDocumentId) return {
|
|
34449
|
+
status: MetadataDocumentIdentityStatuses.UNRESOLVED,
|
|
34450
|
+
diagnostic: {
|
|
34451
|
+
reason: OfflineScanUnresolvedReasons.DOCUMENT_ID_MISMATCH,
|
|
34452
|
+
actualDocumentId,
|
|
34453
|
+
declaredPath,
|
|
34454
|
+
expectedDocumentId,
|
|
34455
|
+
actualNamespace,
|
|
34456
|
+
declaredPathNamespace
|
|
34457
|
+
}
|
|
34458
|
+
};
|
|
34459
|
+
return {
|
|
34460
|
+
status: MetadataDocumentIdentityStatuses.CONSISTENT,
|
|
34461
|
+
actualDocumentId,
|
|
34462
|
+
declaredPath,
|
|
34463
|
+
expectedDocumentId
|
|
34464
|
+
};
|
|
34465
|
+
}
|
|
34466
|
+
async function collectDeletedFiles(host, log) {
|
|
34467
|
+
const limitDays = host.services.setting.currentSettings().automaticallyDeleteMetadataOfDeletedFiles;
|
|
34468
|
+
if (limitDays <= 0) return;
|
|
34469
|
+
log(`Checking expired file history`);
|
|
34470
|
+
const limit = Date.now() - 86400 * 1e3 * limitDays;
|
|
34471
|
+
const notes = [];
|
|
34472
|
+
for await (const doc of host.services.database.localDatabase.findAllDocs({ conflicts: true })) if (isAnyNote(doc)) {
|
|
34473
|
+
if (doc.deleted && doc.mtime - limit < 0) {
|
|
34474
|
+
if (isMetaEntry(doc)) {
|
|
34475
|
+
const identity = await inspectMetadataDocumentIdentity(host, doc);
|
|
34476
|
+
if (identity.status === MetadataDocumentIdentityStatuses.UNRESOLVED) {
|
|
34477
|
+
log(`Expired deletion history has an unresolved Metadata identity and will be left unchanged: ${identity.diagnostic.declaredPath} (${identity.diagnostic.reason})`, 32);
|
|
34478
|
+
continue;
|
|
34274
34479
|
}
|
|
34480
|
+
}
|
|
34481
|
+
notes.push({
|
|
34482
|
+
path: doc.path,
|
|
34483
|
+
mtime: doc.mtime,
|
|
34484
|
+
ttl: (doc.mtime - limit) / 1e3 / 86400,
|
|
34485
|
+
doc
|
|
34275
34486
|
});
|
|
34276
|
-
});
|
|
34277
|
-
return Promise.resolve(true);
|
|
34278
|
-
}
|
|
34279
|
-
async _onLiveSyncLoad() {
|
|
34280
|
-
this.services.context.events;
|
|
34281
|
-
await this.services.appLifecycle.onWireUpEvents();
|
|
34282
|
-
eventHub.emitEvent(EVENT_PLUGIN_LOADED);
|
|
34283
|
-
this._log($msg("moduleLiveSyncMain.logLoadingPlugin"));
|
|
34284
|
-
if (!await this.services.appLifecycle.onInitialise()) {
|
|
34285
|
-
this._log($msg("moduleLiveSyncMain.logPluginInitCancelled"), 64);
|
|
34286
|
-
return false;
|
|
34287
|
-
}
|
|
34288
|
-
this._log($msg("moduleLiveSyncMain.logPluginVersion", {
|
|
34289
|
-
manifestVersion,
|
|
34290
|
-
packageVersion
|
|
34291
|
-
}));
|
|
34292
|
-
await this.services.setting.loadSettings();
|
|
34293
|
-
if (!await this.services.appLifecycle.onSettingLoaded()) {
|
|
34294
|
-
this._log($msg("moduleLiveSyncMain.logPluginInitCancelled"), 64);
|
|
34295
|
-
return false;
|
|
34296
34487
|
}
|
|
34297
|
-
await this.services.database.openDatabase({
|
|
34298
|
-
databaseEvents: this.services.databaseEvents,
|
|
34299
|
-
replicator: this.services.replicator
|
|
34300
|
-
});
|
|
34301
|
-
await this.core.services.appLifecycle.onLoaded();
|
|
34302
|
-
await Promise.all(this.core.addOns.map((e) => Promise.resolve(e.onload())));
|
|
34303
|
-
return true;
|
|
34304
34488
|
}
|
|
34305
|
-
|
|
34306
|
-
|
|
34307
|
-
|
|
34308
|
-
|
|
34309
|
-
services.appLifecycle.onLoad.addHandler(this._onLiveSyncLoad.bind(this));
|
|
34489
|
+
if (notes.length === 0) {
|
|
34490
|
+
log("There are no old documents");
|
|
34491
|
+
log(`Checking expired file history done`);
|
|
34492
|
+
return;
|
|
34310
34493
|
}
|
|
34311
|
-
|
|
34312
|
-
|
|
34313
|
-
|
|
34314
|
-
|
|
34315
|
-
|
|
34316
|
-
|
|
34317
|
-
|
|
34494
|
+
for (const v of notes) {
|
|
34495
|
+
log(`Deletion history expired: ${v.path}`);
|
|
34496
|
+
const delDoc = v.doc;
|
|
34497
|
+
delDoc._deleted = true;
|
|
34498
|
+
await host.services.database.localDatabase.putRaw(delDoc);
|
|
34499
|
+
}
|
|
34500
|
+
log(`Checking expired file history done`);
|
|
34318
34501
|
}
|
|
34319
|
-
function
|
|
34320
|
-
return
|
|
34502
|
+
function getPathFromEntry(host, doc) {
|
|
34503
|
+
return host.services.path.getPath(doc);
|
|
34321
34504
|
}
|
|
34322
|
-
function
|
|
34323
|
-
|
|
34324
|
-
|
|
34505
|
+
async function syncFileBetweenDBandStorage(host, log, file, doc) {
|
|
34506
|
+
const docPath = getPathFromEntry(host, doc);
|
|
34507
|
+
if (!doc) throw new Error(`Missing doc:${docPath}`);
|
|
34508
|
+
switch (host.services.path.compareFileFreshness(file, doc)) {
|
|
34509
|
+
case BASE_IS_NEW: if (!host.services.vault.isFileSizeTooLarge(file.stat.size)) {
|
|
34510
|
+
log("STORAGE -> DB :" + file.path);
|
|
34511
|
+
await host.serviceModules.fileHandler.storeFileToDB(file);
|
|
34512
|
+
return FilePairProcessResults.COMPLETED;
|
|
34513
|
+
} else {
|
|
34514
|
+
log(`STORAGE -> DB : ${file.path} has been skipped due to file size exceeding the limit`, 64);
|
|
34515
|
+
return FilePairProcessResults.SKIPPED;
|
|
34516
|
+
}
|
|
34517
|
+
case TARGET_IS_NEW: if (!host.services.vault.isFileSizeTooLarge(doc.size)) {
|
|
34518
|
+
log("STORAGE <- DB :" + docPath);
|
|
34519
|
+
if (await host.serviceModules.fileHandler.dbToStorage(doc, stripAllPrefixes(docPath), false)) {
|
|
34520
|
+
host.services.context.events.emitEvent("event-file-changed", {
|
|
34521
|
+
file: file.path,
|
|
34522
|
+
automated: true
|
|
34523
|
+
});
|
|
34524
|
+
return FilePairProcessResults.COMPLETED;
|
|
34525
|
+
} else {
|
|
34526
|
+
log(`STORAGE <- DB : Cloud not read ${file.path}, possibly deleted`, 64);
|
|
34527
|
+
return FilePairProcessResults.FAILED;
|
|
34528
|
+
}
|
|
34529
|
+
} else {
|
|
34530
|
+
log(`STORAGE <- DB : ${file.path} has been skipped due to file size exceeding the limit`, 64);
|
|
34531
|
+
return FilePairProcessResults.SKIPPED;
|
|
34532
|
+
}
|
|
34533
|
+
case EVEN:
|
|
34534
|
+
log("STORAGE == DB :" + file.path, -1);
|
|
34535
|
+
return FilePairProcessResults.COMPLETED;
|
|
34536
|
+
default:
|
|
34537
|
+
log("STORAGE ?? DB :" + file.path + " Something got weird");
|
|
34538
|
+
return FilePairProcessResults.FAILED;
|
|
34539
|
+
}
|
|
34325
34540
|
}
|
|
34326
|
-
function
|
|
34327
|
-
|
|
34541
|
+
function canProceedScan(host, errorManager, log, showingNotice = false, ignoreSuspending = false) {
|
|
34542
|
+
const settings = host.services.setting.currentSettings();
|
|
34543
|
+
const ERR_NOT_CONFIGURED = "LiveSync is not configured yet. Synchronising between the storage and the local database is now prevented.";
|
|
34544
|
+
if (!settings.isConfigured) {
|
|
34545
|
+
errorManager.showError(ERR_NOT_CONFIGURED, showingNotice ? 64 : 32);
|
|
34546
|
+
return false;
|
|
34547
|
+
}
|
|
34548
|
+
errorManager.clearError(ERR_NOT_CONFIGURED);
|
|
34549
|
+
const ERR_SUSPENDING = "Now suspending file watching. Synchronising between the storage and the local database is now prevented.";
|
|
34550
|
+
if (!ignoreSuspending && settings.suspendFileWatching) {
|
|
34551
|
+
errorManager.showError(ERR_SUSPENDING, showingNotice ? 64 : 32);
|
|
34552
|
+
return false;
|
|
34553
|
+
}
|
|
34554
|
+
errorManager.clearError(ERR_SUSPENDING);
|
|
34555
|
+
const MSG_IN_REMEDIATION = `Started in remediation Mode! (Max mtime for reflect events is set). Synchronising between the storage and the local database is now prevented.`;
|
|
34556
|
+
if (settings.maxMTimeForReflectEvents > 0) {
|
|
34557
|
+
errorManager.showError(MSG_IN_REMEDIATION, 64);
|
|
34558
|
+
return false;
|
|
34559
|
+
}
|
|
34560
|
+
errorManager.clearError(MSG_IN_REMEDIATION);
|
|
34561
|
+
return true;
|
|
34328
34562
|
}
|
|
34329
|
-
|
|
34330
|
-
|
|
34331
|
-
|
|
34332
|
-
function toDatabasePath(path) {
|
|
34333
|
-
if (path.startsWith(".")) return addPrefix(path, "i:");
|
|
34334
|
-
return path;
|
|
34563
|
+
function convertCase(settings, path) {
|
|
34564
|
+
if (settings.handleFilenameCaseSensitive) return path;
|
|
34565
|
+
return path.toLowerCase();
|
|
34335
34566
|
}
|
|
34336
|
-
async function
|
|
34337
|
-
|
|
34338
|
-
|
|
34339
|
-
|
|
34340
|
-
|
|
34341
|
-
|
|
34342
|
-
if (
|
|
34343
|
-
throw error;
|
|
34567
|
+
async function collectFilesOnStorage(host, settings, log) {
|
|
34568
|
+
log("Collecting local files on the storage", 16);
|
|
34569
|
+
const filesStorageSrc = await host.serviceModules.storageAccess.getFiles();
|
|
34570
|
+
const _filesStorage = [];
|
|
34571
|
+
for (const f of filesStorageSrc) {
|
|
34572
|
+
if (shouldBeIgnored(f.path)) continue;
|
|
34573
|
+
if (await host.services.vault.isTargetFile(f.path)) _filesStorage.push(f);
|
|
34344
34574
|
}
|
|
34345
|
-
|
|
34346
|
-
|
|
34347
|
-
const
|
|
34348
|
-
const legacy = rawStorageType === null || rawStorageType === "notes";
|
|
34349
|
-
const type = legacy ? "notes" : rawStorageType;
|
|
34350
|
-
const legacyBodyPresent = legacy && (typeof raw.data === "string" || Array.isArray(raw.data) && raw.data.every((item) => typeof item === "string"));
|
|
34575
|
+
const storageFileNameMap = Object.fromEntries(_filesStorage.map((e) => [e.path, e]));
|
|
34576
|
+
const storageFileNames = Object.keys(storageFileNameMap);
|
|
34577
|
+
const storageFileNameCapsPair = storageFileNames.map((e) => [e, convertCase(settings, e)]);
|
|
34351
34578
|
return {
|
|
34352
|
-
|
|
34353
|
-
|
|
34354
|
-
|
|
34355
|
-
_revs_info: raw._revs_info,
|
|
34356
|
-
path,
|
|
34357
|
-
data: legacyBodyPresent ? raw.data : "",
|
|
34358
|
-
ctime: raw.ctime ?? 0,
|
|
34359
|
-
mtime: raw.mtime ?? 0,
|
|
34360
|
-
size: raw.size ?? 0,
|
|
34361
|
-
children: type === "newnote" || type === "plain" ? raw.children ?? [] : [],
|
|
34362
|
-
datatype: type === "newnote" ? "newnote" : "plain",
|
|
34363
|
-
deleted: raw.deleted ?? raw._deleted,
|
|
34364
|
-
type,
|
|
34365
|
-
eden: raw.eden ?? {},
|
|
34366
|
-
_rawStorageType: rawStorageType,
|
|
34367
|
-
_legacyBodyPresent: legacyBodyPresent
|
|
34579
|
+
storageFileNameMap,
|
|
34580
|
+
storageFileNames,
|
|
34581
|
+
storageFileNameCI2CS: Object.fromEntries(storageFileNameCapsPair.map((e) => [e[1], e[0]]))
|
|
34368
34582
|
};
|
|
34369
34583
|
}
|
|
34370
|
-
async function
|
|
34371
|
-
|
|
34372
|
-
const
|
|
34373
|
-
const
|
|
34374
|
-
const
|
|
34375
|
-
|
|
34376
|
-
|
|
34377
|
-
|
|
34378
|
-
|
|
34379
|
-
|
|
34380
|
-
|
|
34381
|
-
|
|
34382
|
-
|
|
34383
|
-
|
|
34384
|
-
|
|
34584
|
+
async function collectDatabaseFiles(host, settings, log, showingNotice) {
|
|
34585
|
+
log("Collecting local files on the DB", 16);
|
|
34586
|
+
const _DBEntries = [];
|
|
34587
|
+
const unresolvedFileNamesLC = /* @__PURE__ */ new Set();
|
|
34588
|
+
const resolvableFileNamesLC = /* @__PURE__ */ new Set();
|
|
34589
|
+
let count = 0;
|
|
34590
|
+
for await (const doc of host.services.database.localDatabase.findAllNormalDocs({ conflicts: true }) || []) {
|
|
34591
|
+
count++;
|
|
34592
|
+
if (count % 25 === 0) log(`Collecting local files on the DB: ${count}`, showingNotice ? 64 : 32, "syncAll");
|
|
34593
|
+
if (!isMetaEntry(doc)) {
|
|
34594
|
+
log(`Invalid Metadata entry: ${doc._id ?? "unknown"}`, 32);
|
|
34595
|
+
continue;
|
|
34596
|
+
}
|
|
34597
|
+
const identity = await inspectMetadataDocumentIdentity(host, doc);
|
|
34598
|
+
if (identity.status === MetadataDocumentIdentityStatuses.EXCLUDED) continue;
|
|
34599
|
+
if (identity.status === MetadataDocumentIdentityStatuses.UNRESOLVED) {
|
|
34600
|
+
const { diagnostic } = identity;
|
|
34601
|
+
const unresolvedKey = convertCase(settings, stripAllPrefixes(diagnostic.declaredPath));
|
|
34602
|
+
unresolvedFileNamesLC.add(unresolvedKey);
|
|
34603
|
+
log(`Metadata identity is unresolved and will be left unchanged: ${diagnostic.declaredPath} (${diagnostic.reason})`, 32);
|
|
34604
|
+
continue;
|
|
34605
|
+
}
|
|
34606
|
+
const path = identity.declaredPath;
|
|
34607
|
+
if (host.services.vault.isValidPath(path) && !shouldBeIgnored(path) && await host.services.vault.isTargetFile(path)) {
|
|
34608
|
+
_DBEntries.push(doc);
|
|
34609
|
+
resolvableFileNamesLC.add(convertCase(settings, stripAllPrefixes(path)));
|
|
34610
|
+
}
|
|
34611
|
+
}
|
|
34612
|
+
const databaseFileNameMap = Object.fromEntries(_DBEntries.map((e) => [getPathFromEntry(host, e), e]));
|
|
34613
|
+
const databaseFileNames = Object.keys(databaseFileNameMap);
|
|
34614
|
+
const databaseFileNameCapsPair = databaseFileNames.map((e) => [e, convertCase(settings, e)]);
|
|
34385
34615
|
return {
|
|
34386
|
-
|
|
34387
|
-
|
|
34388
|
-
|
|
34389
|
-
|
|
34390
|
-
storageType: meta._rawStorageType ?? "absent",
|
|
34391
|
-
storageLayout: legacy ? "legacy-inline" : "chunked",
|
|
34392
|
-
ctime: meta.ctime,
|
|
34393
|
-
mtime: meta.mtime,
|
|
34394
|
-
recordedSize: meta.size,
|
|
34395
|
-
revisionHistory: (meta._revs_info ?? []).map(({ rev, status }) => ({
|
|
34396
|
-
revision: rev,
|
|
34397
|
-
status
|
|
34398
|
-
})),
|
|
34399
|
-
chunkReferences: children.length,
|
|
34400
|
-
uniqueChunkReferences: uniqueChildren.length,
|
|
34401
|
-
embeddedChunkReferences: children.filter((id) => embeddedChildren.has(id)).length,
|
|
34402
|
-
locallyStoredChunkReferences: children.filter((id) => localChunkStates.get(id)?.state === "available").length,
|
|
34403
|
-
contentAvailableLocally: legacy ? meta._legacyBodyPresent : uniqueChildren.every((id) => embeddedChildren.has(id) || localChunkStates.get(id)?.state === "available"),
|
|
34404
|
-
chunks: uniqueChildren.map((id) => {
|
|
34405
|
-
const localState = localChunkStates.get(id);
|
|
34406
|
-
return {
|
|
34407
|
-
id,
|
|
34408
|
-
referenceCount: referenceCounts.get(id) ?? 0,
|
|
34409
|
-
embedded: embeddedChildren.has(id),
|
|
34410
|
-
storedInLocalDatabase: localState?.state === "available",
|
|
34411
|
-
localDatabaseState: localState?.state ?? "missing",
|
|
34412
|
-
localDatabaseRevision: localState?.revision ?? null
|
|
34413
|
-
};
|
|
34414
|
-
})
|
|
34616
|
+
databaseFileNameMap,
|
|
34617
|
+
databaseFileNames,
|
|
34618
|
+
databaseFileNameCI2CS: Object.fromEntries(databaseFileNameCapsPair.map((e) => [e[1], e[0]])),
|
|
34619
|
+
quarantinedFileNamesLC: new Set([...unresolvedFileNamesLC].filter((path) => !resolvableFileNamesLC.has(path)))
|
|
34415
34620
|
};
|
|
34416
34621
|
}
|
|
34417
|
-
function
|
|
34418
|
-
|
|
34419
|
-
|
|
34420
|
-
|
|
34421
|
-
|
|
34422
|
-
|
|
34423
|
-
|
|
34424
|
-
|
|
34425
|
-
|
|
34426
|
-
|
|
34427
|
-
}
|
|
34428
|
-
|
|
34429
|
-
|
|
34622
|
+
async function updateToDatabase(host, log, logLevel, file) {
|
|
34623
|
+
if (!host.services.vault.isFileSizeTooLarge(file.stat.size)) {
|
|
34624
|
+
const path = file.path;
|
|
34625
|
+
await host.serviceModules.fileHandler.storeFileToDB(file);
|
|
34626
|
+
host.services.context.events.emitEvent("event-file-changed", {
|
|
34627
|
+
file: path,
|
|
34628
|
+
automated: true
|
|
34629
|
+
});
|
|
34630
|
+
return FilePairProcessResults.COMPLETED;
|
|
34631
|
+
} else {
|
|
34632
|
+
log(`UPDATE DATABASE: ${file.path} has been skipped due to file size exceeding the limit`, logLevel);
|
|
34633
|
+
return FilePairProcessResults.SKIPPED;
|
|
34634
|
+
}
|
|
34430
34635
|
}
|
|
34431
|
-
async function
|
|
34432
|
-
const
|
|
34433
|
-
|
|
34434
|
-
|
|
34435
|
-
|
|
34436
|
-
|
|
34437
|
-
|
|
34438
|
-
|
|
34439
|
-
|
|
34440
|
-
|
|
34441
|
-
|
|
34442
|
-
const mergeBases = [];
|
|
34443
|
-
const metadataByRevision = /* @__PURE__ */ new Map();
|
|
34444
|
-
if (currentMeta !== false && currentMeta._rev) metadataByRevision.set(currentMeta._rev, currentMeta);
|
|
34445
|
-
const getRevisionMeta = async (revision) => {
|
|
34446
|
-
const cached = metadataByRevision.get(revision);
|
|
34447
|
-
if (cached !== void 0) return cached;
|
|
34448
|
-
const meta = await getLocalDatabaseMeta(core, databasePath, {
|
|
34449
|
-
rev: revision,
|
|
34450
|
-
revs: true,
|
|
34451
|
-
revs_info: true
|
|
34636
|
+
async function updateToStorage(host, log, logLevel, w) {
|
|
34637
|
+
const path = getPathFromEntry(host, w);
|
|
34638
|
+
if (w && !(w.deleted || w._deleted)) if (!host.services.vault.isFileSizeTooLarge(w.size)) {
|
|
34639
|
+
if ((w._conflicts?.length ?? 0) > 0) {
|
|
34640
|
+
log(`UPDATE STORAGE: ${path} has conflicts. skipped (x)`, 32);
|
|
34641
|
+
return FilePairProcessResults.SKIPPED;
|
|
34642
|
+
}
|
|
34643
|
+
if (!await host.serviceModules.fileHandler.dbToStorage(path, null, true)) return FilePairProcessResults.FAILED;
|
|
34644
|
+
host.services.context.events.emitEvent("event-file-changed", {
|
|
34645
|
+
file: path,
|
|
34646
|
+
automated: true
|
|
34452
34647
|
});
|
|
34453
|
-
|
|
34454
|
-
return
|
|
34455
|
-
}
|
|
34456
|
-
|
|
34457
|
-
|
|
34458
|
-
|
|
34459
|
-
|
|
34460
|
-
|
|
34461
|
-
|
|
34462
|
-
|
|
34463
|
-
|
|
34464
|
-
|
|
34465
|
-
const sharedHistory = winnerHistory.filter(({ revision: historyRevision }) => conflictHistoryByRevision.has(historyRevision));
|
|
34466
|
-
const sharedRevision = sharedHistory[0]?.revision ?? null;
|
|
34467
|
-
const unavailableSharedRevisions = sharedHistory.filter(({ revision: historyRevision, status }) => status !== "available" || conflictHistoryByRevision.get(historyRevision) !== "available").map(({ revision: historyRevision }) => historyRevision);
|
|
34468
|
-
const sharedMeta = sharedRevision ? await getRevisionMeta(sharedRevision) : false;
|
|
34469
|
-
const sharedInfo = sharedMeta ? await collectRevisionDatabaseInfo(core, sharedMeta, false) : void 0;
|
|
34470
|
-
mergeBases.push({
|
|
34471
|
-
winnerRevision: currentMeta._rev ?? "",
|
|
34472
|
-
conflictRevision: revision,
|
|
34473
|
-
revision: sharedRevision,
|
|
34474
|
-
metadataAvailableLocally: Boolean(sharedMeta),
|
|
34475
|
-
contentAvailableLocally: sharedInfo?.contentAvailableLocally ?? false,
|
|
34476
|
-
missingChunkIds: sharedInfo ? missingChunkIds(sharedInfo) : [],
|
|
34477
|
-
unavailableSharedRevisions
|
|
34478
|
-
});
|
|
34479
|
-
} else unavailableConflictRevisions.push(revision);
|
|
34480
|
-
}
|
|
34648
|
+
log(`Check or pull from db:${path} OK`);
|
|
34649
|
+
return FilePairProcessResults.COMPLETED;
|
|
34650
|
+
} else {
|
|
34651
|
+
log(`UPDATE STORAGE: ${path} has been skipped due to file size exceeding the limit`, logLevel);
|
|
34652
|
+
return FilePairProcessResults.SKIPPED;
|
|
34653
|
+
}
|
|
34654
|
+
else if (w) {
|
|
34655
|
+
log(`Deletion history skipped: ${path}`, 16);
|
|
34656
|
+
return FilePairProcessResults.SKIPPED;
|
|
34657
|
+
} else {
|
|
34658
|
+
log(`entry not found: ${path}`);
|
|
34659
|
+
return FilePairProcessResults.FAILED;
|
|
34481
34660
|
}
|
|
34482
|
-
return {
|
|
34483
|
-
path,
|
|
34484
|
-
databasePath,
|
|
34485
|
-
storage: storageStat ? {
|
|
34486
|
-
exists: true,
|
|
34487
|
-
ctime: storageStat.ctime,
|
|
34488
|
-
mtime: storageStat.mtime,
|
|
34489
|
-
size: storageStat.size
|
|
34490
|
-
} : { exists: false },
|
|
34491
|
-
database: {
|
|
34492
|
-
source: "local database on this device",
|
|
34493
|
-
remoteQueried: false,
|
|
34494
|
-
exists: currentMeta !== false,
|
|
34495
|
-
currentRevision: currentMeta ? currentMeta._rev ?? null : null,
|
|
34496
|
-
conflictCount: conflictRevisions.length,
|
|
34497
|
-
conflictRevisions,
|
|
34498
|
-
unavailableConflictRevisions,
|
|
34499
|
-
revisions,
|
|
34500
|
-
mergeBases
|
|
34501
|
-
}
|
|
34502
|
-
};
|
|
34503
34661
|
}
|
|
34504
|
-
async function
|
|
34505
|
-
|
|
34506
|
-
|
|
34507
|
-
|
|
34508
|
-
|
|
34509
|
-
|
|
34510
|
-
|
|
34662
|
+
async function syncStorageAndDatabase(host, log, file, logLevel, doc) {
|
|
34663
|
+
if ((doc._conflicts?.length ?? 0) > 0) {
|
|
34664
|
+
log(`SYNC DATABASE AND STORAGE: ${file.path} has conflicts. skipped`, 32);
|
|
34665
|
+
return FilePairProcessResults.SKIPPED;
|
|
34666
|
+
}
|
|
34667
|
+
if (!host.services.vault.isFileSizeTooLarge(file.stat.size) && !host.services.vault.isFileSizeTooLarge(doc.size)) return await syncFileBetweenDBandStorage(host, log, file, doc);
|
|
34668
|
+
else {
|
|
34669
|
+
log(`SYNC DATABASE AND STORAGE: ${getPathFromEntry(host, doc)} has been skipped due to file size exceeding the limit`, logLevel);
|
|
34670
|
+
return FilePairProcessResults.SKIPPED;
|
|
34671
|
+
}
|
|
34511
34672
|
}
|
|
34512
|
-
|
|
34513
|
-
|
|
34514
|
-
|
|
34673
|
+
var FullScanModes = {
|
|
34674
|
+
DB_APPLY: "db-apply",
|
|
34675
|
+
NEWER_WINS: "newer-wins"
|
|
34676
|
+
};
|
|
34677
|
+
var ExtraOnRemote = {
|
|
34678
|
+
/**
|
|
34679
|
+
* Delete database entries if they are missing on storage.
|
|
34680
|
+
*/
|
|
34681
|
+
DELETE_LOCAL_MISSING: "delete-local-missing" };
|
|
34682
|
+
var ExtraOnLocal = {
|
|
34683
|
+
/**
|
|
34684
|
+
* Delete local files if they were deleted on database.
|
|
34685
|
+
*/
|
|
34686
|
+
DELETE_DB_DELETED: "delete-db-deleted",
|
|
34687
|
+
/**
|
|
34688
|
+
* Delete local files if they are missing on database or were deleted on database.
|
|
34689
|
+
*/
|
|
34690
|
+
DELETE_DB_MISSING: "delete-db-missing",
|
|
34691
|
+
/**
|
|
34692
|
+
* Merge local files to database
|
|
34693
|
+
*/
|
|
34694
|
+
APPEND_STORAGE_ONLY: "append-storage-only"
|
|
34695
|
+
};
|
|
34696
|
+
function isDeletedEntry(entry) {
|
|
34697
|
+
return entry.deleted || entry._deleted || false;
|
|
34515
34698
|
}
|
|
34516
|
-
|
|
34517
|
-
|
|
34518
|
-
|
|
34519
|
-
|
|
34520
|
-
|
|
34521
|
-
|
|
34522
|
-
|
|
34523
|
-
|
|
34524
|
-
|
|
34525
|
-
|
|
34526
|
-
|
|
34527
|
-
|
|
34528
|
-
|
|
34699
|
+
function getFilePairState(pair) {
|
|
34700
|
+
const { file, doc } = pair;
|
|
34701
|
+
if (file && doc) return isDeletedEntry(doc) ? "both-db-deleted" : "both";
|
|
34702
|
+
if (file) return "storage-only";
|
|
34703
|
+
if (doc) return isDeletedEntry(doc) ? "db-only-deleted" : "db-only";
|
|
34704
|
+
throw new Error("Corrupted file pair");
|
|
34705
|
+
}
|
|
34706
|
+
function shouldDeleteLocalWhenRemoteMissing(options) {
|
|
34707
|
+
return options.extraOnRemote === ExtraOnRemote.DELETE_LOCAL_MISSING || options.extraOnLocal === ExtraOnLocal.DELETE_DB_MISSING;
|
|
34708
|
+
}
|
|
34709
|
+
function shouldDeleteLocalWhenRemoteDeleted(options) {
|
|
34710
|
+
return options.extraOnRemote === ExtraOnRemote.DELETE_LOCAL_MISSING || options.extraOnLocal === ExtraOnLocal.DELETE_DB_DELETED || options.extraOnLocal === ExtraOnLocal.DELETE_DB_MISSING;
|
|
34711
|
+
}
|
|
34712
|
+
function resolveFilePairAction(state, options) {
|
|
34713
|
+
switch (options.mode) {
|
|
34714
|
+
case FullScanModes.DB_APPLY:
|
|
34715
|
+
switch (state) {
|
|
34716
|
+
case "both":
|
|
34717
|
+
case "db-only": return "update-storage";
|
|
34718
|
+
case "storage-only": return shouldDeleteLocalWhenRemoteMissing(options) ? "delete-local" : "skip";
|
|
34719
|
+
case "both-db-deleted": return shouldDeleteLocalWhenRemoteDeleted(options) ? "delete-local" : "skip";
|
|
34720
|
+
case "db-only-deleted": return "skip";
|
|
34529
34721
|
}
|
|
34530
|
-
|
|
34531
|
-
|
|
34532
|
-
|
|
34533
|
-
|
|
34534
|
-
|
|
34535
|
-
|
|
34536
|
-
|
|
34537
|
-
|
|
34538
|
-
|
|
34722
|
+
break;
|
|
34723
|
+
case FullScanModes.NEWER_WINS:
|
|
34724
|
+
switch (state) {
|
|
34725
|
+
case "both": return "sync-newer";
|
|
34726
|
+
case "storage-only": return shouldDeleteLocalWhenRemoteMissing(options) ? "delete-local" : "update-db";
|
|
34727
|
+
case "db-only": return "update-storage";
|
|
34728
|
+
case "both-db-deleted":
|
|
34729
|
+
if (shouldDeleteLocalWhenRemoteDeleted(options)) return "delete-local";
|
|
34730
|
+
return options.extraOnLocal === ExtraOnLocal.APPEND_STORAGE_ONLY ? "update-db" : "skip";
|
|
34731
|
+
case "db-only-deleted": return "skip";
|
|
34539
34732
|
}
|
|
34540
|
-
|
|
34541
|
-
|
|
34542
|
-
|
|
34543
|
-
|
|
34544
|
-
|
|
34545
|
-
|
|
34546
|
-
|
|
34547
|
-
|
|
34548
|
-
|
|
34549
|
-
|
|
34550
|
-
|
|
34551
|
-
|
|
34552
|
-
|
|
34553
|
-
|
|
34733
|
+
break;
|
|
34734
|
+
}
|
|
34735
|
+
return "skip";
|
|
34736
|
+
}
|
|
34737
|
+
async function processFilePair(host, log, pair, options) {
|
|
34738
|
+
const { file, doc } = pair;
|
|
34739
|
+
const canonicalPath = doc ? getPathFromEntry(host, doc) : file?.path;
|
|
34740
|
+
if (!canonicalPath) throw new Error("Corrupted file pair");
|
|
34741
|
+
const path = canonicalPath;
|
|
34742
|
+
const fileMapKey = convertCase(host.services.setting.currentSettings(), canonicalPath);
|
|
34743
|
+
if (file) updateFileMTimeInMap(host, fileMapKey, file.stat.mtime);
|
|
34744
|
+
if (doc && (doc._conflicts?.length ?? 0) > 0) {
|
|
34745
|
+
log(`SKIP ${options.mode}: ${path} has conflicts`, 32);
|
|
34746
|
+
return FilePairProcessResults.SKIPPED;
|
|
34747
|
+
}
|
|
34748
|
+
const state = getFilePairState(pair);
|
|
34749
|
+
let action = resolveFilePairAction(state, options);
|
|
34750
|
+
if (options.mode === FullScanModes.NEWER_WINS && state === "db-only" && doc) {
|
|
34751
|
+
const lastSeenMTime = getFileMTimeFromMap(fileMapKey);
|
|
34752
|
+
if (lastSeenMTime !== void 0) {
|
|
34753
|
+
const recency = compareMTime(lastSeenMTime, doc.mtime);
|
|
34754
|
+
if (recency === BASE_IS_NEW || recency === EVEN) {
|
|
34755
|
+
action = "delete-db";
|
|
34756
|
+
log(`NEWER_WINS: Treating missing local file as deletion (${path})`, 16);
|
|
34554
34757
|
}
|
|
34555
|
-
}
|
|
34556
|
-
|
|
34557
|
-
|
|
34558
|
-
|
|
34559
|
-
|
|
34560
|
-
if (
|
|
34561
|
-
|
|
34562
|
-
|
|
34758
|
+
}
|
|
34759
|
+
}
|
|
34760
|
+
try {
|
|
34761
|
+
switch (action) {
|
|
34762
|
+
case "update-db":
|
|
34763
|
+
if (!file) throw new Error(`Missing storage file for ${path}`);
|
|
34764
|
+
return await updateToDatabase(host, log, 32, file);
|
|
34765
|
+
case "update-storage":
|
|
34766
|
+
if (!doc) throw new Error(`Missing database entry for ${path}`);
|
|
34767
|
+
const updateStorageResult = await updateToStorage(host, log, 32, doc);
|
|
34768
|
+
if (updateStorageResult === FilePairProcessResults.COMPLETED) updateFileMTimeInMap(host, fileMapKey, doc.mtime);
|
|
34769
|
+
return updateStorageResult;
|
|
34770
|
+
case "sync-newer":
|
|
34771
|
+
if (!file || !doc) throw new Error(`Cannot compare freshness for ${path}`);
|
|
34772
|
+
const syncResult = await syncStorageAndDatabase(host, log, file, 32, doc);
|
|
34773
|
+
if (syncResult === FilePairProcessResults.COMPLETED) updateFileMTimeInMap(host, fileMapKey, Math.max(file.stat.mtime, doc.mtime));
|
|
34774
|
+
return syncResult;
|
|
34775
|
+
case "delete-local":
|
|
34776
|
+
if (!file) {
|
|
34777
|
+
log(`DELETE LOCAL: ${path} is already absent from storage`, 16);
|
|
34778
|
+
return FilePairProcessResults.COMPLETED;
|
|
34779
|
+
}
|
|
34780
|
+
log(`DELETE LOCAL: ${file.path}`, 32);
|
|
34781
|
+
await host.serviceModules.storageAccess.delete(file.path, true);
|
|
34782
|
+
fileMaps.delete(fileMapKey);
|
|
34783
|
+
saveFileStatus(host);
|
|
34784
|
+
return FilePairProcessResults.COMPLETED;
|
|
34785
|
+
case "delete-db":
|
|
34786
|
+
if (!doc) throw new Error(`Missing database entry for ${path}`);
|
|
34787
|
+
log(`DELETE DATABASE: ${path}`, 32);
|
|
34788
|
+
if (await host.serviceModules.fileHandler.deleteFileFromDB(stripAllPrefixes(path))) {
|
|
34789
|
+
fileMaps.delete(fileMapKey);
|
|
34790
|
+
saveFileStatus(host);
|
|
34791
|
+
return FilePairProcessResults.COMPLETED;
|
|
34563
34792
|
} else {
|
|
34564
|
-
|
|
34565
|
-
|
|
34793
|
+
log(`DELETE DATABASE did not delete ${path}; keeping last-seen record to avoid resurrecting the file`, 64);
|
|
34794
|
+
return FilePairProcessResults.FAILED;
|
|
34566
34795
|
}
|
|
34567
|
-
|
|
34568
|
-
|
|
34569
|
-
|
|
34570
|
-
}
|
|
34571
|
-
|
|
34572
|
-
|
|
34573
|
-
|
|
34574
|
-
|
|
34575
|
-
|
|
34576
|
-
|
|
34577
|
-
|
|
34578
|
-
|
|
34579
|
-
|
|
34580
|
-
|
|
34581
|
-
|
|
34582
|
-
|
|
34583
|
-
|
|
34584
|
-
|
|
34796
|
+
case "skip":
|
|
34797
|
+
log(`SKIP ${options.mode}: ${path} (${state})`, 16);
|
|
34798
|
+
return FilePairProcessResults.SKIPPED;
|
|
34799
|
+
}
|
|
34800
|
+
} catch (ex) {
|
|
34801
|
+
log(`Error processing ${path} with action ${action}`, 64);
|
|
34802
|
+
log(ex, 16);
|
|
34803
|
+
return FilePairProcessResults.FAILED;
|
|
34804
|
+
}
|
|
34805
|
+
}
|
|
34806
|
+
async function synchroniseAllFilesBetweenDBandStorage(host, log, errorManager, options) {
|
|
34807
|
+
const settings = host.services.setting.currentSettings();
|
|
34808
|
+
const showingNotice = options.showingNotice ?? false;
|
|
34809
|
+
await loadFileStatus(host);
|
|
34810
|
+
const { storageFileNameMap, storageFileNameCI2CS } = await collectFilesOnStorage(host, settings, log);
|
|
34811
|
+
const { databaseFileNameMap, databaseFileNameCI2CS, quarantinedFileNamesLC } = await collectDatabaseFiles(host, settings, log, showingNotice);
|
|
34812
|
+
const pairs = [];
|
|
34813
|
+
for (const fileNameLC of unique([...Object.keys(storageFileNameCI2CS), ...Object.keys(databaseFileNameCI2CS)])) {
|
|
34814
|
+
if (quarantinedFileNamesLC.has(fileNameLC)) continue;
|
|
34815
|
+
const fileName = fileNameLC in storageFileNameCI2CS ? storageFileNameCI2CS[fileNameLC] : void 0;
|
|
34816
|
+
const file = fileName ? storageFileNameMap[fileName] : void 0;
|
|
34817
|
+
const databaseName = fileNameLC in databaseFileNameCI2CS ? databaseFileNameCI2CS[fileNameLC] : void 0;
|
|
34818
|
+
const pair = {
|
|
34819
|
+
file,
|
|
34820
|
+
doc: databaseName ? databaseFileNameMap[databaseName] : void 0
|
|
34821
|
+
};
|
|
34822
|
+
pairs.push(pair);
|
|
34823
|
+
}
|
|
34824
|
+
log(`Total files to synchronise: ${pairs.length}`, 16, "syncAll");
|
|
34825
|
+
let completedCount = 0;
|
|
34826
|
+
let skippedCount = 0;
|
|
34827
|
+
let failedCount = 0;
|
|
34828
|
+
let processedCount = 0;
|
|
34829
|
+
for await (const { path, result } of withConcurrency(pairs, async (e) => {
|
|
34830
|
+
const path2 = e.file?.path ?? getPathFromEntry(host, e.doc);
|
|
34831
|
+
try {
|
|
34832
|
+
return {
|
|
34833
|
+
path: path2,
|
|
34834
|
+
result: await processFilePair(host, log, e, options)
|
|
34835
|
+
};
|
|
34836
|
+
} catch (ex) {
|
|
34837
|
+
log(`Error while synchronising files`, 64);
|
|
34838
|
+
log(ex, 16);
|
|
34839
|
+
return {
|
|
34840
|
+
path: path2,
|
|
34841
|
+
result: FilePairProcessResults.FAILED
|
|
34842
|
+
};
|
|
34843
|
+
}
|
|
34844
|
+
}, 10)) {
|
|
34845
|
+
processedCount++;
|
|
34846
|
+
switch (result) {
|
|
34847
|
+
case FilePairProcessResults.COMPLETED:
|
|
34848
|
+
completedCount++;
|
|
34849
|
+
break;
|
|
34850
|
+
case FilePairProcessResults.SKIPPED:
|
|
34851
|
+
skippedCount++;
|
|
34852
|
+
break;
|
|
34853
|
+
case FilePairProcessResults.FAILED:
|
|
34854
|
+
failedCount++;
|
|
34855
|
+
log(`Offline scan failed to synchronise ${path} between storage and the local database; this path remains eligible for a later scan.`, 16);
|
|
34856
|
+
break;
|
|
34857
|
+
}
|
|
34858
|
+
if (processedCount % 25 === 0) log(`Processing: ${processedCount}/${pairs.length}`, showingNotice ? 64 : 32, "syncAll");
|
|
34859
|
+
}
|
|
34860
|
+
log(`Synchronisation completed: ${processedCount} files processed (${completedCount} completed, ${skippedCount} skipped, ${failedCount} failed)`, showingNotice ? 64 : 32, "syncAll");
|
|
34861
|
+
saveFileStatus(host, true);
|
|
34862
|
+
if (failedCount === 0) return VaultScanResults.COMPLETED;
|
|
34863
|
+
return options.continueOnFileFailure === true ? VaultScanResults.COMPLETED_WITH_FILE_FAILURES : VaultScanResults.FAILED;
|
|
34864
|
+
}
|
|
34865
|
+
function normaliseFullScanOptions(showingNoticeOrOptions, ignoreSuspending = false) {
|
|
34866
|
+
if (typeof showingNoticeOrOptions === "object") return {
|
|
34867
|
+
mode: FullScanModes.NEWER_WINS,
|
|
34868
|
+
...showingNoticeOrOptions
|
|
34869
|
+
};
|
|
34870
|
+
return {
|
|
34871
|
+
mode: FullScanModes.NEWER_WINS,
|
|
34872
|
+
showingNotice: showingNoticeOrOptions ?? false,
|
|
34873
|
+
ignoreSuspending
|
|
34874
|
+
};
|
|
34875
|
+
}
|
|
34876
|
+
var fileMaps = /* @__PURE__ */ new Map();
|
|
34877
|
+
var FILE_STATUS_MAP_KEY = "fileStatusMap";
|
|
34878
|
+
var FILE_STATUS_MAP_LOCK = "offlineScanner-fileStatusMap";
|
|
34879
|
+
async function loadFileStatus(host) {
|
|
34880
|
+
await serialized(FILE_STATUS_MAP_LOCK, async () => {
|
|
34881
|
+
const kvDB = host.services.keyValueDB.kvDB;
|
|
34882
|
+
if (!kvDB?.get) {
|
|
34883
|
+
fileMaps = /* @__PURE__ */ new Map();
|
|
34884
|
+
return;
|
|
34885
|
+
}
|
|
34886
|
+
const mapItems = await kvDB.get(FILE_STATUS_MAP_KEY) || {};
|
|
34887
|
+
fileMaps = new Map(Object.entries(mapItems));
|
|
34888
|
+
});
|
|
34889
|
+
}
|
|
34890
|
+
async function _saveFileStatus(host) {
|
|
34891
|
+
await serialized(FILE_STATUS_MAP_LOCK, async () => {
|
|
34892
|
+
const kvDB = host.services.keyValueDB.kvDB;
|
|
34893
|
+
if (!kvDB?.set) return;
|
|
34894
|
+
await kvDB.set(FILE_STATUS_MAP_KEY, Object.fromEntries(fileMaps));
|
|
34895
|
+
});
|
|
34896
|
+
}
|
|
34897
|
+
var saveFileStatusTimeout = null;
|
|
34898
|
+
function saveFileStatus(host, immediate = false) {
|
|
34899
|
+
if (immediate) {
|
|
34900
|
+
if (saveFileStatusTimeout !== null) compatGlobal.clearTimeout(saveFileStatusTimeout);
|
|
34901
|
+
saveFileStatusTimeout = compatGlobal.setTimeout(() => {
|
|
34902
|
+
saveFileStatusTimeout = null;
|
|
34903
|
+
_saveFileStatus(host);
|
|
34904
|
+
}, 0);
|
|
34905
|
+
return;
|
|
34906
|
+
}
|
|
34907
|
+
if (saveFileStatusTimeout === null) saveFileStatusTimeout = compatGlobal.setTimeout(() => {
|
|
34908
|
+
saveFileStatusTimeout = null;
|
|
34909
|
+
_saveFileStatus(host);
|
|
34910
|
+
}, 1e3);
|
|
34911
|
+
}
|
|
34912
|
+
function updateFileMTimeInMap(host, key, mtime) {
|
|
34913
|
+
fileMaps.set(key, mtime);
|
|
34914
|
+
saveFileStatus(host);
|
|
34915
|
+
}
|
|
34916
|
+
function getFileMTimeFromMap(key) {
|
|
34917
|
+
return fileMaps.get(key);
|
|
34918
|
+
}
|
|
34919
|
+
async function performFullScan(host, log, errorManager, showingNoticeOrOptions = false, ignoreSuspending = false) {
|
|
34920
|
+
const options = normaliseFullScanOptions(showingNoticeOrOptions, ignoreSuspending);
|
|
34921
|
+
const showingNotice = options.showingNotice ?? false;
|
|
34922
|
+
if (!canProceedScan(host, errorManager, log, showingNotice, options.ignoreSuspending ?? false)) return false;
|
|
34923
|
+
log("Opening the key-value database", 16);
|
|
34924
|
+
const isInitialized = await host.services.keyValueDB.kvDB.get("initialized") || false;
|
|
34925
|
+
if (showingNotice) log("Initializing", 64, "syncAll");
|
|
34926
|
+
if (isInitialized) {
|
|
34927
|
+
log("Restoring storage state", 16);
|
|
34928
|
+
await host.serviceModules.storageAccess.restoreState();
|
|
34929
|
+
}
|
|
34930
|
+
log("Initialize and checking database files");
|
|
34931
|
+
log("Checking deleted files");
|
|
34932
|
+
await collectDeletedFiles(host, log);
|
|
34933
|
+
const scanResult = await synchroniseAllFilesBetweenDBandStorage(host, log, errorManager, options);
|
|
34934
|
+
log("Initialized, NOW TRACKING!");
|
|
34935
|
+
if (!isInitialized) await host.services.keyValueDB.kvDB.set("initialized", true);
|
|
34936
|
+
if (showingNotice) log("Initialize done!", 64, "syncAll");
|
|
34937
|
+
return scanResult;
|
|
34938
|
+
}
|
|
34939
|
+
//#endregion
|
|
34940
|
+
//#region ../../modules/main/ModuleLiveSyncMain.ts
|
|
34941
|
+
var ModuleLiveSyncMain = class extends AbstractModule {
|
|
34942
|
+
async _onLiveSyncReady() {
|
|
34943
|
+
if (!await this.core.services.appLifecycle.onLayoutReady()) return false;
|
|
34944
|
+
eventHub.emitEvent(EVENT_LAYOUT_READY);
|
|
34945
|
+
if (this.settings.suspendFileWatching || this.settings.suspendParseReplicationResult) {
|
|
34946
|
+
const ANSWER_KEEP = $msg("moduleLiveSyncMain.optionKeepLiveSyncDisabled");
|
|
34947
|
+
const ANSWER_RESUME = $msg("moduleLiveSyncMain.optionResumeAndRestart");
|
|
34948
|
+
const message = $msg("moduleLiveSyncMain.msgScramEnabled", {
|
|
34949
|
+
fileWatchingStatus: this.settings.suspendFileWatching ? "suspended" : "active",
|
|
34950
|
+
parseReplicationStatus: this.settings.suspendParseReplicationResult ? "suspended" : "active"
|
|
34951
|
+
});
|
|
34952
|
+
if (await this.core.confirm.askSelectStringDialogue(message, [ANSWER_KEEP, ANSWER_RESUME], {
|
|
34953
|
+
defaultAction: ANSWER_KEEP,
|
|
34954
|
+
title: $msg("moduleLiveSyncMain.titleScramEnabled")
|
|
34955
|
+
}) == ANSWER_RESUME) {
|
|
34956
|
+
this.settings.suspendFileWatching = false;
|
|
34957
|
+
this.settings.suspendParseReplicationResult = false;
|
|
34958
|
+
await this.saveSettings();
|
|
34959
|
+
this.services.appLifecycle.scheduleRestart();
|
|
34960
|
+
return false;
|
|
34585
34961
|
}
|
|
34962
|
+
}
|
|
34963
|
+
const initialisationResult = await this.services.databaseEvents.initialiseDatabase(false, false, false, true);
|
|
34964
|
+
if (initialisationResult === VaultScanResults.FAILED) {
|
|
34965
|
+
this._log($msg("Ui.Common.LocalDatabaseInitialisationFailed"), 64);
|
|
34966
|
+
return false;
|
|
34967
|
+
}
|
|
34968
|
+
if (initialisationResult === VaultScanResults.COMPLETED_WITH_FILE_FAILURES) this._log($msg("Ui.Common.SomeFilesCouldNotBeSynchronised"), 64);
|
|
34969
|
+
if (!await this.core.services.appLifecycle.onFirstInitialise()) return false;
|
|
34970
|
+
await this.services.control.applySettings();
|
|
34971
|
+
fireAndForget(async () => {
|
|
34972
|
+
this._log($msg("moduleLiveSyncMain.logAdditionalSafetyScan"), 16);
|
|
34973
|
+
if (!await this.services.appLifecycle.onScanningStartupIssues()) this._log($msg("moduleLiveSyncMain.logSafetyScanFailed"), 64);
|
|
34974
|
+
else this._log($msg("moduleLiveSyncMain.logSafetyScanCompleted"), 16);
|
|
34586
34975
|
});
|
|
34587
|
-
|
|
34588
|
-
|
|
34589
|
-
|
|
34590
|
-
|
|
34591
|
-
|
|
34592
|
-
|
|
34593
|
-
|
|
34594
|
-
|
|
34976
|
+
return true;
|
|
34977
|
+
}
|
|
34978
|
+
_wireUpEvents() {
|
|
34979
|
+
eventHub.onEvent(EVENT_SETTING_SAVED, (settings) => {
|
|
34980
|
+
fireAndForget(async () => {
|
|
34981
|
+
try {
|
|
34982
|
+
const lang = this.core.services.setting.currentSettings()?.displayLanguage;
|
|
34983
|
+
if (lang !== void 0) setLang(lang);
|
|
34984
|
+
if (this.core.services.database.isDatabaseReady()) await this.core.services.control.applySettings();
|
|
34985
|
+
eventHub.emitEvent(EVENT_REQUEST_RELOAD_SETTING_TAB);
|
|
34986
|
+
} catch (e) {
|
|
34987
|
+
this._log(`Error in Setting Save Event`, 64);
|
|
34988
|
+
this._log(e, 16);
|
|
34989
|
+
}
|
|
34990
|
+
});
|
|
34595
34991
|
});
|
|
34596
34992
|
return Promise.resolve(true);
|
|
34597
34993
|
}
|
|
34994
|
+
async _onLiveSyncLoad() {
|
|
34995
|
+
this.services.context.events;
|
|
34996
|
+
await this.services.appLifecycle.onWireUpEvents();
|
|
34997
|
+
eventHub.emitEvent(EVENT_PLUGIN_LOADED);
|
|
34998
|
+
this._log($msg("moduleLiveSyncMain.logLoadingPlugin"));
|
|
34999
|
+
if (!await this.services.appLifecycle.onInitialise()) {
|
|
35000
|
+
this._log($msg("moduleLiveSyncMain.logPluginInitCancelled"), 64);
|
|
35001
|
+
return false;
|
|
35002
|
+
}
|
|
35003
|
+
this._log($msg("moduleLiveSyncMain.logPluginVersion", {
|
|
35004
|
+
manifestVersion,
|
|
35005
|
+
packageVersion
|
|
35006
|
+
}));
|
|
35007
|
+
await this.services.setting.loadSettings();
|
|
35008
|
+
if (!await this.services.appLifecycle.onSettingLoaded()) {
|
|
35009
|
+
this._log($msg("moduleLiveSyncMain.logPluginInitCancelled"), 64);
|
|
35010
|
+
return false;
|
|
35011
|
+
}
|
|
35012
|
+
await this.services.database.openDatabase({
|
|
35013
|
+
databaseEvents: this.services.databaseEvents,
|
|
35014
|
+
replicator: this.services.replicator
|
|
35015
|
+
});
|
|
35016
|
+
await this.core.services.appLifecycle.onLoaded();
|
|
35017
|
+
await Promise.all(this.core.addOns.map((e) => Promise.resolve(e.onload())));
|
|
35018
|
+
return true;
|
|
35019
|
+
}
|
|
34598
35020
|
onBindFunction(core, services) {
|
|
34599
|
-
|
|
35021
|
+
super.onBindFunction(core, services);
|
|
35022
|
+
services.appLifecycle.onReady.addHandler(this._onLiveSyncReady.bind(this));
|
|
35023
|
+
services.appLifecycle.onWireUpEvents.addHandler(this._wireUpEvents.bind(this));
|
|
35024
|
+
services.appLifecycle.onLoad.addHandler(this._onLiveSyncLoad.bind(this));
|
|
34600
35025
|
}
|
|
34601
35026
|
};
|
|
34602
35027
|
//#endregion
|
|
34603
35028
|
//#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/serviceFeatures/prepareDatabaseForUse.js
|
|
34604
|
-
|
|
35029
|
+
function reportPreparationFailure(log, message) {
|
|
35030
|
+
log(message, 16);
|
|
35031
|
+
return false;
|
|
35032
|
+
}
|
|
35033
|
+
async function prepareDatabaseForUse(host, log, errorManager, showingNotice = false, reopenDatabase = true, ignoreSuspending = false, continueOnFileFailure = false) {
|
|
34605
35034
|
const appLifecycle = host.services.appLifecycle;
|
|
34606
35035
|
appLifecycle.resetIsReady();
|
|
34607
|
-
|
|
34608
|
-
|
|
34609
|
-
|
|
34610
|
-
|
|
34611
|
-
|
|
34612
|
-
|
|
34613
|
-
|
|
34614
|
-
|
|
34615
|
-
|
|
34616
|
-
return
|
|
35036
|
+
try {
|
|
35037
|
+
if (reopenDatabase && !await host.services.database.openDatabase({
|
|
35038
|
+
databaseEvents: host.services.databaseEvents,
|
|
35039
|
+
replicator: host.services.replicator
|
|
35040
|
+
})) return reportPreparationFailure(log, "Database preparation stopped because the local database could not be opened.");
|
|
35041
|
+
if (!host.services.database.isDatabaseReady()) return reportPreparationFailure(log, "Database preparation stopped because the local database is not ready.");
|
|
35042
|
+
const scanResult = await host.services.vault.scanVault(showingNotice, ignoreSuspending, continueOnFileFailure);
|
|
35043
|
+
if (scanResult === VaultScanResults.FAILED) return reportPreparationFailure(log, "Database preparation stopped because the Vault scan failed.");
|
|
35044
|
+
if (scanResult === VaultScanResults.COMPLETED_WITH_FILE_FAILURES && continueOnFileFailure !== true) return reportPreparationFailure(log, "Database preparation stopped because the Vault scan could not process every file.");
|
|
35045
|
+
if (!await host.services.databaseEvents.onDatabaseInitialised(showingNotice)) return reportPreparationFailure(log, "Database preparation stopped because an initialisation handler failed.");
|
|
35046
|
+
if (!await host.services.fileProcessing.commitPendingFileEvents()) return reportPreparationFailure(log, "Database preparation stopped because pending file events could not be committed.");
|
|
35047
|
+
appLifecycle.markIsReady();
|
|
35048
|
+
return scanResult;
|
|
35049
|
+
} catch (error) {
|
|
35050
|
+
log(error, 16);
|
|
35051
|
+
throw error;
|
|
34617
35052
|
}
|
|
34618
|
-
errorManager.clearError(ERR_INITIALISATION_FAILED);
|
|
34619
|
-
if (!await host.services.fileProcessing.commitPendingFileEvents()) return false;
|
|
34620
|
-
appLifecycle.markIsReady();
|
|
34621
|
-
return true;
|
|
34622
35053
|
}
|
|
34623
35054
|
function usePrepareDatabaseForUse(host) {
|
|
34624
35055
|
const log = createInstanceLogFunction("SF:prepareDatabaseForUse", host.services.API);
|
|
34625
35056
|
const errorManager = new UnresolvedErrorManager(host.services.appLifecycle, host.services.context.events);
|
|
34626
|
-
const initialiseDatabaseHandler = async (showingNotice = false, reopenDatabase = true, ignoreSuspending = false) => {
|
|
34627
|
-
return await prepareDatabaseForUse(host, log, errorManager, showingNotice, reopenDatabase, ignoreSuspending);
|
|
35057
|
+
const initialiseDatabaseHandler = async (showingNotice = false, reopenDatabase = true, ignoreSuspending = false, continueOnFileFailure = false) => {
|
|
35058
|
+
return await prepareDatabaseForUse(host, log, errorManager, showingNotice, reopenDatabase, ignoreSuspending, continueOnFileFailure);
|
|
34628
35059
|
};
|
|
34629
35060
|
host.services.databaseEvents.initialiseDatabase.addHandler(initialiseDatabaseHandler);
|
|
34630
35061
|
}
|
|
@@ -34933,7 +35364,7 @@ async function countCompromisedChunks(db) {
|
|
|
34933
35364
|
}
|
|
34934
35365
|
//#endregion
|
|
34935
35366
|
//#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/pouchdb/LiveSyncDBFunctions.js
|
|
34936
|
-
async function ensureRemoteIsCompatible(infoSrc, setting, deviceNodeID, currentVersionRange, nodeDeviceInfo, updateCallback) {
|
|
35367
|
+
async function ensureRemoteIsCompatible(infoSrc, setting, deviceNodeID, currentVersionRange, nodeDeviceInfo, updateCallback, recordTweakAssessment) {
|
|
34937
35368
|
const now = Date.now();
|
|
34938
35369
|
const baseMilestone = {
|
|
34939
35370
|
_id: MILESTONE_DOCID,
|
|
@@ -35009,14 +35440,9 @@ async function ensureRemoteIsCompatible(infoSrc, setting, deviceNodeID, currentV
|
|
|
35009
35440
|
}
|
|
35010
35441
|
if (!setting.disableCheckingConfigMismatch) {
|
|
35011
35442
|
const preferred_tweak = remoteMilestone.tweak_values?.["PREFERRED"] ?? currentTweakValues;
|
|
35012
|
-
const
|
|
35013
|
-
|
|
35014
|
-
|
|
35015
|
-
...preferred_tweak
|
|
35016
|
-
}), extractObject(TweakValuesShouldMatchedTemplate, {
|
|
35017
|
-
...TweakValuesDefault,
|
|
35018
|
-
...current_tweak
|
|
35019
|
-
}), true)) return ["MISMATCHED", preferred_tweak];
|
|
35443
|
+
const tweakAssessment = assessTweakCompatibility(currentTweakValues, preferred_tweak);
|
|
35444
|
+
recordTweakAssessment?.(tweakAssessment);
|
|
35445
|
+
if (tweakAssessment.alignment === "mismatched") return ["MISMATCHED", preferred_tweak];
|
|
35020
35446
|
}
|
|
35021
35447
|
if (remoteMilestone.locked) {
|
|
35022
35448
|
if (remoteMilestone.accepted_nodes.indexOf(deviceNodeID) == -1) {
|
|
@@ -35027,10 +35453,10 @@ async function ensureRemoteIsCompatible(infoSrc, setting, deviceNodeID, currentV
|
|
|
35027
35453
|
}
|
|
35028
35454
|
return "OK";
|
|
35029
35455
|
}
|
|
35030
|
-
async function ensureDatabaseIsCompatible(db, setting, deviceNodeID, currentVersionRange, nodeDeviceInfo) {
|
|
35456
|
+
async function ensureDatabaseIsCompatible(db, setting, deviceNodeID, currentVersionRange, nodeDeviceInfo, recordTweakAssessment) {
|
|
35031
35457
|
return await ensureRemoteIsCompatible(await resolveWithIgnoreKnownError(db.get(MILESTONE_DOCID), false), setting, deviceNodeID, currentVersionRange, nodeDeviceInfo, async (info) => {
|
|
35032
35458
|
await db.put(info);
|
|
35033
|
-
});
|
|
35459
|
+
}, recordTweakAssessment);
|
|
35034
35460
|
}
|
|
35035
35461
|
//#endregion
|
|
35036
35462
|
//#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/replication/LiveSyncAbstractReplicator.js
|
|
@@ -36215,7 +36641,10 @@ ${sendingDocs}/(${sentDocsCount} done)`, showResult ? 64 : 32, "send");
|
|
|
36215
36641
|
device_name: this.env.services.vault.getVaultName(),
|
|
36216
36642
|
progress
|
|
36217
36643
|
};
|
|
36218
|
-
|
|
36644
|
+
let tweakAssessment;
|
|
36645
|
+
const ensure = await ensureDatabaseIsCompatible(dbRet.db, setting, this.nodeid, currentVersionRange$1, info, (assessment) => {
|
|
36646
|
+
tweakAssessment = assessment;
|
|
36647
|
+
});
|
|
36219
36648
|
if (ensure == "INCOMPATIBLE") {
|
|
36220
36649
|
recordCompatibilityDecision?.(centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.INCOMPATIBLE_VERSION));
|
|
36221
36650
|
Logger("The remote database has no compatibility with the running version. Please upgrade the plugin.", 64);
|
|
@@ -36237,7 +36666,7 @@ ${sendingDocs}/(${sentDocsCount} done)`, showResult ? 64 : 32, "send");
|
|
|
36237
36666
|
return false;
|
|
36238
36667
|
}
|
|
36239
36668
|
else if (ensure == "OK") {} else if (ensure[0] == "MISMATCHED") {
|
|
36240
|
-
recordCompatibilityDecision?.(centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.TWEAK_MISMATCH, ensure[1]));
|
|
36669
|
+
recordCompatibilityDecision?.(centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.TWEAK_MISMATCH, ensure[1], tweakAssessment));
|
|
36241
36670
|
Logger(this.translate("liveSyncReplicator.mismatchedTweakDetected"), 64);
|
|
36242
36671
|
this.tweakSettingsMismatched = true;
|
|
36243
36672
|
this.preferredTweakValue = ensure[1];
|
|
@@ -55631,7 +56060,7 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
|
|
|
55631
56060
|
else this._client = new JournalSyncCore(settings, this.simpleStore, this.env, new MinioStorageAdapter(settings, this.env));
|
|
55632
56061
|
return this._client;
|
|
55633
56062
|
}
|
|
55634
|
-
async ensureBucketIsCompatible(deviceNodeID, currentVersionRange2, setting = this.currentSettings, client = this.setupJournalSyncClient(setting)) {
|
|
56063
|
+
async ensureBucketIsCompatible(deviceNodeID, currentVersionRange2, setting = this.currentSettings, client = this.setupJournalSyncClient(setting), recordTweakAssessment) {
|
|
55635
56064
|
const milestoneResult = await client.downloadJsonWithResult(MILSTONE_DOCID);
|
|
55636
56065
|
if (milestoneResult.status === JournalStorageReadStatuses.UNAVAILABLE) throw milestoneResult.error;
|
|
55637
56066
|
const downloadedMilestone = milestoneResult.status === JournalStorageReadStatuses.AVAILABLE ? milestoneResult.value : false;
|
|
@@ -55644,7 +56073,7 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
|
|
|
55644
56073
|
progress
|
|
55645
56074
|
}, async (info) => {
|
|
55646
56075
|
if (!await client.uploadJson(MILSTONE_DOCID, info)) throw new Error("Could not upload remote milestone");
|
|
55647
|
-
});
|
|
56076
|
+
}, recordTweakAssessment);
|
|
55648
56077
|
}
|
|
55649
56078
|
constructor(env) {
|
|
55650
56079
|
super(env);
|
|
@@ -55764,7 +56193,10 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
|
|
|
55764
56193
|
this.remoteLockedAndDeviceNotAccepted = false;
|
|
55765
56194
|
this.tweakSettingsMismatched = false;
|
|
55766
56195
|
this.preferredTweakValue = void 0;
|
|
55767
|
-
|
|
56196
|
+
let tweakAssessment;
|
|
56197
|
+
const ensure = await this.ensureBucketIsCompatible(this.nodeid, currentVersionRange, setting, client, (assessment) => {
|
|
56198
|
+
tweakAssessment = assessment;
|
|
56199
|
+
});
|
|
55768
56200
|
if (ensure == "INCOMPATIBLE") {
|
|
55769
56201
|
recordCompatibilityDecision?.(centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.INCOMPATIBLE_VERSION));
|
|
55770
56202
|
Logger("The remote database has no compatibility with the running version. Please upgrade the plugin.", 64);
|
|
@@ -55786,7 +56218,7 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
|
|
|
55786
56218
|
return false;
|
|
55787
56219
|
}
|
|
55788
56220
|
else if (ensure == "OK") {} else if (ensure[0] == "MISMATCHED") {
|
|
55789
|
-
recordCompatibilityDecision?.(centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.TWEAK_MISMATCH, ensure[1]));
|
|
56221
|
+
recordCompatibilityDecision?.(centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.TWEAK_MISMATCH, ensure[1], tweakAssessment));
|
|
55790
56222
|
Logger(this.translate("liveSyncReplicator.mismatchedTweakDetected"), 64);
|
|
55791
56223
|
this.tweakSettingsMismatched = true;
|
|
55792
56224
|
this.preferredTweakValue = ensure[1];
|
|
@@ -56440,6 +56872,23 @@ function createAutomaticReplicationTriggers(context) {
|
|
|
56440
56872
|
};
|
|
56441
56873
|
}
|
|
56442
56874
|
//#endregion
|
|
56875
|
+
//#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/common/utils.doc.js
|
|
56876
|
+
function isErrorOf(ex, statusCode) {
|
|
56877
|
+
if (!ex || typeof ex !== "object") throw new Error(`Expected an object error, but got ${typeof ex}`);
|
|
56878
|
+
if ("status" in ex && typeof ex.status === "number" && ex.status == statusCode) return true;
|
|
56879
|
+
return false;
|
|
56880
|
+
}
|
|
56881
|
+
function isNotFoundError(ex) {
|
|
56882
|
+
return isErrorOf(ex, 404);
|
|
56883
|
+
}
|
|
56884
|
+
function isEntryWithPath(entry) {
|
|
56885
|
+
if (!entry || typeof entry !== "object") return false;
|
|
56886
|
+
return "path" in entry && typeof entry.path === "string";
|
|
56887
|
+
}
|
|
56888
|
+
function tryGetFilePath(entry) {
|
|
56889
|
+
if (isEntryWithPath(entry)) return entry.path;
|
|
56890
|
+
}
|
|
56891
|
+
//#endregion
|
|
56443
56892
|
//#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/pouchdb/chunks.js
|
|
56444
56893
|
async function purgeUnreferencedChunks(db, dryRun, connSetting, performCompact = false) {
|
|
56445
56894
|
const info = await db.info();
|
|
@@ -56746,6 +57195,8 @@ Even if you choose to clean up, you will see this option again if you exit Obsid
|
|
|
56746
57195
|
const recovery = outcome.recoveryHint;
|
|
56747
57196
|
if (!recovery) return false;
|
|
56748
57197
|
if (recovery.reason === CENTRAL_COMPATIBILITY_REJECTION_REASONS.TWEAK_MISMATCH && recovery.preferredTweakValue) {
|
|
57198
|
+
if (!await context.services.replicator.runWithActiveReplicatorContext((activeContext) => activeContext === failedContext) || JSON.stringify(setting) !== JSON.stringify(context.services.setting.currentSettings())) return false;
|
|
57199
|
+
const assessment = recovery.tweakAssessment ?? assessTweakCompatibility(setting, recovery.preferredTweakValue);
|
|
56749
57200
|
await context.services.tweakValue.askResolvingMismatched(recovery.preferredTweakValue, async (effectiveSetting) => {
|
|
56750
57201
|
let updated = false;
|
|
56751
57202
|
await context.services.replicator.runWithActiveReplicatorContext(async (activeContext) => {
|
|
@@ -56755,7 +57206,7 @@ Even if you choose to clean up, you will see this option again if you exit Obsid
|
|
|
56755
57206
|
updated = true;
|
|
56756
57207
|
});
|
|
56757
57208
|
return updated;
|
|
56758
|
-
});
|
|
57209
|
+
}, assessment);
|
|
56759
57210
|
return false;
|
|
56760
57211
|
}
|
|
56761
57212
|
if (recovery.reason !== CENTRAL_COMPATIBILITY_REJECTION_REASONS.NODE_LOCKED && recovery.reason !== CENTRAL_COMPATIBILITY_REJECTION_REASONS.NODE_CLEANED) return false;
|
|
@@ -56856,6 +57307,11 @@ var ReplicateResultProcessor = class {
|
|
|
56856
57307
|
logError(e) {
|
|
56857
57308
|
Logger(e, 16);
|
|
56858
57309
|
}
|
|
57310
|
+
reportVaultReflectionFailure(entry, cause) {
|
|
57311
|
+
this.log(`Live replication could not reflect ${this.getPath(entry)} from the local database to the Vault; this path remains eligible for a later Vault scan.`, 16);
|
|
57312
|
+
if (cause !== void 0) this.logError(cause);
|
|
57313
|
+
Logger($msg("Ui.Common.SomeFilesCouldNotBeSynchronised"), 64);
|
|
57314
|
+
}
|
|
56859
57315
|
constructor(context) {
|
|
56860
57316
|
this.context = context;
|
|
56861
57317
|
this._suspended = false;
|
|
@@ -57157,10 +57613,16 @@ var ReplicateResultProcessor = class {
|
|
|
57157
57613
|
return;
|
|
57158
57614
|
}
|
|
57159
57615
|
if (await this.services.replication.processOptionalSynchroniseResult(dbDoc)) this.log(`Processed by other processor: ${docNote}`, -1);
|
|
57160
|
-
else if (this.services.vault.isValidPath(this.getPath(doc))) {
|
|
57161
|
-
await this.applyToStorage(doc)
|
|
57616
|
+
else if (this.services.vault.isValidPath(this.getPath(doc))) try {
|
|
57617
|
+
if (!await this.applyToStorage(doc)) {
|
|
57618
|
+
this.reportVaultReflectionFailure(doc);
|
|
57619
|
+
return;
|
|
57620
|
+
}
|
|
57162
57621
|
this.log(`Processed: ${docNote}`, -1);
|
|
57163
|
-
}
|
|
57622
|
+
} catch (error) {
|
|
57623
|
+
this.reportVaultReflectionFailure(doc, error);
|
|
57624
|
+
}
|
|
57625
|
+
else this.log(`Unprocessed (Invalid path): ${docNote}`, 16);
|
|
57164
57626
|
});
|
|
57165
57627
|
}
|
|
57166
57628
|
/**
|
|
@@ -57169,9 +57631,7 @@ var ReplicateResultProcessor = class {
|
|
|
57169
57631
|
* @returns
|
|
57170
57632
|
*/
|
|
57171
57633
|
applyToStorage(entry) {
|
|
57172
|
-
return this.withCounting(
|
|
57173
|
-
await this.services.replication.processSynchroniseResult(entry);
|
|
57174
|
-
}, this.services.replication.storageApplyingCount);
|
|
57634
|
+
return this.withCounting(() => this.services.replication.processSynchroniseResult(entry), this.services.replication.storageApplyingCount);
|
|
57175
57635
|
}
|
|
57176
57636
|
/**
|
|
57177
57637
|
* Check whether processing is required for the given document.
|
|
@@ -57260,6 +57720,7 @@ function useReplicationFeature(core) {
|
|
|
57260
57720
|
API: services.API,
|
|
57261
57721
|
appLifecycle: services.appLifecycle,
|
|
57262
57722
|
replicator: services.replicator,
|
|
57723
|
+
setting: services.setting,
|
|
57263
57724
|
tweakValue: services.tweakValue
|
|
57264
57725
|
}
|
|
57265
57726
|
});
|
|
@@ -57286,6 +57747,531 @@ function useReplicationFeature(core) {
|
|
|
57286
57747
|
services.replication.onReplicationFailed.addHandler(centralCompatibilityRecovery.handleReplicationFailure);
|
|
57287
57748
|
}
|
|
57288
57749
|
//#endregion
|
|
57750
|
+
//#region ../../serviceFeatures/conflictResolution/checker.ts
|
|
57751
|
+
/** Create conflict-checking handlers while retaining scheduling state privately. */
|
|
57752
|
+
function createConflictCheckingHandlers(dependencies) {
|
|
57753
|
+
const conflictQueue = new QueueProcessor(async (filenames) => {
|
|
57754
|
+
const filename = filenames[0];
|
|
57755
|
+
return await dependencies.conflict.resolve(filename);
|
|
57756
|
+
}, {
|
|
57757
|
+
suspended: false,
|
|
57758
|
+
batchSize: 1,
|
|
57759
|
+
concurrentLimit: 10,
|
|
57760
|
+
delay: 0,
|
|
57761
|
+
keepResultUntilDownstreamConnected: false,
|
|
57762
|
+
totalRemainingReactiveSource: dependencies.conflictProcessQueueCount
|
|
57763
|
+
}).replaceEnqueueProcessor((queue, newEntity) => {
|
|
57764
|
+
return [...[...queue].filter((entry) => entry != newEntity), newEntity];
|
|
57765
|
+
});
|
|
57766
|
+
const queueCheckForIfOpen = async (file) => {
|
|
57767
|
+
const path = file;
|
|
57768
|
+
if (dependencies.currentSettings().checkConflictOnlyOnOpen) {
|
|
57769
|
+
const activeFile = dependencies.vault.getActiveFilePath();
|
|
57770
|
+
if (activeFile && activeFile != path) {
|
|
57771
|
+
dependencies.log(`${file} is conflicted, merging process has been postponed.`, 64);
|
|
57772
|
+
return;
|
|
57773
|
+
}
|
|
57774
|
+
}
|
|
57775
|
+
await dependencies.conflict.queueCheckFor(path);
|
|
57776
|
+
};
|
|
57777
|
+
const queueCheckFor = async (file) => {
|
|
57778
|
+
const optionalConflictResult = await dependencies.conflict.getOptionalConflictCheckMethod(file);
|
|
57779
|
+
if (optionalConflictResult == true) return;
|
|
57780
|
+
else if (optionalConflictResult === "newer") await dependencies.conflict.resolveByNewest(file);
|
|
57781
|
+
else conflictQueue.enqueue(file);
|
|
57782
|
+
};
|
|
57783
|
+
const ensureAllProcessed = () => conflictQueue.waitForAllProcessed();
|
|
57784
|
+
return {
|
|
57785
|
+
queueCheckForIfOpen,
|
|
57786
|
+
queueCheckFor,
|
|
57787
|
+
ensureAllProcessed
|
|
57788
|
+
};
|
|
57789
|
+
}
|
|
57790
|
+
//#endregion
|
|
57791
|
+
//#region ../../serviceFeatures/conflictResolution/operations.ts
|
|
57792
|
+
function createConflictResolutionOperations(dependencies) {
|
|
57793
|
+
const latestResolveRequestByFilename = /* @__PURE__ */ new Map();
|
|
57794
|
+
let nextResolveRequestId = 0;
|
|
57795
|
+
const resolveByDeletingRevision = async (path, deleteRevision, subTitle = "", showNotice = true) => {
|
|
57796
|
+
const title = `Resolving ${subTitle ? `[${subTitle}]` : ""}:`;
|
|
57797
|
+
if (!await dependencies.fileHandler.deleteRevisionFromDB(path, deleteRevision)) {
|
|
57798
|
+
dependencies.log(`${title} Could not delete conflicted revision ${displayRev(deleteRevision)} of ${path}`, 64);
|
|
57799
|
+
return MISSING_OR_ERROR;
|
|
57800
|
+
}
|
|
57801
|
+
dependencies.events.emitEvent(EVENT_CONFLICT_CANCELLED, path);
|
|
57802
|
+
dependencies.log(`${title} Conflicted revision has been deleted ${displayRev(deleteRevision)} ${path}`, 32);
|
|
57803
|
+
if ((await dependencies.databaseFileAccess.getConflictedRevs(path)).length != 0) {
|
|
57804
|
+
dependencies.log(`${title} some conflicts are left in ${path}`, 32);
|
|
57805
|
+
return AUTO_MERGED;
|
|
57806
|
+
}
|
|
57807
|
+
if (isPluginMetadata(path) || isCustomisationSyncMetadata(path)) {
|
|
57808
|
+
dependencies.log(`${title} ${path} is a plugin metadata file, no need to write to storage`, 32);
|
|
57809
|
+
return AUTO_MERGED;
|
|
57810
|
+
}
|
|
57811
|
+
if (!await dependencies.fileHandler.dbToStorage(path, stripAllPrefixes(path), true)) {
|
|
57812
|
+
dependencies.log(`Could not write the resolved content to the storage: ${path}`, 64);
|
|
57813
|
+
return MISSING_OR_ERROR;
|
|
57814
|
+
}
|
|
57815
|
+
const level = subTitle.indexOf("same") !== -1 || !showNotice ? 32 : 64;
|
|
57816
|
+
dependencies.log(`${path} has been merged automatically`, level);
|
|
57817
|
+
return AUTO_MERGED;
|
|
57818
|
+
};
|
|
57819
|
+
const checkConflictAndPerformAutoMerge = async (path) => {
|
|
57820
|
+
const ret = await dependencies.localDatabase().tryAutoMerge(path, !dependencies.currentSettings().disableMarkdownAutoMerge);
|
|
57821
|
+
if ("ok" in ret) return ret.ok;
|
|
57822
|
+
if ("result" in ret) {
|
|
57823
|
+
const p = ret.result;
|
|
57824
|
+
if (!await dependencies.databaseFileAccess.storeContent(path, p)) {
|
|
57825
|
+
dependencies.log(`Merged content cannot be stored:${path}`, 64);
|
|
57826
|
+
return MISSING_OR_ERROR;
|
|
57827
|
+
}
|
|
57828
|
+
return await dependencies.conflict.resolveByDeletingRevision(path, ret.conflictedRev, "Sensible");
|
|
57829
|
+
}
|
|
57830
|
+
const { rightRev, leftLeaf, rightLeaf } = ret;
|
|
57831
|
+
if (leftLeaf == false) {
|
|
57832
|
+
dependencies.log(`could not get current revisions:${path}`, 64);
|
|
57833
|
+
return MISSING_OR_ERROR;
|
|
57834
|
+
}
|
|
57835
|
+
if (rightLeaf == false) {
|
|
57836
|
+
dependencies.log(`could not read conflicted revision ${rightRev}:${path}`, 64);
|
|
57837
|
+
return MISSING_OR_ERROR;
|
|
57838
|
+
}
|
|
57839
|
+
const isSame = leftLeaf.data == rightLeaf.data && leftLeaf.deleted == rightLeaf.deleted;
|
|
57840
|
+
const isBinary = !isPlainText(path);
|
|
57841
|
+
const alwaysNewer = dependencies.currentSettings().resolveConflictsByNewerFile;
|
|
57842
|
+
if (isSame || isBinary || alwaysNewer) {
|
|
57843
|
+
const result = compareMTime(leftLeaf.mtime, rightLeaf.mtime);
|
|
57844
|
+
let loser = leftLeaf;
|
|
57845
|
+
if (result != TARGET_IS_NEW) loser = rightLeaf;
|
|
57846
|
+
const subTitle = [
|
|
57847
|
+
`${isSame ? "same" : ""}`,
|
|
57848
|
+
`${isBinary ? "binary" : ""}`,
|
|
57849
|
+
`${alwaysNewer ? "alwaysNewer" : ""}`
|
|
57850
|
+
].filter((e) => e.trim()).join(",");
|
|
57851
|
+
return await dependencies.conflict.resolveByDeletingRevision(path, loser.rev, subTitle);
|
|
57852
|
+
}
|
|
57853
|
+
const dmp = new import_diff_match_patch.default();
|
|
57854
|
+
const diff = dmp.diff_main(leftLeaf.data, rightLeaf.data);
|
|
57855
|
+
dmp.diff_cleanupSemantic(diff);
|
|
57856
|
+
dependencies.log(`conflict(s) found:${path}`);
|
|
57857
|
+
return {
|
|
57858
|
+
left: leftLeaf,
|
|
57859
|
+
right: rightLeaf,
|
|
57860
|
+
diff
|
|
57861
|
+
};
|
|
57862
|
+
};
|
|
57863
|
+
const resolve = async (filename) => {
|
|
57864
|
+
const requestId = ++nextResolveRequestId;
|
|
57865
|
+
latestResolveRequestByFilename.set(filename, requestId);
|
|
57866
|
+
const serialisationKey = `conflict-resolve:${filename}`;
|
|
57867
|
+
if (isLockAcquired(serialisationKey)) dependencies.events.emitEvent(EVENT_CONFLICT_CANCELLED, filename);
|
|
57868
|
+
return await serialized(serialisationKey, async () => {
|
|
57869
|
+
if (latestResolveRequestByFilename.get(filename) !== requestId) return;
|
|
57870
|
+
try {
|
|
57871
|
+
const conflictCheckResult = await checkConflictAndPerformAutoMerge(filename);
|
|
57872
|
+
if (latestResolveRequestByFilename.get(filename) !== requestId) return;
|
|
57873
|
+
if (conflictCheckResult === NOT_CONFLICTED) {
|
|
57874
|
+
dependencies.events.emitEvent(EVENT_CONFLICT_CANCELLED, filename);
|
|
57875
|
+
dependencies.log(`[conflict] Not conflicted or cancelled: ${filename}`, 16);
|
|
57876
|
+
return;
|
|
57877
|
+
}
|
|
57878
|
+
if (conflictCheckResult === MISSING_OR_ERROR || conflictCheckResult === CANCELLED) {
|
|
57879
|
+
dependencies.log(`[conflict] Not conflicted or cancelled: ${filename}`, 16);
|
|
57880
|
+
return;
|
|
57881
|
+
}
|
|
57882
|
+
if (conflictCheckResult === AUTO_MERGED) {
|
|
57883
|
+
if (dependencies.currentSettings().syncAfterMerge && !dependencies.appLifecycle.isSuspended()) await dependencies.replication.replicateUnattendedByEvent({
|
|
57884
|
+
trigger: "merge",
|
|
57885
|
+
interaction: NO_INTERACTION
|
|
57886
|
+
});
|
|
57887
|
+
dependencies.log("[conflict] Automatically merged, but we have to check it again");
|
|
57888
|
+
await dependencies.conflict.queueCheckFor(filename);
|
|
57889
|
+
return;
|
|
57890
|
+
}
|
|
57891
|
+
if (dependencies.currentSettings().showMergeDialogOnlyOnActive) {
|
|
57892
|
+
const activeFile = dependencies.vault.getActiveFilePath();
|
|
57893
|
+
if (activeFile && activeFile != filename) {
|
|
57894
|
+
dependencies.log(`[conflict] ${filename} is conflicted. Merging process has been postponed to the file have got opened.`, 64);
|
|
57895
|
+
return;
|
|
57896
|
+
}
|
|
57897
|
+
}
|
|
57898
|
+
dependencies.log("[conflict] Manual merge required!");
|
|
57899
|
+
dependencies.events.emitEvent(EVENT_CONFLICT_CANCELLED, filename);
|
|
57900
|
+
await dependencies.conflict.resolveByUserInteraction(filename, conflictCheckResult);
|
|
57901
|
+
} finally {
|
|
57902
|
+
if (latestResolveRequestByFilename.get(filename) === requestId) latestResolveRequestByFilename.delete(filename);
|
|
57903
|
+
}
|
|
57904
|
+
});
|
|
57905
|
+
};
|
|
57906
|
+
const resolveByNewest = async (filename, showNotice = true) => {
|
|
57907
|
+
const currentRev = await dependencies.databaseFileAccess.fetchEntryMeta(filename, void 0, true);
|
|
57908
|
+
if (currentRev == false) {
|
|
57909
|
+
dependencies.log(`Could not get current revision of ${filename}`);
|
|
57910
|
+
return Promise.resolve(false);
|
|
57911
|
+
}
|
|
57912
|
+
const revs = await dependencies.databaseFileAccess.getConflictedRevs(filename);
|
|
57913
|
+
if (revs.length == 0) return Promise.resolve(true);
|
|
57914
|
+
const mTimeAndRev = [[currentRev.mtime, currentRev._rev], ...await Promise.all(revs.map(async (rev) => {
|
|
57915
|
+
const leaf = await dependencies.databaseFileAccess.fetchEntryMeta(filename, rev);
|
|
57916
|
+
if (leaf == false) return [0, rev];
|
|
57917
|
+
return [leaf.mtime, rev];
|
|
57918
|
+
}))].sort((a, b) => {
|
|
57919
|
+
const diff = b[0] - a[0];
|
|
57920
|
+
if (diff == 0) return a[1].localeCompare(b[1], "en", { numeric: true });
|
|
57921
|
+
return diff;
|
|
57922
|
+
});
|
|
57923
|
+
dependencies.log(`Resolving conflict by newest: ${filename} (Newest: ${new Date(mTimeAndRev[0][0]).toLocaleString()}) (${mTimeAndRev.length} revisions exists)`);
|
|
57924
|
+
for (let i = 1; i < mTimeAndRev.length; i++) {
|
|
57925
|
+
dependencies.log(`conflict: Deleting the older revision ${mTimeAndRev[i][1]} (${new Date(mTimeAndRev[i][0]).toLocaleString()}) of ${filename}`);
|
|
57926
|
+
await resolveByDeletingRevision(filename, mTimeAndRev[i][1], "NEWEST", showNotice);
|
|
57927
|
+
}
|
|
57928
|
+
return true;
|
|
57929
|
+
};
|
|
57930
|
+
const resolveAllConflictedFilesByNewerOnes = async () => {
|
|
57931
|
+
dependencies.log(`Resolving conflicts by newer ones`, 64);
|
|
57932
|
+
const files = await dependencies.storageAccess.getFileNames();
|
|
57933
|
+
let i = 0;
|
|
57934
|
+
for (const file of files) {
|
|
57935
|
+
i++;
|
|
57936
|
+
if (i % 10 === 0) dependencies.log(`Check and Processing ${i} / ${files.length}`, 64, "resolveAllConflictedFilesByNewerOnes");
|
|
57937
|
+
await resolveByNewest(file, false);
|
|
57938
|
+
}
|
|
57939
|
+
dependencies.log(`Done!`, 64, "resolveAllConflictedFilesByNewerOnes");
|
|
57940
|
+
};
|
|
57941
|
+
return {
|
|
57942
|
+
resolveByDeletingRevision,
|
|
57943
|
+
checkConflictAndPerformAutoMerge,
|
|
57944
|
+
resolve,
|
|
57945
|
+
resolveByNewest,
|
|
57946
|
+
resolveAllConflictedFilesByNewerOnes
|
|
57947
|
+
};
|
|
57948
|
+
}
|
|
57949
|
+
//#endregion
|
|
57950
|
+
//#region ../../serviceFeatures/conflictResolution/index.ts
|
|
57951
|
+
/** Compose the host-neutral conflict checker and resolver handlers. */
|
|
57952
|
+
function useConflictResolutionFeature(host) {
|
|
57953
|
+
const { services, serviceModules } = host;
|
|
57954
|
+
const log = createInstanceLogFunction("SF:ConflictResolution", services.API);
|
|
57955
|
+
const operations = createConflictResolutionOperations({
|
|
57956
|
+
events: services.context.events,
|
|
57957
|
+
databaseFileAccess: serviceModules.databaseFileAccess,
|
|
57958
|
+
fileHandler: serviceModules.fileHandler,
|
|
57959
|
+
localDatabase: () => services.database.localDatabase,
|
|
57960
|
+
conflict: services.conflict,
|
|
57961
|
+
replication: services.replication,
|
|
57962
|
+
appLifecycle: services.appLifecycle,
|
|
57963
|
+
vault: services.vault,
|
|
57964
|
+
storageAccess: serviceModules.storageAccess,
|
|
57965
|
+
currentSettings: () => services.setting.currentSettings(),
|
|
57966
|
+
log
|
|
57967
|
+
});
|
|
57968
|
+
const checking = createConflictCheckingHandlers({
|
|
57969
|
+
conflict: services.conflict,
|
|
57970
|
+
conflictProcessQueueCount: services.conflict.conflictProcessQueueCount,
|
|
57971
|
+
currentSettings: () => services.setting.currentSettings(),
|
|
57972
|
+
vault: services.vault,
|
|
57973
|
+
log
|
|
57974
|
+
});
|
|
57975
|
+
services.conflict.queueCheckForIfOpen.setHandler(checking.queueCheckForIfOpen);
|
|
57976
|
+
services.conflict.queueCheckFor.setHandler(checking.queueCheckFor);
|
|
57977
|
+
services.conflict.ensureAllProcessed.setHandler(checking.ensureAllProcessed);
|
|
57978
|
+
services.conflict.resolveByDeletingRevision.setHandler(operations.resolveByDeletingRevision);
|
|
57979
|
+
services.conflict.resolve.setHandler(operations.resolve);
|
|
57980
|
+
services.conflict.resolveByNewest.setHandler(operations.resolveByNewest);
|
|
57981
|
+
services.conflict.resolveAllConflictedFilesByNewerOnes.setHandler(operations.resolveAllConflictedFilesByNewerOnes);
|
|
57982
|
+
}
|
|
57983
|
+
//#endregion
|
|
57984
|
+
//#region ../../serviceFeatures/fileDatabaseInfo.ts
|
|
57985
|
+
var REPORT_WARNING = "All revisions and chunk availability below are a snapshot of this device's local database; the remote is not queried. Review the Vault-relative path, document identifier, content-derived chunk identifiers, and metadata before sharing this report. File contents are omitted.";
|
|
57986
|
+
function toDatabasePath(path) {
|
|
57987
|
+
if (path.startsWith(".")) return addPrefix(path, "i:");
|
|
57988
|
+
return path;
|
|
57989
|
+
}
|
|
57990
|
+
async function getLocalDatabaseMeta(core, path, options) {
|
|
57991
|
+
const documentId = await core.services.path.path2id(path);
|
|
57992
|
+
let raw;
|
|
57993
|
+
try {
|
|
57994
|
+
raw = await core.localDatabase.localDatabase.get(documentId, options);
|
|
57995
|
+
} catch (error) {
|
|
57996
|
+
if (isNotFoundError(error)) return false;
|
|
57997
|
+
throw error;
|
|
57998
|
+
}
|
|
57999
|
+
if (raw.type === "leaf") return false;
|
|
58000
|
+
if (raw.type && raw.type !== "notes" && raw.type !== "newnote" && raw.type !== "plain") return false;
|
|
58001
|
+
const rawStorageType = raw.type ?? null;
|
|
58002
|
+
const legacy = rawStorageType === null || rawStorageType === "notes";
|
|
58003
|
+
const type = legacy ? "notes" : rawStorageType;
|
|
58004
|
+
const legacyBodyPresent = legacy && (typeof raw.data === "string" || Array.isArray(raw.data) && raw.data.every((item) => typeof item === "string"));
|
|
58005
|
+
return {
|
|
58006
|
+
_id: raw._id,
|
|
58007
|
+
_rev: raw._rev,
|
|
58008
|
+
_conflicts: raw._conflicts,
|
|
58009
|
+
_revs_info: raw._revs_info,
|
|
58010
|
+
path,
|
|
58011
|
+
data: legacyBodyPresent ? raw.data : "",
|
|
58012
|
+
ctime: raw.ctime ?? 0,
|
|
58013
|
+
mtime: raw.mtime ?? 0,
|
|
58014
|
+
size: raw.size ?? 0,
|
|
58015
|
+
children: type === "newnote" || type === "plain" ? raw.children ?? [] : [],
|
|
58016
|
+
datatype: type === "newnote" ? "newnote" : "plain",
|
|
58017
|
+
deleted: raw.deleted ?? raw._deleted,
|
|
58018
|
+
type,
|
|
58019
|
+
eden: raw.eden ?? {},
|
|
58020
|
+
_rawStorageType: rawStorageType,
|
|
58021
|
+
_legacyBodyPresent: legacyBodyPresent
|
|
58022
|
+
};
|
|
58023
|
+
}
|
|
58024
|
+
async function collectRevisionDatabaseInfo(core, meta, current) {
|
|
58025
|
+
const legacy = meta._rawStorageType === null || meta._rawStorageType === "notes";
|
|
58026
|
+
const children = legacy ? [] : "children" in meta ? meta.children : [];
|
|
58027
|
+
const uniqueChildren = [...new Set(children)];
|
|
58028
|
+
const referenceCounts = /* @__PURE__ */ new Map();
|
|
58029
|
+
for (const child of children) referenceCounts.set(child, (referenceCounts.get(child) ?? 0) + 1);
|
|
58030
|
+
const embeddedChildren = new Set(Object.keys("eden" in meta && meta.eden ? meta.eden : {}).filter((id) => uniqueChildren.includes(id)));
|
|
58031
|
+
const localRows = uniqueChildren.length === 0 ? [] : (await core.localDatabase.allDocsRaw({
|
|
58032
|
+
keys: uniqueChildren,
|
|
58033
|
+
include_docs: false
|
|
58034
|
+
})).rows;
|
|
58035
|
+
const localChunkStates = new Map(localRows.filter((row) => "value" in row).map((row) => [row.key, {
|
|
58036
|
+
state: row.value.deleted ? "deleted" : "available",
|
|
58037
|
+
revision: row.value.rev
|
|
58038
|
+
}]));
|
|
58039
|
+
return {
|
|
58040
|
+
documentId: meta._id,
|
|
58041
|
+
revision: meta._rev ?? null,
|
|
58042
|
+
current,
|
|
58043
|
+
deleted: Boolean(meta.deleted ?? meta._deleted),
|
|
58044
|
+
storageType: meta._rawStorageType ?? "absent",
|
|
58045
|
+
storageLayout: legacy ? "legacy-inline" : "chunked",
|
|
58046
|
+
ctime: meta.ctime,
|
|
58047
|
+
mtime: meta.mtime,
|
|
58048
|
+
recordedSize: meta.size,
|
|
58049
|
+
revisionHistory: (meta._revs_info ?? []).map(({ rev, status }) => ({
|
|
58050
|
+
revision: rev,
|
|
58051
|
+
status
|
|
58052
|
+
})),
|
|
58053
|
+
chunkReferences: children.length,
|
|
58054
|
+
uniqueChunkReferences: uniqueChildren.length,
|
|
58055
|
+
embeddedChunkReferences: children.filter((id) => embeddedChildren.has(id)).length,
|
|
58056
|
+
locallyStoredChunkReferences: children.filter((id) => localChunkStates.get(id)?.state === "available").length,
|
|
58057
|
+
contentAvailableLocally: legacy ? meta._legacyBodyPresent : uniqueChildren.every((id) => embeddedChildren.has(id) || localChunkStates.get(id)?.state === "available"),
|
|
58058
|
+
chunks: uniqueChildren.map((id) => {
|
|
58059
|
+
const localState = localChunkStates.get(id);
|
|
58060
|
+
return {
|
|
58061
|
+
id,
|
|
58062
|
+
referenceCount: referenceCounts.get(id) ?? 0,
|
|
58063
|
+
embedded: embeddedChildren.has(id),
|
|
58064
|
+
storedInLocalDatabase: localState?.state === "available",
|
|
58065
|
+
localDatabaseState: localState?.state ?? "missing",
|
|
58066
|
+
localDatabaseRevision: localState?.revision ?? null
|
|
58067
|
+
};
|
|
58068
|
+
})
|
|
58069
|
+
};
|
|
58070
|
+
}
|
|
58071
|
+
function revisionHistory(meta) {
|
|
58072
|
+
const history = (meta._revs_info ?? []).map(({ rev, status }) => ({
|
|
58073
|
+
revision: rev,
|
|
58074
|
+
status
|
|
58075
|
+
}));
|
|
58076
|
+
if (meta._rev && !history.some(({ revision }) => revision === meta._rev)) history.unshift({
|
|
58077
|
+
revision: meta._rev,
|
|
58078
|
+
status: "available"
|
|
58079
|
+
});
|
|
58080
|
+
return history;
|
|
58081
|
+
}
|
|
58082
|
+
function missingChunkIds(info) {
|
|
58083
|
+
return info.chunks.filter(({ embedded, localDatabaseState }) => !embedded && localDatabaseState !== "available").map(({ id }) => id);
|
|
58084
|
+
}
|
|
58085
|
+
async function inspectFileDatabaseInfo(core, path) {
|
|
58086
|
+
const storageStat = await core.storageAccess.isExistsIncludeHidden(path) ? await core.storageAccess.statHidden(path) : null;
|
|
58087
|
+
const databasePath = toDatabasePath(path);
|
|
58088
|
+
const currentMeta = await getLocalDatabaseMeta(core, databasePath, {
|
|
58089
|
+
conflicts: true,
|
|
58090
|
+
revs: true,
|
|
58091
|
+
revs_info: true
|
|
58092
|
+
});
|
|
58093
|
+
const revisions = [];
|
|
58094
|
+
const conflictRevisions = currentMeta === false ? [] : currentMeta._conflicts ?? [];
|
|
58095
|
+
const unavailableConflictRevisions = [];
|
|
58096
|
+
const mergeBases = [];
|
|
58097
|
+
const metadataByRevision = /* @__PURE__ */ new Map();
|
|
58098
|
+
if (currentMeta !== false && currentMeta._rev) metadataByRevision.set(currentMeta._rev, currentMeta);
|
|
58099
|
+
const getRevisionMeta = async (revision) => {
|
|
58100
|
+
const cached = metadataByRevision.get(revision);
|
|
58101
|
+
if (cached !== void 0) return cached;
|
|
58102
|
+
const meta = await getLocalDatabaseMeta(core, databasePath, {
|
|
58103
|
+
rev: revision,
|
|
58104
|
+
revs: true,
|
|
58105
|
+
revs_info: true
|
|
58106
|
+
});
|
|
58107
|
+
metadataByRevision.set(revision, meta);
|
|
58108
|
+
return meta;
|
|
58109
|
+
};
|
|
58110
|
+
if (currentMeta) {
|
|
58111
|
+
revisions.push(await collectRevisionDatabaseInfo(core, currentMeta, true));
|
|
58112
|
+
for (const revision of conflictRevisions) {
|
|
58113
|
+
const conflictMeta = await getRevisionMeta(revision);
|
|
58114
|
+
if (conflictMeta) {
|
|
58115
|
+
revisions.push(await collectRevisionDatabaseInfo(core, conflictMeta, false));
|
|
58116
|
+
const winnerHistory = revisionHistory(currentMeta);
|
|
58117
|
+
const conflictHistory = revisionHistory(conflictMeta);
|
|
58118
|
+
const conflictHistoryByRevision = new Map(conflictHistory.map(({ revision: historyRevision, status }) => [historyRevision, status]));
|
|
58119
|
+
const sharedHistory = winnerHistory.filter(({ revision: historyRevision }) => conflictHistoryByRevision.has(historyRevision));
|
|
58120
|
+
const sharedRevision = sharedHistory[0]?.revision ?? null;
|
|
58121
|
+
const unavailableSharedRevisions = sharedHistory.filter(({ revision: historyRevision, status }) => status !== "available" || conflictHistoryByRevision.get(historyRevision) !== "available").map(({ revision: historyRevision }) => historyRevision);
|
|
58122
|
+
const sharedMeta = sharedRevision ? await getRevisionMeta(sharedRevision) : false;
|
|
58123
|
+
const sharedInfo = sharedMeta ? await collectRevisionDatabaseInfo(core, sharedMeta, false) : void 0;
|
|
58124
|
+
mergeBases.push({
|
|
58125
|
+
winnerRevision: currentMeta._rev ?? "",
|
|
58126
|
+
conflictRevision: revision,
|
|
58127
|
+
revision: sharedRevision,
|
|
58128
|
+
metadataAvailableLocally: Boolean(sharedMeta),
|
|
58129
|
+
contentAvailableLocally: sharedInfo?.contentAvailableLocally ?? false,
|
|
58130
|
+
missingChunkIds: sharedInfo ? missingChunkIds(sharedInfo) : [],
|
|
58131
|
+
unavailableSharedRevisions
|
|
58132
|
+
});
|
|
58133
|
+
} else unavailableConflictRevisions.push(revision);
|
|
58134
|
+
}
|
|
58135
|
+
}
|
|
58136
|
+
return {
|
|
58137
|
+
path,
|
|
58138
|
+
databasePath,
|
|
58139
|
+
storage: storageStat ? {
|
|
58140
|
+
exists: true,
|
|
58141
|
+
ctime: storageStat.ctime,
|
|
58142
|
+
mtime: storageStat.mtime,
|
|
58143
|
+
size: storageStat.size
|
|
58144
|
+
} : { exists: false },
|
|
58145
|
+
database: {
|
|
58146
|
+
source: "local database on this device",
|
|
58147
|
+
remoteQueried: false,
|
|
58148
|
+
exists: currentMeta !== false,
|
|
58149
|
+
currentRevision: currentMeta ? currentMeta._rev ?? null : null,
|
|
58150
|
+
conflictCount: conflictRevisions.length,
|
|
58151
|
+
conflictRevisions,
|
|
58152
|
+
unavailableConflictRevisions,
|
|
58153
|
+
revisions,
|
|
58154
|
+
mergeBases
|
|
58155
|
+
}
|
|
58156
|
+
};
|
|
58157
|
+
}
|
|
58158
|
+
async function buildFileDatabaseInfoReport(core, path) {
|
|
58159
|
+
const report = await inspectFileDatabaseInfo(core, path);
|
|
58160
|
+
return `${$msg(REPORT_WARNING)}
|
|
58161
|
+
|
|
58162
|
+
\`\`\`json
|
|
58163
|
+
${JSON.stringify(report, null, 2)}
|
|
58164
|
+
\`\`\``;
|
|
58165
|
+
}
|
|
58166
|
+
async function copyFileDatabaseInfo(core, path) {
|
|
58167
|
+
const report = await buildFileDatabaseInfoReport(core, path);
|
|
58168
|
+
return await core.services.UI.promptCopyToClipboard($msg("Database information for ${FILE}", { FILE: path }), report);
|
|
58169
|
+
}
|
|
58170
|
+
//#endregion
|
|
58171
|
+
//#region ../../serviceFeatures/basicCommands.ts
|
|
58172
|
+
function createFileDatabaseInfoCore(host) {
|
|
58173
|
+
const { services, serviceModules } = host;
|
|
58174
|
+
return {
|
|
58175
|
+
localDatabase: services.database.localDatabase,
|
|
58176
|
+
services: {
|
|
58177
|
+
path: services.path,
|
|
58178
|
+
UI: services.UI
|
|
58179
|
+
},
|
|
58180
|
+
settings: services.setting.currentSettings(),
|
|
58181
|
+
storageAccess: serviceModules.storageAccess
|
|
58182
|
+
};
|
|
58183
|
+
}
|
|
58184
|
+
/**
|
|
58185
|
+
* Register the platform-independent command palette actions.
|
|
58186
|
+
*
|
|
58187
|
+
* Registration remains tied to `onInitialise`, matching the legacy module's
|
|
58188
|
+
* timing and allowing hosts to compose the feature before the lifecycle runs.
|
|
58189
|
+
*/
|
|
58190
|
+
function useBasicCommandsFeature(host) {
|
|
58191
|
+
const { services } = host;
|
|
58192
|
+
const log = createInstanceLogFunction("SF:BasicCommands", services.API);
|
|
58193
|
+
services.appLifecycle.onInitialise.addHandler(() => {
|
|
58194
|
+
services.API.addCommand({
|
|
58195
|
+
id: "livesync-replicate",
|
|
58196
|
+
name: $msg("Sync now"),
|
|
58197
|
+
callback: async () => {
|
|
58198
|
+
await services.replication.replicateUserInitiated({
|
|
58199
|
+
trigger: "manual",
|
|
58200
|
+
progressPresentation: REPLICATION_PROGRESS_PRESENTATIONS.QUIET,
|
|
58201
|
+
interaction: USER_INITIATED_REPLICATION_AUTHORITY
|
|
58202
|
+
});
|
|
58203
|
+
}
|
|
58204
|
+
});
|
|
58205
|
+
services.API.addCommand({
|
|
58206
|
+
id: "livesync-dump",
|
|
58207
|
+
name: $msg("Copy database information for the active file"),
|
|
58208
|
+
checkCallback: (checking) => {
|
|
58209
|
+
const file = services.vault.getActiveFilePath();
|
|
58210
|
+
if (!file) return false;
|
|
58211
|
+
if (!checking) fireAndForget(() => copyFileDatabaseInfo(createFileDatabaseInfoCore(host), file));
|
|
58212
|
+
return true;
|
|
58213
|
+
}
|
|
58214
|
+
});
|
|
58215
|
+
services.API.addCommand({
|
|
58216
|
+
id: "livesync-toggle",
|
|
58217
|
+
name: "Toggle LiveSync",
|
|
58218
|
+
callback: async () => {
|
|
58219
|
+
const settings = services.setting.currentSettings();
|
|
58220
|
+
if (settings.liveSync) {
|
|
58221
|
+
settings.liveSync = false;
|
|
58222
|
+
log("LiveSync Disabled.", 64);
|
|
58223
|
+
} else {
|
|
58224
|
+
settings.liveSync = true;
|
|
58225
|
+
log("LiveSync Enabled.", 64);
|
|
58226
|
+
}
|
|
58227
|
+
await services.control.applySettings();
|
|
58228
|
+
await services.setting.saveSettingData();
|
|
58229
|
+
}
|
|
58230
|
+
});
|
|
58231
|
+
services.API.addCommand({
|
|
58232
|
+
id: "livesync-suspendall",
|
|
58233
|
+
name: "Toggle All Sync.",
|
|
58234
|
+
callback: async () => {
|
|
58235
|
+
if (services.appLifecycle.isSuspended()) {
|
|
58236
|
+
services.appLifecycle.setSuspended(false);
|
|
58237
|
+
log("Self-hosted LiveSync resumed", 64);
|
|
58238
|
+
} else {
|
|
58239
|
+
services.appLifecycle.setSuspended(true);
|
|
58240
|
+
log("Self-hosted LiveSync suspended", 64);
|
|
58241
|
+
}
|
|
58242
|
+
await services.control.applySettings();
|
|
58243
|
+
await services.setting.saveSettingData();
|
|
58244
|
+
}
|
|
58245
|
+
});
|
|
58246
|
+
services.API.addCommand({
|
|
58247
|
+
id: "livesync-scan-files",
|
|
58248
|
+
name: "Scan storage and database again",
|
|
58249
|
+
checkCallback: (checking) => {
|
|
58250
|
+
if (!services.setting.currentSettings().useAdvancedMode) return false;
|
|
58251
|
+
if (!checking) fireAndForget(() => services.vault.scanVault(true));
|
|
58252
|
+
return true;
|
|
58253
|
+
}
|
|
58254
|
+
});
|
|
58255
|
+
services.API.addCommand({
|
|
58256
|
+
id: "livesync-runbatch",
|
|
58257
|
+
name: $msg("Apply pending changes now"),
|
|
58258
|
+
callback: async () => {
|
|
58259
|
+
await services.fileProcessing.commitPendingFileEvents();
|
|
58260
|
+
}
|
|
58261
|
+
});
|
|
58262
|
+
services.API.addCommand({
|
|
58263
|
+
id: "livesync-abortsync",
|
|
58264
|
+
name: "Abort synchronization immediately",
|
|
58265
|
+
checkCallback: (checking) => {
|
|
58266
|
+
if (!services.setting.currentSettings().useAdvancedMode) return false;
|
|
58267
|
+
if (!checking) fireAndForget(() => services.replication.stopActiveTransfer());
|
|
58268
|
+
return true;
|
|
58269
|
+
}
|
|
58270
|
+
});
|
|
58271
|
+
return Promise.resolve(true);
|
|
58272
|
+
});
|
|
58273
|
+
}
|
|
58274
|
+
//#endregion
|
|
57289
58275
|
//#region ../../LiveSyncBaseCore.ts
|
|
57290
58276
|
var LiveSyncBaseCore = class {
|
|
57291
58277
|
/**
|
|
@@ -57319,6 +58305,7 @@ var LiveSyncBaseCore = class {
|
|
|
57319
58305
|
const addOns = addOnsInitialiser(this);
|
|
57320
58306
|
for (const addOn of addOns) this._registerAddOn(addOn);
|
|
57321
58307
|
useReplicationFeature(this);
|
|
58308
|
+
useBasicCommandsFeature(this);
|
|
57322
58309
|
this.bindModuleFunctions();
|
|
57323
58310
|
}
|
|
57324
58311
|
get services() {
|
|
@@ -57351,10 +58338,7 @@ var LiveSyncBaseCore = class {
|
|
|
57351
58338
|
}
|
|
57352
58339
|
registerModules(extraModules = []) {
|
|
57353
58340
|
this._registerModule(new ModuleLiveSyncMain(this));
|
|
57354
|
-
this._registerModule(new ModuleConflictChecker(this));
|
|
57355
|
-
this._registerModule(new ModuleConflictResolver(this));
|
|
57356
58341
|
this._registerModule(new ModuleResolvingMismatchedTweaks(this));
|
|
57357
|
-
this._registerModule(new ModuleBasicMenu(this));
|
|
57358
58342
|
for (const module of extraModules) this._registerModule(module);
|
|
57359
58343
|
}
|
|
57360
58344
|
/**
|
|
@@ -57459,6 +58443,7 @@ var LiveSyncBaseCore = class {
|
|
|
57459
58443
|
* (Please refer `serviceFeatures` for more details)
|
|
57460
58444
|
*/
|
|
57461
58445
|
initialiseServiceFeatures() {
|
|
58446
|
+
useConflictResolutionFeature(this);
|
|
57462
58447
|
useTargetFilters(this);
|
|
57463
58448
|
usePrepareDatabaseForUse(this);
|
|
57464
58449
|
useRemoteConfigurationMigration(this);
|
|
@@ -58745,12 +59730,15 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
|
|
|
58745
59730
|
this._log(`Rename event for ${path} has no source path`, 16);
|
|
58746
59731
|
return false;
|
|
58747
59732
|
}
|
|
58748
|
-
const
|
|
59733
|
+
const relatedPath = type === "RENAME" ? eventItem.oldPath : type === "DELETE" ? eventItem.renameTarget : void 0;
|
|
59734
|
+
const eventPaths = relatedPath === void 0 ? [path] : [path, relatedPath];
|
|
58749
59735
|
return await this.serializedByFileEventPaths(eventPaths, async () => {
|
|
58750
59736
|
switch (type) {
|
|
58751
59737
|
case "CREATE":
|
|
58752
59738
|
case "CHANGED": return await this.storeFileToDB(item.args.file);
|
|
58753
|
-
case "DELETE":
|
|
59739
|
+
case "DELETE":
|
|
59740
|
+
if (!await this.canRecordStorageDeletion(item)) return true;
|
|
59741
|
+
return await this.deleteFileFromDB(item.args.file);
|
|
58754
59742
|
case "RENAME": return await this.renameFileInDB(item.args.file, item.args.oldPath);
|
|
58755
59743
|
case "INTERNAL": return false;
|
|
58756
59744
|
default:
|
|
@@ -58759,6 +59747,39 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
|
|
|
58759
59747
|
}
|
|
58760
59748
|
});
|
|
58761
59749
|
}
|
|
59750
|
+
async canRecordStorageDeletion(item) {
|
|
59751
|
+
const path = item.args.file.path;
|
|
59752
|
+
try {
|
|
59753
|
+
const current = await this.storage.getStub(path);
|
|
59754
|
+
let excludedRenameTarget = null;
|
|
59755
|
+
if (item.args.renameTarget !== void 0) {
|
|
59756
|
+
const targetPath = item.args.renameTarget;
|
|
59757
|
+
const targetItem = await this.storage.getStub(targetPath);
|
|
59758
|
+
const target = this.getExactCurrentFile(targetItem, targetPath);
|
|
59759
|
+
if (targetItem !== null && !target) {
|
|
59760
|
+
this._log(`Preserved ${path}: the rename target no longer resolves to ${targetPath}`, 64);
|
|
59761
|
+
return false;
|
|
59762
|
+
}
|
|
59763
|
+
if (!shouldBeIgnored(targetPath) && await this.vault.isTargetFile(targetPath, { skipCaseCollisionCheck: true }) && !(target && this.vault.isFileSizeTooLarge(target.stat.size))) {
|
|
59764
|
+
this._log(`Preserved ${path}: rename target ${targetPath} is still selected`, 64);
|
|
59765
|
+
return false;
|
|
59766
|
+
}
|
|
59767
|
+
excludedRenameTarget = target;
|
|
59768
|
+
}
|
|
59769
|
+
if (current === null) return true;
|
|
59770
|
+
if (!isFolderInfo(current)) {
|
|
59771
|
+
const [currentId, deletedId] = await Promise.all([this.path.path2id(current.path), this.path.path2id(path)]);
|
|
59772
|
+
if (currentId !== deletedId) return true;
|
|
59773
|
+
if (excludedRenameTarget && this.storage.normalisePath(current.path) !== this.storage.normalisePath(path) && this.storage.normalisePath(current.path) === this.storage.normalisePath(excludedRenameTarget.path)) return true;
|
|
59774
|
+
}
|
|
59775
|
+
this._log(`Preserved ${path}: a current storage item contradicts its deletion event`, 64);
|
|
59776
|
+
return false;
|
|
59777
|
+
} catch (ex) {
|
|
59778
|
+
this._log(`Could not validate deletion of ${path}; preserved the database entry`, 64);
|
|
59779
|
+
this._log(ex, 16);
|
|
59780
|
+
return false;
|
|
59781
|
+
}
|
|
59782
|
+
}
|
|
58762
59783
|
async serializedByFileEventPaths(eventPaths, callback) {
|
|
58763
59784
|
const documentIds = await Promise.all(eventPaths.map((eventPath) => this.path.path2id(eventPath)));
|
|
58764
59785
|
return await serializedByKeys([...new Set(documentIds)].sort().map((documentId) => `processFileEvent-${documentId}`), () => callback(documentIds.length === 2 && documentIds[0] === documentIds[1]));
|
|
@@ -58779,7 +59800,8 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
|
|
|
58779
59800
|
this._log(`Rename event for ${path} has no source path`, 16);
|
|
58780
59801
|
return true;
|
|
58781
59802
|
}
|
|
58782
|
-
const
|
|
59803
|
+
const relatedPath = type === "RENAME" ? eventItem.oldPath : type === "DELETE" ? eventItem.renameTarget : void 0;
|
|
59804
|
+
const eventPaths = relatedPath === void 0 ? [path] : [path, relatedPath];
|
|
58783
59805
|
return await this.serializedByFileEventPaths(eventPaths, async (isSameDocument) => {
|
|
58784
59806
|
let action;
|
|
58785
59807
|
try {
|
|
@@ -58807,10 +59829,15 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
|
|
|
58807
59829
|
file: current
|
|
58808
59830
|
} : { kind: "none" };
|
|
58809
59831
|
}
|
|
58810
|
-
case "DELETE":
|
|
58811
|
-
|
|
58812
|
-
|
|
58813
|
-
|
|
59832
|
+
case "DELETE":
|
|
59833
|
+
if (item.args.renameTarget !== void 0) return await this.canRecordStorageDeletion(item) && await this.canApplyRestoredDeletion(path) ? {
|
|
59834
|
+
kind: "delete",
|
|
59835
|
+
path
|
|
59836
|
+
} : { kind: "none" };
|
|
59837
|
+
return await this.storage.getStub(path) === null && await this.canApplyRestoredDeletion(path) ? {
|
|
59838
|
+
kind: "delete",
|
|
59839
|
+
path
|
|
59840
|
+
} : { kind: "none" };
|
|
58814
59841
|
case "RENAME": return await this._planRestoredRename(path, item.args.oldPath, isSameDocument);
|
|
58815
59842
|
case "INTERNAL": return { kind: "none" };
|
|
58816
59843
|
default:
|
|
@@ -60198,6 +61225,7 @@ var StorageEventManagerBase = class extends StorageEventManager {
|
|
|
60198
61225
|
args: {
|
|
60199
61226
|
file,
|
|
60200
61227
|
oldPath: type === "RENAME" ? oldPath : void 0,
|
|
61228
|
+
...param.type === "RENAME" && type === "DELETE" ? { renameTarget: param.file.path } : {},
|
|
60201
61229
|
cache,
|
|
60202
61230
|
ctx
|
|
60203
61231
|
},
|
|
@@ -63575,572 +64603,6 @@ async function openP2PHost(core, p2pService) {
|
|
|
63575
64603
|
return service;
|
|
63576
64604
|
}
|
|
63577
64605
|
//#endregion
|
|
63578
|
-
//#region ../../../node_modules/octagonal-wheels/dist/iterable/map.js
|
|
63579
|
-
/**
|
|
63580
|
-
* apply a function to each element of an iterable asynchronously with a concurrency limit.
|
|
63581
|
-
* Note that the order of the elements is not guaranteed.
|
|
63582
|
-
* @param iterable An iterable items to be processed.
|
|
63583
|
-
* @param callback A function to be applied to each element of the iterable.
|
|
63584
|
-
* @param concurrency The number of concurrent processes.
|
|
63585
|
-
*/
|
|
63586
|
-
async function* withConcurrency(iterable, callback, concurrency) {
|
|
63587
|
-
const processes = /* @__PURE__ */ new Set();
|
|
63588
|
-
const mapTaskToPromise = /* @__PURE__ */ new Map();
|
|
63589
|
-
let serial = 0;
|
|
63590
|
-
const enqueue = (item) => {
|
|
63591
|
-
const idx = serial++;
|
|
63592
|
-
const promise = (async () => [idx, await callback(item)])();
|
|
63593
|
-
processes.add(promise);
|
|
63594
|
-
mapTaskToPromise.set(idx, promise);
|
|
63595
|
-
};
|
|
63596
|
-
const consume = async () => {
|
|
63597
|
-
const r = await Promise.race(processes);
|
|
63598
|
-
const item = mapTaskToPromise.get(r[0]);
|
|
63599
|
-
processes.delete(item);
|
|
63600
|
-
mapTaskToPromise.delete(r[0]);
|
|
63601
|
-
return r[1];
|
|
63602
|
-
};
|
|
63603
|
-
for await (const t of iterable) {
|
|
63604
|
-
while (processes.size >= concurrency) yield await consume();
|
|
63605
|
-
enqueue(t);
|
|
63606
|
-
}
|
|
63607
|
-
while (processes.size > 0) yield await consume();
|
|
63608
|
-
}
|
|
63609
|
-
//#endregion
|
|
63610
|
-
//#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/serviceFeatures/offlineScanner.js
|
|
63611
|
-
var FilePairProcessResults = {
|
|
63612
|
-
COMPLETED: "completed",
|
|
63613
|
-
SKIPPED: "skipped",
|
|
63614
|
-
FAILED: "failed"
|
|
63615
|
-
};
|
|
63616
|
-
var MetadataDocumentNamespaces = {
|
|
63617
|
-
NORMAL: "normal",
|
|
63618
|
-
INTERNAL: "internal",
|
|
63619
|
-
CUSTOMISATION: "customisation",
|
|
63620
|
-
PLUGIN_STORAGE: "plugin-storage"
|
|
63621
|
-
};
|
|
63622
|
-
var MetadataDocumentIdentityStatuses = {
|
|
63623
|
-
CONSISTENT: "consistent",
|
|
63624
|
-
EXCLUDED: "excluded",
|
|
63625
|
-
UNRESOLVED: "unresolved"
|
|
63626
|
-
};
|
|
63627
|
-
var OfflineScanUnresolvedReasons = {
|
|
63628
|
-
DOCUMENT_ID_MISMATCH: "document-id-mismatch",
|
|
63629
|
-
NAMESPACE_MISMATCH: "namespace-mismatch"
|
|
63630
|
-
};
|
|
63631
|
-
function getMetadataDocumentNamespace(value) {
|
|
63632
|
-
if (value.startsWith("ix:")) return MetadataDocumentNamespaces.CUSTOMISATION;
|
|
63633
|
-
if (value.startsWith("i:")) return MetadataDocumentNamespaces.INTERNAL;
|
|
63634
|
-
if (value.startsWith("ps:")) return MetadataDocumentNamespaces.PLUGIN_STORAGE;
|
|
63635
|
-
return MetadataDocumentNamespaces.NORMAL;
|
|
63636
|
-
}
|
|
63637
|
-
async function inspectMetadataDocumentIdentity(host, doc) {
|
|
63638
|
-
const actualDocumentId = doc._id;
|
|
63639
|
-
const declaredPath = getPathFromEntry(host, doc);
|
|
63640
|
-
const actualNamespace = getMetadataDocumentNamespace(actualDocumentId);
|
|
63641
|
-
const declaredPathNamespace = getMetadataDocumentNamespace(declaredPath);
|
|
63642
|
-
if (actualNamespace !== MetadataDocumentNamespaces.NORMAL || declaredPathNamespace !== MetadataDocumentNamespaces.NORMAL) {
|
|
63643
|
-
if (actualNamespace === declaredPathNamespace) return {
|
|
63644
|
-
status: MetadataDocumentIdentityStatuses.EXCLUDED,
|
|
63645
|
-
actualDocumentId,
|
|
63646
|
-
declaredPath,
|
|
63647
|
-
namespace: actualNamespace
|
|
63648
|
-
};
|
|
63649
|
-
return {
|
|
63650
|
-
status: MetadataDocumentIdentityStatuses.UNRESOLVED,
|
|
63651
|
-
diagnostic: {
|
|
63652
|
-
reason: OfflineScanUnresolvedReasons.NAMESPACE_MISMATCH,
|
|
63653
|
-
actualDocumentId,
|
|
63654
|
-
declaredPath,
|
|
63655
|
-
actualNamespace,
|
|
63656
|
-
declaredPathNamespace
|
|
63657
|
-
}
|
|
63658
|
-
};
|
|
63659
|
-
}
|
|
63660
|
-
const expectedDocumentId = await host.services.path.path2id(declaredPath);
|
|
63661
|
-
if (actualDocumentId !== expectedDocumentId) return {
|
|
63662
|
-
status: MetadataDocumentIdentityStatuses.UNRESOLVED,
|
|
63663
|
-
diagnostic: {
|
|
63664
|
-
reason: OfflineScanUnresolvedReasons.DOCUMENT_ID_MISMATCH,
|
|
63665
|
-
actualDocumentId,
|
|
63666
|
-
declaredPath,
|
|
63667
|
-
expectedDocumentId,
|
|
63668
|
-
actualNamespace,
|
|
63669
|
-
declaredPathNamespace
|
|
63670
|
-
}
|
|
63671
|
-
};
|
|
63672
|
-
return {
|
|
63673
|
-
status: MetadataDocumentIdentityStatuses.CONSISTENT,
|
|
63674
|
-
actualDocumentId,
|
|
63675
|
-
declaredPath,
|
|
63676
|
-
expectedDocumentId
|
|
63677
|
-
};
|
|
63678
|
-
}
|
|
63679
|
-
async function collectDeletedFiles(host, log) {
|
|
63680
|
-
const limitDays = host.services.setting.currentSettings().automaticallyDeleteMetadataOfDeletedFiles;
|
|
63681
|
-
if (limitDays <= 0) return;
|
|
63682
|
-
log(`Checking expired file history`);
|
|
63683
|
-
const limit = Date.now() - 86400 * 1e3 * limitDays;
|
|
63684
|
-
const notes = [];
|
|
63685
|
-
for await (const doc of host.services.database.localDatabase.findAllDocs({ conflicts: true })) if (isAnyNote(doc)) {
|
|
63686
|
-
if (doc.deleted && doc.mtime - limit < 0) {
|
|
63687
|
-
if (isMetaEntry(doc)) {
|
|
63688
|
-
const identity = await inspectMetadataDocumentIdentity(host, doc);
|
|
63689
|
-
if (identity.status === MetadataDocumentIdentityStatuses.UNRESOLVED) {
|
|
63690
|
-
log(`Expired deletion history has an unresolved Metadata identity and will be left unchanged: ${identity.diagnostic.declaredPath} (${identity.diagnostic.reason})`, 32);
|
|
63691
|
-
continue;
|
|
63692
|
-
}
|
|
63693
|
-
}
|
|
63694
|
-
notes.push({
|
|
63695
|
-
path: doc.path,
|
|
63696
|
-
mtime: doc.mtime,
|
|
63697
|
-
ttl: (doc.mtime - limit) / 1e3 / 86400,
|
|
63698
|
-
doc
|
|
63699
|
-
});
|
|
63700
|
-
}
|
|
63701
|
-
}
|
|
63702
|
-
if (notes.length === 0) {
|
|
63703
|
-
log("There are no old documents");
|
|
63704
|
-
log(`Checking expired file history done`);
|
|
63705
|
-
return;
|
|
63706
|
-
}
|
|
63707
|
-
for (const v of notes) {
|
|
63708
|
-
log(`Deletion history expired: ${v.path}`);
|
|
63709
|
-
const delDoc = v.doc;
|
|
63710
|
-
delDoc._deleted = true;
|
|
63711
|
-
await host.services.database.localDatabase.putRaw(delDoc);
|
|
63712
|
-
}
|
|
63713
|
-
log(`Checking expired file history done`);
|
|
63714
|
-
}
|
|
63715
|
-
function getPathFromEntry(host, doc) {
|
|
63716
|
-
return host.services.path.getPath(doc);
|
|
63717
|
-
}
|
|
63718
|
-
async function syncFileBetweenDBandStorage(host, log, file, doc) {
|
|
63719
|
-
const docPath = getPathFromEntry(host, doc);
|
|
63720
|
-
if (!doc) throw new Error(`Missing doc:${docPath}`);
|
|
63721
|
-
switch (host.services.path.compareFileFreshness(file, doc)) {
|
|
63722
|
-
case BASE_IS_NEW: if (!host.services.vault.isFileSizeTooLarge(file.stat.size)) {
|
|
63723
|
-
log("STORAGE -> DB :" + file.path);
|
|
63724
|
-
await host.serviceModules.fileHandler.storeFileToDB(file);
|
|
63725
|
-
return FilePairProcessResults.COMPLETED;
|
|
63726
|
-
} else {
|
|
63727
|
-
log(`STORAGE -> DB : ${file.path} has been skipped due to file size exceeding the limit`, 64);
|
|
63728
|
-
return FilePairProcessResults.SKIPPED;
|
|
63729
|
-
}
|
|
63730
|
-
case TARGET_IS_NEW: if (!host.services.vault.isFileSizeTooLarge(doc.size)) {
|
|
63731
|
-
log("STORAGE <- DB :" + docPath);
|
|
63732
|
-
if (await host.serviceModules.fileHandler.dbToStorage(doc, stripAllPrefixes(docPath), false)) {
|
|
63733
|
-
host.services.context.events.emitEvent("event-file-changed", {
|
|
63734
|
-
file: file.path,
|
|
63735
|
-
automated: true
|
|
63736
|
-
});
|
|
63737
|
-
return FilePairProcessResults.COMPLETED;
|
|
63738
|
-
} else {
|
|
63739
|
-
log(`STORAGE <- DB : Cloud not read ${file.path}, possibly deleted`, 64);
|
|
63740
|
-
return FilePairProcessResults.FAILED;
|
|
63741
|
-
}
|
|
63742
|
-
} else {
|
|
63743
|
-
log(`STORAGE <- DB : ${file.path} has been skipped due to file size exceeding the limit`, 64);
|
|
63744
|
-
return FilePairProcessResults.SKIPPED;
|
|
63745
|
-
}
|
|
63746
|
-
case EVEN:
|
|
63747
|
-
log("STORAGE == DB :" + file.path, -1);
|
|
63748
|
-
return FilePairProcessResults.COMPLETED;
|
|
63749
|
-
default:
|
|
63750
|
-
log("STORAGE ?? DB :" + file.path + " Something got weird");
|
|
63751
|
-
return FilePairProcessResults.FAILED;
|
|
63752
|
-
}
|
|
63753
|
-
}
|
|
63754
|
-
function canProceedScan(host, errorManager, log, showingNotice = false, ignoreSuspending = false) {
|
|
63755
|
-
const settings = host.services.setting.currentSettings();
|
|
63756
|
-
const ERR_NOT_CONFIGURED = "LiveSync is not configured yet. Synchronising between the storage and the local database is now prevented.";
|
|
63757
|
-
if (!settings.isConfigured) {
|
|
63758
|
-
errorManager.showError(ERR_NOT_CONFIGURED, showingNotice ? 64 : 32);
|
|
63759
|
-
return false;
|
|
63760
|
-
}
|
|
63761
|
-
errorManager.clearError(ERR_NOT_CONFIGURED);
|
|
63762
|
-
const ERR_SUSPENDING = "Now suspending file watching. Synchronising between the storage and the local database is now prevented.";
|
|
63763
|
-
if (!ignoreSuspending && settings.suspendFileWatching) {
|
|
63764
|
-
errorManager.showError(ERR_SUSPENDING, showingNotice ? 64 : 32);
|
|
63765
|
-
return false;
|
|
63766
|
-
}
|
|
63767
|
-
errorManager.clearError(ERR_SUSPENDING);
|
|
63768
|
-
const MSG_IN_REMEDIATION = `Started in remediation Mode! (Max mtime for reflect events is set). Synchronising between the storage and the local database is now prevented.`;
|
|
63769
|
-
if (settings.maxMTimeForReflectEvents > 0) {
|
|
63770
|
-
errorManager.showError(MSG_IN_REMEDIATION, 64);
|
|
63771
|
-
return false;
|
|
63772
|
-
}
|
|
63773
|
-
errorManager.clearError(MSG_IN_REMEDIATION);
|
|
63774
|
-
return true;
|
|
63775
|
-
}
|
|
63776
|
-
function convertCase(settings, path) {
|
|
63777
|
-
if (settings.handleFilenameCaseSensitive) return path;
|
|
63778
|
-
return path.toLowerCase();
|
|
63779
|
-
}
|
|
63780
|
-
async function collectFilesOnStorage(host, settings, log) {
|
|
63781
|
-
log("Collecting local files on the storage", 16);
|
|
63782
|
-
const filesStorageSrc = await host.serviceModules.storageAccess.getFiles();
|
|
63783
|
-
const _filesStorage = [];
|
|
63784
|
-
for (const f of filesStorageSrc) {
|
|
63785
|
-
if (shouldBeIgnored(f.path)) continue;
|
|
63786
|
-
if (await host.services.vault.isTargetFile(f.path)) _filesStorage.push(f);
|
|
63787
|
-
}
|
|
63788
|
-
const storageFileNameMap = Object.fromEntries(_filesStorage.map((e) => [e.path, e]));
|
|
63789
|
-
const storageFileNames = Object.keys(storageFileNameMap);
|
|
63790
|
-
const storageFileNameCapsPair = storageFileNames.map((e) => [e, convertCase(settings, e)]);
|
|
63791
|
-
return {
|
|
63792
|
-
storageFileNameMap,
|
|
63793
|
-
storageFileNames,
|
|
63794
|
-
storageFileNameCI2CS: Object.fromEntries(storageFileNameCapsPair.map((e) => [e[1], e[0]]))
|
|
63795
|
-
};
|
|
63796
|
-
}
|
|
63797
|
-
async function collectDatabaseFiles(host, settings, log, showingNotice) {
|
|
63798
|
-
log("Collecting local files on the DB", 16);
|
|
63799
|
-
const _DBEntries = [];
|
|
63800
|
-
const unresolvedFileNamesLC = /* @__PURE__ */ new Set();
|
|
63801
|
-
const resolvableFileNamesLC = /* @__PURE__ */ new Set();
|
|
63802
|
-
let count = 0;
|
|
63803
|
-
for await (const doc of host.services.database.localDatabase.findAllNormalDocs({ conflicts: true }) || []) {
|
|
63804
|
-
count++;
|
|
63805
|
-
if (count % 25 === 0) log(`Collecting local files on the DB: ${count}`, showingNotice ? 64 : 32, "syncAll");
|
|
63806
|
-
if (!isMetaEntry(doc)) {
|
|
63807
|
-
log(`Invalid Metadata entry: ${doc._id ?? "unknown"}`, 32);
|
|
63808
|
-
continue;
|
|
63809
|
-
}
|
|
63810
|
-
const identity = await inspectMetadataDocumentIdentity(host, doc);
|
|
63811
|
-
if (identity.status === MetadataDocumentIdentityStatuses.EXCLUDED) continue;
|
|
63812
|
-
if (identity.status === MetadataDocumentIdentityStatuses.UNRESOLVED) {
|
|
63813
|
-
const { diagnostic } = identity;
|
|
63814
|
-
const unresolvedKey = convertCase(settings, stripAllPrefixes(diagnostic.declaredPath));
|
|
63815
|
-
unresolvedFileNamesLC.add(unresolvedKey);
|
|
63816
|
-
log(`Metadata identity is unresolved and will be left unchanged: ${diagnostic.declaredPath} (${diagnostic.reason})`, 32);
|
|
63817
|
-
continue;
|
|
63818
|
-
}
|
|
63819
|
-
const path = identity.declaredPath;
|
|
63820
|
-
if (host.services.vault.isValidPath(path) && !shouldBeIgnored(path) && await host.services.vault.isTargetFile(path)) {
|
|
63821
|
-
_DBEntries.push(doc);
|
|
63822
|
-
resolvableFileNamesLC.add(convertCase(settings, stripAllPrefixes(path)));
|
|
63823
|
-
}
|
|
63824
|
-
}
|
|
63825
|
-
const databaseFileNameMap = Object.fromEntries(_DBEntries.map((e) => [getPathFromEntry(host, e), e]));
|
|
63826
|
-
const databaseFileNames = Object.keys(databaseFileNameMap);
|
|
63827
|
-
const databaseFileNameCapsPair = databaseFileNames.map((e) => [e, convertCase(settings, e)]);
|
|
63828
|
-
return {
|
|
63829
|
-
databaseFileNameMap,
|
|
63830
|
-
databaseFileNames,
|
|
63831
|
-
databaseFileNameCI2CS: Object.fromEntries(databaseFileNameCapsPair.map((e) => [e[1], e[0]])),
|
|
63832
|
-
quarantinedFileNamesLC: new Set([...unresolvedFileNamesLC].filter((path) => !resolvableFileNamesLC.has(path)))
|
|
63833
|
-
};
|
|
63834
|
-
}
|
|
63835
|
-
async function updateToDatabase(host, log, logLevel, file) {
|
|
63836
|
-
if (!host.services.vault.isFileSizeTooLarge(file.stat.size)) {
|
|
63837
|
-
const path = file.path;
|
|
63838
|
-
await host.serviceModules.fileHandler.storeFileToDB(file);
|
|
63839
|
-
host.services.context.events.emitEvent("event-file-changed", {
|
|
63840
|
-
file: path,
|
|
63841
|
-
automated: true
|
|
63842
|
-
});
|
|
63843
|
-
return FilePairProcessResults.COMPLETED;
|
|
63844
|
-
} else {
|
|
63845
|
-
log(`UPDATE DATABASE: ${file.path} has been skipped due to file size exceeding the limit`, logLevel);
|
|
63846
|
-
return FilePairProcessResults.SKIPPED;
|
|
63847
|
-
}
|
|
63848
|
-
}
|
|
63849
|
-
async function updateToStorage(host, log, logLevel, w) {
|
|
63850
|
-
const path = getPathFromEntry(host, w);
|
|
63851
|
-
if (w && !(w.deleted || w._deleted)) if (!host.services.vault.isFileSizeTooLarge(w.size)) {
|
|
63852
|
-
if ((w._conflicts?.length ?? 0) > 0) {
|
|
63853
|
-
log(`UPDATE STORAGE: ${path} has conflicts. skipped (x)`, 32);
|
|
63854
|
-
return FilePairProcessResults.SKIPPED;
|
|
63855
|
-
}
|
|
63856
|
-
if (!await host.serviceModules.fileHandler.dbToStorage(path, null, true)) return FilePairProcessResults.FAILED;
|
|
63857
|
-
host.services.context.events.emitEvent("event-file-changed", {
|
|
63858
|
-
file: path,
|
|
63859
|
-
automated: true
|
|
63860
|
-
});
|
|
63861
|
-
log(`Check or pull from db:${path} OK`);
|
|
63862
|
-
return FilePairProcessResults.COMPLETED;
|
|
63863
|
-
} else {
|
|
63864
|
-
log(`UPDATE STORAGE: ${path} has been skipped due to file size exceeding the limit`, logLevel);
|
|
63865
|
-
return FilePairProcessResults.SKIPPED;
|
|
63866
|
-
}
|
|
63867
|
-
else if (w) {
|
|
63868
|
-
log(`Deletion history skipped: ${path}`, 16);
|
|
63869
|
-
return FilePairProcessResults.SKIPPED;
|
|
63870
|
-
} else {
|
|
63871
|
-
log(`entry not found: ${path}`);
|
|
63872
|
-
return FilePairProcessResults.FAILED;
|
|
63873
|
-
}
|
|
63874
|
-
}
|
|
63875
|
-
async function syncStorageAndDatabase(host, log, file, logLevel, doc) {
|
|
63876
|
-
if ((doc._conflicts?.length ?? 0) > 0) {
|
|
63877
|
-
log(`SYNC DATABASE AND STORAGE: ${file.path} has conflicts. skipped`, 32);
|
|
63878
|
-
return FilePairProcessResults.SKIPPED;
|
|
63879
|
-
}
|
|
63880
|
-
if (!host.services.vault.isFileSizeTooLarge(file.stat.size) && !host.services.vault.isFileSizeTooLarge(doc.size)) return await syncFileBetweenDBandStorage(host, log, file, doc);
|
|
63881
|
-
else {
|
|
63882
|
-
log(`SYNC DATABASE AND STORAGE: ${getPathFromEntry(host, doc)} has been skipped due to file size exceeding the limit`, logLevel);
|
|
63883
|
-
return FilePairProcessResults.SKIPPED;
|
|
63884
|
-
}
|
|
63885
|
-
}
|
|
63886
|
-
var FullScanModes = {
|
|
63887
|
-
DB_APPLY: "db-apply",
|
|
63888
|
-
NEWER_WINS: "newer-wins"
|
|
63889
|
-
};
|
|
63890
|
-
var ExtraOnRemote = {
|
|
63891
|
-
/**
|
|
63892
|
-
* Delete database entries if they are missing on storage.
|
|
63893
|
-
*/
|
|
63894
|
-
DELETE_LOCAL_MISSING: "delete-local-missing" };
|
|
63895
|
-
var ExtraOnLocal = {
|
|
63896
|
-
/**
|
|
63897
|
-
* Delete local files if they were deleted on database.
|
|
63898
|
-
*/
|
|
63899
|
-
DELETE_DB_DELETED: "delete-db-deleted",
|
|
63900
|
-
/**
|
|
63901
|
-
* Delete local files if they are missing on database or were deleted on database.
|
|
63902
|
-
*/
|
|
63903
|
-
DELETE_DB_MISSING: "delete-db-missing",
|
|
63904
|
-
/**
|
|
63905
|
-
* Merge local files to database
|
|
63906
|
-
*/
|
|
63907
|
-
APPEND_STORAGE_ONLY: "append-storage-only"
|
|
63908
|
-
};
|
|
63909
|
-
function isDeletedEntry(entry) {
|
|
63910
|
-
return entry.deleted || entry._deleted || false;
|
|
63911
|
-
}
|
|
63912
|
-
function getFilePairState(pair) {
|
|
63913
|
-
const { file, doc } = pair;
|
|
63914
|
-
if (file && doc) return isDeletedEntry(doc) ? "both-db-deleted" : "both";
|
|
63915
|
-
if (file) return "storage-only";
|
|
63916
|
-
if (doc) return isDeletedEntry(doc) ? "db-only-deleted" : "db-only";
|
|
63917
|
-
throw new Error("Corrupted file pair");
|
|
63918
|
-
}
|
|
63919
|
-
function shouldDeleteLocalWhenRemoteMissing(options) {
|
|
63920
|
-
return options.extraOnRemote === ExtraOnRemote.DELETE_LOCAL_MISSING || options.extraOnLocal === ExtraOnLocal.DELETE_DB_MISSING;
|
|
63921
|
-
}
|
|
63922
|
-
function shouldDeleteLocalWhenRemoteDeleted(options) {
|
|
63923
|
-
return options.extraOnRemote === ExtraOnRemote.DELETE_LOCAL_MISSING || options.extraOnLocal === ExtraOnLocal.DELETE_DB_DELETED || options.extraOnLocal === ExtraOnLocal.DELETE_DB_MISSING;
|
|
63924
|
-
}
|
|
63925
|
-
function resolveFilePairAction(state, options) {
|
|
63926
|
-
switch (options.mode) {
|
|
63927
|
-
case FullScanModes.DB_APPLY:
|
|
63928
|
-
switch (state) {
|
|
63929
|
-
case "both":
|
|
63930
|
-
case "db-only": return "update-storage";
|
|
63931
|
-
case "storage-only": return shouldDeleteLocalWhenRemoteMissing(options) ? "delete-local" : "skip";
|
|
63932
|
-
case "both-db-deleted": return shouldDeleteLocalWhenRemoteDeleted(options) ? "delete-local" : "skip";
|
|
63933
|
-
case "db-only-deleted": return "skip";
|
|
63934
|
-
}
|
|
63935
|
-
break;
|
|
63936
|
-
case FullScanModes.NEWER_WINS:
|
|
63937
|
-
switch (state) {
|
|
63938
|
-
case "both": return "sync-newer";
|
|
63939
|
-
case "storage-only": return shouldDeleteLocalWhenRemoteMissing(options) ? "delete-local" : "update-db";
|
|
63940
|
-
case "db-only": return "update-storage";
|
|
63941
|
-
case "both-db-deleted":
|
|
63942
|
-
if (shouldDeleteLocalWhenRemoteDeleted(options)) return "delete-local";
|
|
63943
|
-
return options.extraOnLocal === ExtraOnLocal.APPEND_STORAGE_ONLY ? "update-db" : "skip";
|
|
63944
|
-
case "db-only-deleted": return "skip";
|
|
63945
|
-
}
|
|
63946
|
-
break;
|
|
63947
|
-
}
|
|
63948
|
-
return "skip";
|
|
63949
|
-
}
|
|
63950
|
-
async function processFilePair(host, log, pair, options) {
|
|
63951
|
-
const { file, doc } = pair;
|
|
63952
|
-
const canonicalPath = doc ? getPathFromEntry(host, doc) : file?.path;
|
|
63953
|
-
if (!canonicalPath) throw new Error("Corrupted file pair");
|
|
63954
|
-
const path = canonicalPath;
|
|
63955
|
-
const fileMapKey = convertCase(host.services.setting.currentSettings(), canonicalPath);
|
|
63956
|
-
if (file) updateFileMTimeInMap(host, fileMapKey, file.stat.mtime);
|
|
63957
|
-
if (doc && (doc._conflicts?.length ?? 0) > 0) {
|
|
63958
|
-
log(`SKIP ${options.mode}: ${path} has conflicts`, 32);
|
|
63959
|
-
return FilePairProcessResults.SKIPPED;
|
|
63960
|
-
}
|
|
63961
|
-
const state = getFilePairState(pair);
|
|
63962
|
-
let action = resolveFilePairAction(state, options);
|
|
63963
|
-
if (options.mode === FullScanModes.NEWER_WINS && state === "db-only" && doc) {
|
|
63964
|
-
const lastSeenMTime = getFileMTimeFromMap(fileMapKey);
|
|
63965
|
-
if (lastSeenMTime !== void 0) {
|
|
63966
|
-
const recency = compareMTime(lastSeenMTime, doc.mtime);
|
|
63967
|
-
if (recency === BASE_IS_NEW || recency === EVEN) {
|
|
63968
|
-
action = "delete-db";
|
|
63969
|
-
log(`NEWER_WINS: Treating missing local file as deletion (${path})`, 16);
|
|
63970
|
-
}
|
|
63971
|
-
}
|
|
63972
|
-
}
|
|
63973
|
-
try {
|
|
63974
|
-
switch (action) {
|
|
63975
|
-
case "update-db":
|
|
63976
|
-
if (!file) throw new Error(`Missing storage file for ${path}`);
|
|
63977
|
-
return await updateToDatabase(host, log, 32, file);
|
|
63978
|
-
case "update-storage":
|
|
63979
|
-
if (!doc) throw new Error(`Missing database entry for ${path}`);
|
|
63980
|
-
const updateStorageResult = await updateToStorage(host, log, 32, doc);
|
|
63981
|
-
if (updateStorageResult === FilePairProcessResults.COMPLETED) updateFileMTimeInMap(host, fileMapKey, doc.mtime);
|
|
63982
|
-
return updateStorageResult;
|
|
63983
|
-
case "sync-newer":
|
|
63984
|
-
if (!file || !doc) throw new Error(`Cannot compare freshness for ${path}`);
|
|
63985
|
-
const syncResult = await syncStorageAndDatabase(host, log, file, 32, doc);
|
|
63986
|
-
if (syncResult === FilePairProcessResults.COMPLETED) updateFileMTimeInMap(host, fileMapKey, Math.max(file.stat.mtime, doc.mtime));
|
|
63987
|
-
return syncResult;
|
|
63988
|
-
case "delete-local":
|
|
63989
|
-
if (!file) {
|
|
63990
|
-
log(`DELETE LOCAL: ${path} is already absent from storage`, 16);
|
|
63991
|
-
return FilePairProcessResults.COMPLETED;
|
|
63992
|
-
}
|
|
63993
|
-
log(`DELETE LOCAL: ${file.path}`, 32);
|
|
63994
|
-
await host.serviceModules.storageAccess.delete(file.path, true);
|
|
63995
|
-
fileMaps.delete(fileMapKey);
|
|
63996
|
-
saveFileStatus(host);
|
|
63997
|
-
return FilePairProcessResults.COMPLETED;
|
|
63998
|
-
case "delete-db":
|
|
63999
|
-
if (!doc) throw new Error(`Missing database entry for ${path}`);
|
|
64000
|
-
log(`DELETE DATABASE: ${path}`, 32);
|
|
64001
|
-
if (await host.serviceModules.fileHandler.deleteFileFromDB(stripAllPrefixes(path))) {
|
|
64002
|
-
fileMaps.delete(fileMapKey);
|
|
64003
|
-
saveFileStatus(host);
|
|
64004
|
-
return FilePairProcessResults.COMPLETED;
|
|
64005
|
-
} else {
|
|
64006
|
-
log(`DELETE DATABASE did not delete ${path}; keeping last-seen record to avoid resurrecting the file`, 64);
|
|
64007
|
-
return FilePairProcessResults.FAILED;
|
|
64008
|
-
}
|
|
64009
|
-
case "skip":
|
|
64010
|
-
log(`SKIP ${options.mode}: ${path} (${state})`, 16);
|
|
64011
|
-
return FilePairProcessResults.SKIPPED;
|
|
64012
|
-
}
|
|
64013
|
-
} catch (ex) {
|
|
64014
|
-
log(`Error processing ${path} with action ${action}`, 64);
|
|
64015
|
-
log(ex, 16);
|
|
64016
|
-
return FilePairProcessResults.FAILED;
|
|
64017
|
-
}
|
|
64018
|
-
}
|
|
64019
|
-
async function synchroniseAllFilesBetweenDBandStorage(host, log, errorManager, options) {
|
|
64020
|
-
const settings = host.services.setting.currentSettings();
|
|
64021
|
-
const showingNotice = options.showingNotice ?? false;
|
|
64022
|
-
await loadFileStatus(host);
|
|
64023
|
-
const { storageFileNameMap, storageFileNameCI2CS } = await collectFilesOnStorage(host, settings, log);
|
|
64024
|
-
const { databaseFileNameMap, databaseFileNameCI2CS, quarantinedFileNamesLC } = await collectDatabaseFiles(host, settings, log, showingNotice);
|
|
64025
|
-
const pairs = [];
|
|
64026
|
-
for (const fileNameLC of unique([...Object.keys(storageFileNameCI2CS), ...Object.keys(databaseFileNameCI2CS)])) {
|
|
64027
|
-
if (quarantinedFileNamesLC.has(fileNameLC)) continue;
|
|
64028
|
-
const fileName = fileNameLC in storageFileNameCI2CS ? storageFileNameCI2CS[fileNameLC] : void 0;
|
|
64029
|
-
const file = fileName ? storageFileNameMap[fileName] : void 0;
|
|
64030
|
-
const databaseName = fileNameLC in databaseFileNameCI2CS ? databaseFileNameCI2CS[fileNameLC] : void 0;
|
|
64031
|
-
const pair = {
|
|
64032
|
-
file,
|
|
64033
|
-
doc: databaseName ? databaseFileNameMap[databaseName] : void 0
|
|
64034
|
-
};
|
|
64035
|
-
pairs.push(pair);
|
|
64036
|
-
}
|
|
64037
|
-
log(`Total files to synchronise: ${pairs.length}`, 16, "syncAll");
|
|
64038
|
-
let completedCount = 0;
|
|
64039
|
-
let skippedCount = 0;
|
|
64040
|
-
let failedCount = 0;
|
|
64041
|
-
let processedCount = 0;
|
|
64042
|
-
for await (const result of withConcurrency(pairs, async (e) => {
|
|
64043
|
-
try {
|
|
64044
|
-
return await processFilePair(host, log, e, options);
|
|
64045
|
-
} catch (ex) {
|
|
64046
|
-
log(`Error while synchronising files`, 64);
|
|
64047
|
-
log(ex, 16);
|
|
64048
|
-
return FilePairProcessResults.FAILED;
|
|
64049
|
-
}
|
|
64050
|
-
}, 10)) {
|
|
64051
|
-
processedCount++;
|
|
64052
|
-
switch (result) {
|
|
64053
|
-
case FilePairProcessResults.COMPLETED:
|
|
64054
|
-
completedCount++;
|
|
64055
|
-
break;
|
|
64056
|
-
case FilePairProcessResults.SKIPPED:
|
|
64057
|
-
skippedCount++;
|
|
64058
|
-
break;
|
|
64059
|
-
case FilePairProcessResults.FAILED:
|
|
64060
|
-
failedCount++;
|
|
64061
|
-
break;
|
|
64062
|
-
}
|
|
64063
|
-
if (processedCount % 25 === 0) log(`Processing: ${processedCount}/${pairs.length}`, showingNotice ? 64 : 32, "syncAll");
|
|
64064
|
-
}
|
|
64065
|
-
log(`Synchronisation completed: ${processedCount} files processed (${completedCount} completed, ${skippedCount} skipped, ${failedCount} failed)`, showingNotice ? 64 : 32, "syncAll");
|
|
64066
|
-
saveFileStatus(host, true);
|
|
64067
|
-
return failedCount === 0;
|
|
64068
|
-
}
|
|
64069
|
-
function normaliseFullScanOptions(showingNoticeOrOptions, ignoreSuspending = false) {
|
|
64070
|
-
if (typeof showingNoticeOrOptions === "object") return {
|
|
64071
|
-
mode: FullScanModes.NEWER_WINS,
|
|
64072
|
-
...showingNoticeOrOptions
|
|
64073
|
-
};
|
|
64074
|
-
return {
|
|
64075
|
-
mode: FullScanModes.NEWER_WINS,
|
|
64076
|
-
showingNotice: showingNoticeOrOptions ?? false,
|
|
64077
|
-
ignoreSuspending
|
|
64078
|
-
};
|
|
64079
|
-
}
|
|
64080
|
-
var fileMaps = /* @__PURE__ */ new Map();
|
|
64081
|
-
var FILE_STATUS_MAP_KEY = "fileStatusMap";
|
|
64082
|
-
var FILE_STATUS_MAP_LOCK = "offlineScanner-fileStatusMap";
|
|
64083
|
-
async function loadFileStatus(host) {
|
|
64084
|
-
await serialized(FILE_STATUS_MAP_LOCK, async () => {
|
|
64085
|
-
const kvDB = host.services.keyValueDB.kvDB;
|
|
64086
|
-
if (!kvDB?.get) {
|
|
64087
|
-
fileMaps = /* @__PURE__ */ new Map();
|
|
64088
|
-
return;
|
|
64089
|
-
}
|
|
64090
|
-
const mapItems = await kvDB.get(FILE_STATUS_MAP_KEY) || {};
|
|
64091
|
-
fileMaps = new Map(Object.entries(mapItems));
|
|
64092
|
-
});
|
|
64093
|
-
}
|
|
64094
|
-
async function _saveFileStatus(host) {
|
|
64095
|
-
await serialized(FILE_STATUS_MAP_LOCK, async () => {
|
|
64096
|
-
const kvDB = host.services.keyValueDB.kvDB;
|
|
64097
|
-
if (!kvDB?.set) return;
|
|
64098
|
-
await kvDB.set(FILE_STATUS_MAP_KEY, Object.fromEntries(fileMaps));
|
|
64099
|
-
});
|
|
64100
|
-
}
|
|
64101
|
-
var saveFileStatusTimeout = null;
|
|
64102
|
-
function saveFileStatus(host, immediate = false) {
|
|
64103
|
-
if (immediate) {
|
|
64104
|
-
if (saveFileStatusTimeout !== null) compatGlobal.clearTimeout(saveFileStatusTimeout);
|
|
64105
|
-
saveFileStatusTimeout = compatGlobal.setTimeout(() => {
|
|
64106
|
-
saveFileStatusTimeout = null;
|
|
64107
|
-
_saveFileStatus(host);
|
|
64108
|
-
}, 0);
|
|
64109
|
-
return;
|
|
64110
|
-
}
|
|
64111
|
-
if (saveFileStatusTimeout === null) saveFileStatusTimeout = compatGlobal.setTimeout(() => {
|
|
64112
|
-
saveFileStatusTimeout = null;
|
|
64113
|
-
_saveFileStatus(host);
|
|
64114
|
-
}, 1e3);
|
|
64115
|
-
}
|
|
64116
|
-
function updateFileMTimeInMap(host, key, mtime) {
|
|
64117
|
-
fileMaps.set(key, mtime);
|
|
64118
|
-
saveFileStatus(host);
|
|
64119
|
-
}
|
|
64120
|
-
function getFileMTimeFromMap(key) {
|
|
64121
|
-
return fileMaps.get(key);
|
|
64122
|
-
}
|
|
64123
|
-
async function performFullScan(host, log, errorManager, showingNoticeOrOptions = false, ignoreSuspending = false) {
|
|
64124
|
-
const options = normaliseFullScanOptions(showingNoticeOrOptions, ignoreSuspending);
|
|
64125
|
-
const showingNotice = options.showingNotice ?? false;
|
|
64126
|
-
if (!canProceedScan(host, errorManager, log, showingNotice, options.ignoreSuspending ?? false)) return false;
|
|
64127
|
-
log("Opening the key-value database", 16);
|
|
64128
|
-
const isInitialized = await host.services.keyValueDB.kvDB.get("initialized") || false;
|
|
64129
|
-
if (showingNotice) log("Initializing", 64, "syncAll");
|
|
64130
|
-
if (isInitialized) {
|
|
64131
|
-
log("Restoring storage state", 16);
|
|
64132
|
-
await host.serviceModules.storageAccess.restoreState();
|
|
64133
|
-
}
|
|
64134
|
-
log("Initialize and checking database files");
|
|
64135
|
-
log("Checking deleted files");
|
|
64136
|
-
await collectDeletedFiles(host, log);
|
|
64137
|
-
const scanResult = await synchroniseAllFilesBetweenDBandStorage(host, log, errorManager, options);
|
|
64138
|
-
log("Initialized, NOW TRACKING!");
|
|
64139
|
-
if (!isInitialized) await host.services.keyValueDB.kvDB.set("initialized", true);
|
|
64140
|
-
if (showingNotice) log("Initialize done!", 64, "syncAll");
|
|
64141
|
-
return scanResult;
|
|
64142
|
-
}
|
|
64143
|
-
//#endregion
|
|
64144
64606
|
//#region cliOutput.ts
|
|
64145
64607
|
function formatValue(value) {
|
|
64146
64608
|
if (typeof value === "string") return value;
|
|
@@ -64561,7 +65023,7 @@ async function runCommand(options, context) {
|
|
|
64561
65023
|
if (options.command === "mirror") {
|
|
64562
65024
|
writeStderrLine(standardIo, "[Command] mirror");
|
|
64563
65025
|
const log = (msg) => writeStderrLine(standardIo, `[Mirror] ${String(msg)}`);
|
|
64564
|
-
return await performFullScan(core, log, new UnresolvedErrorManager(core.services.appLifecycle, core.services.context.events), false, true);
|
|
65026
|
+
return await performFullScan(core, log, new UnresolvedErrorManager(core.services.appLifecycle, core.services.context.events), false, true) === VaultScanResults.COMPLETED;
|
|
64565
65027
|
}
|
|
64566
65028
|
if (options.command === "remote-add") {
|
|
64567
65029
|
if (options.commandArgs.length < 2) throw new Error("remote-add requires two arguments: <name> <connstr>");
|
|
@@ -70802,11 +71264,11 @@ ${info.lastSeq} / ${info.maxSeqInBatch})`, logLevel, "p2p-replicator");
|
|
|
70802
71264
|
const tweakValues = await this.server.getConnection(peerId).invokeRemoteObjectFunction("getTweakSettings", [this.server.serverPeerId], 5e3, signal);
|
|
70803
71265
|
if (signal?.aborted) return false;
|
|
70804
71266
|
const thisTweakValues = await this.getTweakSettings("");
|
|
70805
|
-
if (!isObjectDifferent(thisTweakValues, tweakValues)) return true;
|
|
70806
71267
|
if (thisTweakValues.passphrase !== tweakValues.passphrase) {
|
|
70807
71268
|
Logger("Replication cancelled: Passphrase is not matched\nCannot replicate to a remote database until the problem is resolved.", logLevel);
|
|
70808
71269
|
return false;
|
|
70809
71270
|
}
|
|
71271
|
+
if (!assessTweakCompatibility(thisTweakValues, tweakValues).representationDiffers) return true;
|
|
70810
71272
|
Logger("Some mismatched configuration have been detected... Please check settings for efficient replication.", logLevel);
|
|
70811
71273
|
return true;
|
|
70812
71274
|
}
|