pro and smart conflict

This commit is contained in:
fyears
2024-05-27 00:33:49 +08:00
parent 0802767726
commit 06dad54d4c
42 changed files with 2087 additions and 348 deletions
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+9
View File
@@ -0,0 +1,9 @@
# Main Basic Source
## What?
The main basic source code for Remotely Save.
## License
The codes or files or subfolders inside the current folder (`src` in the repo), are released under "open source" license: "Apache License, version 2.0".
+9 -3
View File
@@ -3,6 +3,7 @@
* To avoid circular dependency.
*/
import type { ProConfig } from "../pro/src/baseTypesPro";
import type { LangTypeAndAuto } from "./i18n";
export const DEFAULT_CONTENT_TYPE = "application/octet-stream";
@@ -155,6 +156,8 @@ export interface RemotelySavePluginSettings {
profiler?: ProfilerConfig;
pro?: ProConfig;
/**
* @deprecated
*/
@@ -188,7 +191,10 @@ export const OAUTH2_FORCE_EXPIRE_MILLISECONDS = 1000 * 60 * 60 * 24 * 80;
export type EmptyFolderCleanType = "skip" | "clean_both";
export type ConflictActionType = "keep_newer" | "keep_larger" | "rename_both";
export type ConflictActionType =
| "keep_newer"
| "keep_larger"
| "smart_conflict";
export type DecisionTypeForMixedEntity =
| "only_history"
@@ -203,11 +209,11 @@ export type DecisionTypeForMixedEntity =
| "remote_is_deleted_thus_also_delete_local"
| "conflict_created_then_keep_local"
| "conflict_created_then_keep_remote"
| "conflict_created_then_keep_both"
| "conflict_created_then_smart_conflict"
| "conflict_created_then_do_nothing"
| "conflict_modified_then_keep_local"
| "conflict_modified_then_keep_remote"
| "conflict_modified_then_keep_both"
| "conflict_modified_then_smart_conflict"
| "folder_existed_both_then_do_nothing"
| "folder_existed_local_then_also_create_remote"
| "folder_existed_remote_then_also_create_local"
+60
View File
@@ -0,0 +1,60 @@
import type { FakeFs } from "./fsAll";
export async function copyFolder(key: string, left: FakeFs, right: FakeFs) {
if (!key.endsWith("/")) {
throw Error(`should not call ${key} in copyFolder`);
}
const statsLeft = await left.stat(key);
const entity = await right.mkdir(key, statsLeft.mtimeCli);
return {
entity: entity,
content: undefined,
};
}
export async function copyFile(key: string, left: FakeFs, right: FakeFs) {
// console.debug(`copyFile: key=${key}, left=${left.kind}, right=${right.kind}`);
if (key.endsWith("/")) {
throw Error(`should not call ${key} in copyFile`);
}
const statsLeft = await left.stat(key);
const content = await left.readFile(key);
if (statsLeft.size === undefined || statsLeft.size === 0) {
// some weird bugs on android not returning size. just ignore them
statsLeft.size = content.byteLength;
} else {
if (statsLeft.size !== content.byteLength) {
throw Error(
`error copying ${left.kind}=>${right.kind}: size not matched`
);
}
}
if (statsLeft.mtimeCli === undefined) {
throw Error(`error copying ${left.kind}=>${right.kind}, no mtimeCli`);
}
// console.debug(`copyFile: about to start right.writeFile`);
return {
entity: await right.writeFile(
key,
content,
statsLeft.mtimeCli,
statsLeft.mtimeCli /* TODO */
),
content: content,
};
}
export async function copyFileOrFolder(
key: string,
left: FakeFs,
right: FakeFs
) {
if (key.endsWith("/")) {
return await copyFolder(key, left, right);
} else {
return await copyFile(key, left, right);
}
}
+1
View File
@@ -13,6 +13,7 @@ export abstract class FakeFs {
ctime: number
): Promise<Entity>;
abstract readFile(key: string): Promise<ArrayBuffer>;
abstract rename(key1: string, key2: string): Promise<void>;
abstract rm(key: string): Promise<void>;
abstract checkConnect(callbackFunc?: any): Promise<boolean>;
abstract getUserDisplayName(): Promise<string>;
+19
View File
@@ -695,6 +695,25 @@ export class FakeFsDropbox extends FakeFs {
}
}
async rename(key1: string, key2: string): Promise<void> {
const remoteFileName1 = getDropboxPath(key1, this.remoteBaseDir);
const remoteFileName2 = getDropboxPath(key2, this.remoteBaseDir);
await this._init();
try {
await retryReq(
() =>
this.dropbox.filesMoveV2({
from_path: remoteFileName1,
to_path: remoteFileName2,
}),
`${key1}=>${key2}` // just a hint here
);
} catch (err) {
console.error("some error while moving");
console.error(err);
}
}
async rm(key: string): Promise<void> {
if (key === "/") {
return;
+25
View File
@@ -356,6 +356,31 @@ export class FakeFsEncrypt extends FakeFs {
}
}
async rename(key1: string, key2: string): Promise<void> {
if (!this.hasCacheMap) {
throw new Error("You have to build the cacheMap firstly for readFile");
}
let key1Enc = this.cacheMapOrigToEnc[key1];
if (key1Enc === undefined) {
if (this.isPasswordEmpty()) {
key1Enc = key1;
} else {
key1Enc = await this._encryptName(key1);
}
this.cacheMapOrigToEnc[key1] = key1Enc;
}
let key2Enc = this.cacheMapOrigToEnc[key2];
if (key2Enc === undefined) {
if (this.isPasswordEmpty()) {
key2Enc = key2;
} else {
key2Enc = await this._encryptName(key2);
}
this.cacheMapOrigToEnc[key2] = key2Enc;
}
return await this.innerFs.rename(key1Enc, key2Enc);
}
async rm(key: string): Promise<void> {
if (!this.hasCacheMap) {
throw new Error("You have to build the cacheMap firstly for rm");
+5
View File
@@ -145,6 +145,7 @@ export class FakeFsLocal extends FakeFs {
): Promise<Entity> {
await this.vault.adapter.writeBinary(key, content, {
mtime: mtime,
ctime: ctime,
});
return await this.stat(key);
}
@@ -153,6 +154,10 @@ export class FakeFsLocal extends FakeFs {
return await this.vault.adapter.readBinary(key);
}
async rename(key1: string, key2: string): Promise<void> {
return await this.vault.adapter.rename(key1, key2);
}
async rm(key: string): Promise<void> {
if (this.deleteToWhere === "obsidian") {
await this.vault.adapter.trashLocal(key);
+4
View File
@@ -38,6 +38,10 @@ export class FakeFsMock extends FakeFs {
throw new Error("Method not implemented.");
}
async rename(key1: string, key2: string): Promise<void> {
throw new Error("Method not implemented.");
}
async rm(key: string): Promise<void> {
throw new Error("Method not implemented.");
}
+12
View File
@@ -928,6 +928,18 @@ export class FakeFsOnedrive extends FakeFs {
}
}
async rename(key1: string, key2: string): Promise<void> {
if (key1 === "" || key1 === "/" || key2 === "" || key2 === "/") {
return;
}
const remoteFileName1 = getOnedrivePath(key1, this.remoteBaseDir);
const remoteFileName2 = getOnedrivePath(key2, this.remoteBaseDir);
await this._init();
await this._patchJson(remoteFileName1, {
name: remoteFileName2,
});
}
async rm(key: string): Promise<void> {
if (key === "" || key === "/") {
return;
+4
View File
@@ -746,6 +746,10 @@ export class FakeFsS3 extends FakeFs {
return bodyContents;
}
async rename(key1: string, key2: string): Promise<void> {
throw Error(`rename not implemented for s3`);
}
async rm(key: string): Promise<void> {
if (key === "/") {
return;
+13 -16
View File
@@ -66,24 +66,11 @@ if (VALID_REQURL) {
const p: RequestUrlParam = {
url: options.url,
method: options.method,
// body: options.data as string | ArrayBuffer,
body: options.data as string | ArrayBuffer,
headers: transformedHeaders,
contentType: reqContentType,
throw: false,
};
if (
options.data === undefined ||
options.data === null ||
isString(options.data)
) {
p.body = options.data;
} else {
if (typeof (options.data as any).transfer === "function") {
p.body = (options.data as any).transfer();
} else {
p.body = options.data as ArrayBuffer;
}
}
let r = await requestUrl(p);
@@ -330,9 +317,9 @@ export class FakeFsWebdav extends FakeFs {
*/
_getnextcloudUploadServerAddress = () => {
let k = this.webdavConfig.address;
if (k.endsWith('/')) {
if (k.endsWith("/")) {
// no tailing slash
k = k.substring(0, k.length-1);
k = k.substring(0, k.length - 1);
}
const s = k.split("/");
if (
@@ -797,6 +784,16 @@ export class FakeFsWebdav extends FakeFs {
throw Error(`unexpected file content result with type ${typeof buff}`);
}
async rename(key1: string, key2: string): Promise<void> {
if (key1 === "/" || key2 === "/") {
return;
}
const remoteFileName1 = getWebdavPath(key1, this.remoteBaseDir);
const remoteFileName2 = getWebdavPath(key2, this.remoteBaseDir);
await this._init();
await this.client.moveFile(remoteFileName1, remoteFileName2);
}
async rm(key: string): Promise<void> {
if (key === "/") {
return;
+9
View File
@@ -230,6 +230,15 @@ export class FakeFsWebdis extends FakeFs {
return rsp;
}
async rename(key1: string, key2: string): Promise<void> {
const fullKey1 = getWebdisPath(key1, this.remoteBaseDir);
const fullKey2 = getWebdisPath(key2, this.remoteBaseDir);
const commandContent = `RENAME/${fullKey1}:content/${fullKey2}:content`;
await this._fetchCommand("POST", commandContent);
const commandMeta = `RENAME/${fullKey1}:meta/${fullKey2}:meta`;
await this._fetchCommand("POST", commandMeta);
}
async rm(key: string): Promise<void> {
const fullKey = getWebdisPath(key, this.remoteBaseDir);
const command = `DEL/${fullKey}:meta/${fullKey}:content`;
+5 -1
View File
@@ -1,7 +1,11 @@
import merge from "lodash/merge";
import Mustache from "mustache";
import { moment } from "obsidian";
import { LANGS } from "./langs";
import { LANGS as LANGS_PRO } from "../pro/src/langs";
import { LANGS as LANGS_BASIC } from "./langs";
const LANGS = merge(LANGS_BASIC, LANGS_PRO);
export type LangType = keyof typeof LANGS;
export type LangTypeAndAuto = LangType | "auto";
+1
View File
@@ -24,6 +24,7 @@ export const exportQrCodeUri = async (
delete settings2.onedrive;
delete settings2.webdav;
delete settings2.webdis;
delete settings2.pro;
} else if (exportFields === "s3") {
settings2 = { s3: cloneDeep(settings.s3) };
} else if (exportFields === "dropbox") {
+1 -1
View File
@@ -277,7 +277,7 @@
"settings_deletetowhere_system_trash": "system trash (default)",
"settings_deletetowhere_obsidian_trash": "Obsidian .trash folder",
"settings_conflictaction": "Action For Conflict",
"settings_conflictaction_desc": "If a file is created or modified on both side since last update, it's a conflict event. How to deal with it? This only works for bidirectional sync.",
"settings_conflictaction_desc": "<p>If a file is created or modified on both side since last update, it's a conflict event. How to deal with it? This only works for bidirectional sync.</p>",
"settings_conflictaction_keep_newer": "newer version survives (default)",
"settings_conflictaction_keep_larger": "larger size version survives",
"settings_cleanemptyfolder": "Action For Empty Folders",
+7
View File
@@ -20,6 +20,7 @@ export const DEFAULT_TBL_LOGGER_OUTPUT = "loggeroutput";
export const DEFAULT_TBL_SIMPLE_KV_FOR_MISC = "simplekvformisc";
export const DEFAULT_TBL_PREV_SYNC_RECORDS = "prevsyncrecords";
export const DEFAULT_TBL_PROFILER_RESULTS = "profilerresults";
export const DEFAULT_TBL_FILE_CONTENT_HISTORY = "filecontenthistory";
/**
* @deprecated
@@ -62,6 +63,7 @@ export interface InternalDBs {
simpleKVForMiscTbl: LocalForage;
prevSyncRecordsTbl: LocalForage;
profilerResultsTbl: LocalForage;
fileContentHistoryTbl: LocalForage;
/**
* @deprecated
@@ -221,6 +223,11 @@ export const prepareDBs = async (
name: DEFAULT_DB_NAME,
storeName: DEFAULT_TBL_SYNC_MAPPING,
}),
fileContentHistoryTbl: localforage.createInstance({
name: DEFAULT_DB_NAME,
storeName: DEFAULT_TBL_FILE_CONTENT_HISTORY,
}),
} as InternalDBs;
// try to get vaultRandomID firstly
+88
View File
@@ -13,6 +13,13 @@ import {
requireApiVersion,
setIcon,
} from "obsidian";
import {
DEFAULT_PRO_CONFIG,
getAndSaveProEmail,
getAndSaveProFeatures,
sendAuthReq as sendAuthReqPro,
setConfigBySuccessfullAuthInplace as setConfigBySuccessfullAuthInplacePro,
} from "../pro/src/account";
import type {
RemotelySavePluginSettings,
SyncTriggerSourceType,
@@ -56,6 +63,7 @@ import { SyncAlgoV3Modal } from "./syncAlgoV3Notice";
// biome-ignore lint/suspicious/noShadowRestrictedNames: <explanation>
import AggregateError from "aggregate-error";
import throttle from "lodash/throttle";
import { COMMAND_CALLBACK_PRO } from "../pro/src/baseTypesPro";
import { exportVaultSyncPlansToFiles } from "./debugMode";
import { FakeFsEncrypt } from "./fsEncrypt";
import { getClient } from "./fsGetter";
@@ -97,6 +105,7 @@ const DEFAULT_SETTINGS: RemotelySavePluginSettings = {
enableMobileStatusBar: false,
encryptionMethod: "unknown",
profiler: DEFAULT_PROFILER_CONFIG,
pro: DEFAULT_PRO_CONFIG,
};
interface OAuth2Info {
@@ -399,6 +408,8 @@ export default class RemotelySavePlugin extends Plugin {
return;
}
const configSaver = async () => await this.saveSettings();
await syncer(
fsLocal,
fsRemote,
@@ -410,6 +421,8 @@ export default class RemotelySavePlugin extends Plugin {
this.vaultRandomID,
this.app.vault.configDir,
this.settings,
this.manifest.version,
configSaver,
getProtectError,
markIsSyncingFunc,
notifyFunc,
@@ -696,6 +709,77 @@ export default class RemotelySavePlugin extends Plugin {
}
);
this.registerObsidianProtocolHandler(
COMMAND_CALLBACK_PRO,
async (inputParams) => {
if (this.oauth2Info.helperModal !== undefined) {
const k = this.oauth2Info.helperModal.contentEl;
k.empty();
t("protocol_pro_connecting")
.split("\n")
.forEach((val) => {
k.createEl("p", {
text: val,
});
});
}
console.debug(inputParams);
const authRes = await sendAuthReqPro(
this.oauth2Info.verifier || "verifier",
inputParams.code,
async (e: any) => {
new Notice(t("protocol_pro_connect_fail"));
new Notice(`${e}`);
throw e;
}
);
console.debug(authRes);
const self = this;
await setConfigBySuccessfullAuthInplacePro(
this.settings.pro!,
authRes,
() => self.saveSettings()
);
await getAndSaveProFeatures(
this.settings.pro!,
this.manifest.version,
() => self.saveSettings()
);
await getAndSaveProEmail(
this.settings.pro!,
this.manifest.version,
() => self.saveSettings()
);
this.oauth2Info.verifier = ""; // reset it
this.oauth2Info.helperModal?.close(); // close it
this.oauth2Info.helperModal = undefined;
this.oauth2Info.authDiv?.toggleClass(
"pro-auth-button-hide",
this.settings.pro?.refreshToken !== ""
);
this.oauth2Info.authDiv = undefined;
this.oauth2Info.revokeAuthSetting?.setDesc(
t("protocol_pro_connect_succ_revoke", {
email: this.settings.pro?.email,
})
);
this.oauth2Info.revokeAuthSetting = undefined;
this.oauth2Info.revokeDiv?.toggleClass(
"pro-revoke-auth-button-hide",
this.settings.pro?.email === ""
);
this.oauth2Info.revokeDiv = undefined;
}
);
this.syncRibbon = this.addRibbonIcon(
iconNameSyncWait,
`${this.manifest.name}`,
@@ -1046,6 +1130,10 @@ export default class RemotelySavePlugin extends Plugin {
needSave = true;
}
if (this.settings.pro === undefined) {
this.settings.pro = cloneDeep(DEFAULT_PRO_CONFIG);
}
// save back
if (needSave) {
await this.saveSettings();
+1 -1
View File
@@ -416,7 +416,7 @@ export const toText = (x: any) => {
export const statFix = async (vault: Vault, path: string) => {
const s = await vault.adapter.stat(path);
if (s === undefined || s === null) {
return s;
throw Error(`${path} doesn't exist cannot run stat`);
}
if (s.ctime === undefined || s.ctime === null || Number.isNaN(s.ctime)) {
s.ctime = undefined as any; // force assignment
+47 -18
View File
@@ -21,6 +21,7 @@ import type {
} from "./baseTypes";
import cloneDeep from "lodash/cloneDeep";
import { generateProSettingsPart } from "../pro/src/settingsPro";
import { API_VER_ENSURE_REQURL_OK, VALID_REQURL } from "./baseTypesObs";
import { messyConfigToNormal } from "./configPersist";
import {
@@ -2130,25 +2131,44 @@ export class RemotelySaveSettingTab extends PluginSettingTab {
});
});
new Setting(advDiv)
let conflictActionSettingOrigDesc = t("settings_conflictaction_desc");
if (
(this.plugin.settings.conflictAction ?? "keep_newer") === "smart_conflict"
) {
conflictActionSettingOrigDesc += t(
"settings_conflictaction_smart_conflict_desc"
);
}
const conflictActionSetting = new Setting(advDiv)
.setName(t("settings_conflictaction"))
.setDesc(t("settings_conflictaction_desc"))
.addDropdown((dropdown) => {
dropdown.addOption(
"keep_newer",
t("settings_conflictaction_keep_newer")
);
dropdown.addOption(
"keep_larger",
t("settings_conflictaction_keep_larger")
);
dropdown
.setValue(this.plugin.settings.conflictAction ?? "keep_newer")
.onChange(async (val) => {
this.plugin.settings.conflictAction = val as ConflictActionType;
await this.plugin.saveSettings();
});
});
.setDesc(stringToFragment(conflictActionSettingOrigDesc));
conflictActionSetting.addDropdown((dropdown) => {
dropdown
.addOption("keep_newer", t("settings_conflictaction_keep_newer"))
.addOption("keep_larger", t("settings_conflictaction_keep_larger"))
.addOption(
"smart_conflict",
t("settings_conflictaction_smart_conflict")
)
.setValue(this.plugin.settings.conflictAction ?? "keep_newer")
.onChange(async (val) => {
this.plugin.settings.conflictAction = val as ConflictActionType;
await this.plugin.saveSettings();
conflictActionSettingOrigDesc = t("settings_conflictaction_desc");
if (
(this.plugin.settings.conflictAction ?? "keep_newer") ===
"smart_conflict"
) {
conflictActionSettingOrigDesc += t(
"settings_conflictaction_smart_conflict_desc"
);
}
conflictActionSetting.setDesc(
stringToFragment(conflictActionSettingOrigDesc)
);
});
});
new Setting(advDiv)
.setName(t("settings_cleanemptyfolder"))
@@ -2417,6 +2437,15 @@ export class RemotelySaveSettingTab extends PluginSettingTab {
});
});
//////////////////////////////////////////////////
// below for pro
//////////////////////////////////////////////////
const proDiv = containerEl.createEl("div");
generateProSettingsPart(proDiv, t, this.app, this.plugin, () =>
this.plugin.saveSettings()
);
//////////////////////////////////////////////////
// below for debug
//////////////////////////////////////////////////
+213 -97
View File
@@ -2,6 +2,13 @@
import AggregateError from "aggregate-error";
import PQueue from "p-queue";
import XRegExp from "xregexp";
import { checkProRunnableAndFixInplace } from "../pro/src/account";
import { duplicateFile, isMergable, mergeFile } from "../pro/src/conflictLogic";
import {
clearFileContentHistoryByVaultAndProfile,
getFileContentHistoryByVaultAndProfile,
upsertFileContentHistoryByVaultAndProfile,
} from "../pro/src/localdb";
import type {
ConflictActionType,
EmptyFolderCleanType,
@@ -12,6 +19,7 @@ import type {
SyncDirectionType,
SyncTriggerSourceType,
} from "./baseTypes";
import { copyFile, copyFileOrFolder, copyFolder } from "./copyLogic";
import type { FakeFs } from "./fsAll";
import type { FakeFsEncrypt } from "./fsEncrypt";
import {
@@ -432,7 +440,6 @@ const getSyncPlanInplace = async (
} else {
// Both exists, but modified or conflict
// Look for past files of A or B.
const localEqualPrevSync =
prevSync?.mtimeCli === local.mtimeCli &&
prevSync?.sizeEnc === local.sizeEnc;
@@ -521,9 +528,10 @@ const getSyncPlanInplace = async (
mixedEntry.change = true;
keptFolder.add(getParentFolder(key));
}
} else {
mixedEntry.decisionBranch = 15;
mixedEntry.decision = "conflict_created_then_keep_both";
} else if (conflictAction === "smart_conflict") {
// try merge!
mixedEntry.decisionBranch = 302;
mixedEntry.decision = "conflict_created_then_smart_conflict";
mixedEntry.change = true;
keptFolder.add(getParentFolder(key));
}
@@ -572,9 +580,10 @@ const getSyncPlanInplace = async (
mixedEntry.change = true;
keptFolder.add(getParentFolder(key));
}
} else {
mixedEntry.decisionBranch = 20;
mixedEntry.decision = "conflict_modified_then_keep_both";
} else if (conflictAction === "smart_conflict") {
// yeah, try to merge them!
mixedEntry.decisionBranch = 301;
mixedEntry.decision = "conflict_modified_then_smart_conflict";
mixedEntry.change = true;
keptFolder.add(getParentFolder(key));
}
@@ -900,10 +909,10 @@ const splitFourStepsOnEntityMappings = (
val.decision === "remote_is_created_then_pull" ||
val.decision === "conflict_created_then_keep_local" ||
val.decision === "conflict_created_then_keep_remote" ||
val.decision === "conflict_created_then_keep_both" ||
val.decision === "conflict_created_then_smart_conflict" ||
val.decision === "conflict_modified_then_keep_local" ||
val.decision === "conflict_modified_then_keep_remote" ||
val.decision === "conflict_modified_then_keep_both"
val.decision === "conflict_modified_then_smart_conflict"
) {
if (
uploadDownloads.length === 0 ||
@@ -966,75 +975,6 @@ const fullfillMTimeOfRemoteEntityInplace = (
return remote;
};
async function copyFolder(
key: string,
left: FakeFs,
right: FakeFs
): Promise<Entity> {
if (!key.endsWith("/")) {
throw Error(`should not call ${key} in copyFolder`);
}
const statsLeft = await left.stat(key);
return await right.mkdir(key, statsLeft.mtimeCli);
}
async function copyFile(
key: string,
left: FakeFs,
right: FakeFs
): Promise<Entity> {
// console.debug(`copyFile: key=${key}, left=${left.kind}, right=${right.kind}`);
if (key.endsWith("/")) {
throw Error(`should not call ${key} in copyFile`);
}
const statsLeft = await left.stat(key);
const content = await left.readFile(key);
if (statsLeft.size === undefined || statsLeft.size === 0) {
// some weird bugs on android not returning size. just ignore them
statsLeft.size = content.byteLength;
} else {
if (statsLeft.size !== content.byteLength) {
throw Error(
`error copying ${left.kind}=>${right.kind}: size not matched`
);
}
}
if (statsLeft.mtimeCli === undefined) {
throw Error(`error copying ${left.kind}=>${right.kind}, no mtimeCli`);
}
// console.debug(`copyFile: about to start right.writeFile`);
if (typeof (content as any).transfer === "function") {
return await right.writeFile(
key,
(content as any).transfer(),
statsLeft.mtimeCli,
statsLeft.mtimeCli /* TODO */
);
} else {
return await right.writeFile(
key,
content,
statsLeft.mtimeCli,
statsLeft.mtimeCli /* TODO */
);
}
}
async function copyFileOrFolder(
key: string,
left: FakeFs,
right: FakeFs
): Promise<Entity> {
if (key.endsWith("/")) {
return await copyFolder(key, left, right);
} else {
return await copyFile(key, left, right);
}
}
const dispatchOperationToActualV3 = async (
key: string,
vaultRandomID: string,
@@ -1042,7 +982,8 @@ const dispatchOperationToActualV3 = async (
r: MixedEntity,
fsLocal: FakeFs,
fsEncrypt: FakeFsEncrypt,
db: InternalDBs
db: InternalDBs,
conflictAction: ConflictActionType
) => {
// console.debug(
// `inside dispatchOperationToActualV3, key=${key}, r=${JSON.stringify(
@@ -1052,7 +993,20 @@ const dispatchOperationToActualV3 = async (
// )}`
// );
if (r.decision === "only_history") {
clearPrevSyncRecordByVaultAndProfile(db, vaultRandomID, profileID, key);
await clearPrevSyncRecordByVaultAndProfile(
db,
vaultRandomID,
profileID,
key
);
if (conflictAction === "smart_conflict") {
await clearFileContentHistoryByVaultAndProfile(
db,
vaultRandomID,
profileID,
key
);
}
} else if (
r.decision === "local_is_created_too_large_then_do_nothing" ||
r.decision === "remote_is_created_too_large_then_do_nothing" ||
@@ -1071,12 +1025,34 @@ const dispatchOperationToActualV3 = async (
if (r.prevSync !== undefined) {
// if we have prevSync,
// we don't need to do anything, because the record is already there!
// we don't need to update prevSync, because the record is already there!
// but we might need to update content, because it's a new feature
if (conflictAction === "smart_conflict") {
if (isMergable(r.local!)) {
const k = await getFileContentHistoryByVaultAndProfile(
db,
vaultRandomID,
profileID,
r.local!
);
if (k === null || k === undefined) {
await upsertFileContentHistoryByVaultAndProfile(
db,
vaultRandomID,
profileID,
r.local!,
await fsLocal.readFile(r.local!.keyRaw)
);
}
}
}
} else {
// if we don't have prevSync, we use remote entity AND local mtime
// as if it is "uploaded"
if (r.remote !== undefined) {
let entity = r.remote;
// TODO: abstract away the dirty hack
entity = fullfillMTimeOfRemoteEntityInplace(entity, r.local?.mtimeCli);
if (entity !== undefined) {
@@ -1086,6 +1062,17 @@ const dispatchOperationToActualV3 = async (
profileID,
entity
);
if (conflictAction === "smart_conflict") {
if (isMergable(entity)) {
await upsertFileContentHistoryByVaultAndProfile(
db,
vaultRandomID,
profileID,
entity,
await fsLocal.readFile(entity.keyRaw)
);
}
}
}
}
}
@@ -1098,7 +1085,12 @@ const dispatchOperationToActualV3 = async (
) {
// console.debug(`before upload in sync, r=${JSON.stringify(r, null, 2)}`);
const mtimeCli = (await fsLocal.stat(r.key)).mtimeCli!;
const entity = await copyFileOrFolder(r.key, fsLocal, fsEncrypt);
const { entity, content } = await copyFileOrFolder(
r.key,
fsLocal,
fsEncrypt
);
// TODO: abstract away the dirty hack
fullfillMTimeOfRemoteEntityInplace(entity, mtimeCli);
// console.debug(`after fullfill, entity=${JSON.stringify(entity,null,2)}`)
await upsertPrevSyncRecordByVaultAndProfile(
@@ -1107,6 +1099,17 @@ const dispatchOperationToActualV3 = async (
profileID,
entity
);
if (conflictAction === "smart_conflict") {
if (isMergable(entity)) {
await upsertFileContentHistoryByVaultAndProfile(
db,
vaultRandomID,
profileID,
entity,
content!
);
}
}
} else if (
r.decision === "remote_is_modified_then_pull" ||
r.decision === "remote_is_created_then_pull" ||
@@ -1114,10 +1117,14 @@ const dispatchOperationToActualV3 = async (
r.decision === "conflict_modified_then_keep_remote" ||
r.decision === "folder_existed_remote_then_also_create_local"
) {
let e1: Entity | undefined = undefined;
let c1: ArrayBuffer | undefined = undefined;
if (r.key.endsWith("/")) {
await fsLocal.mkdir(r.key);
} else {
await copyFile(r.key, fsEncrypt, fsLocal);
const { entity, content } = await copyFile(r.key, fsEncrypt, fsLocal);
e1 = entity;
c1 = content;
}
await upsertPrevSyncRecordByVaultAndProfile(
db,
@@ -1125,6 +1132,17 @@ const dispatchOperationToActualV3 = async (
profileID,
r.remote!
);
if (conflictAction === "smart_conflict") {
if (isMergable(r.remote!)) {
await upsertFileContentHistoryByVaultAndProfile(
db,
vaultRandomID,
profileID,
r.remote!,
c1! // always file, always has real value
);
}
}
} else if (r.decision === "local_is_deleted_thus_also_delete_remote") {
// local is deleted, we need to delete remote now
await fsEncrypt.rm(r.key);
@@ -1134,6 +1152,16 @@ const dispatchOperationToActualV3 = async (
profileID,
r.key
);
if (conflictAction === "smart_conflict") {
if (isMergable(r.remote!)) {
await clearFileContentHistoryByVaultAndProfile(
db,
vaultRandomID,
profileID,
r.key
);
}
}
} else if (r.decision === "remote_is_deleted_thus_also_delete_local") {
// remote is deleted, we need to delete local now
await fsLocal.rm(r.key);
@@ -1143,20 +1171,92 @@ const dispatchOperationToActualV3 = async (
profileID,
r.key
);
if (conflictAction === "smart_conflict") {
if (isMergable(r.remote!)) {
await clearFileContentHistoryByVaultAndProfile(
db,
vaultRandomID,
profileID,
r.key
);
}
}
} else if (
r.decision === "conflict_created_then_keep_both" ||
r.decision === "conflict_modified_then_keep_both"
r.decision === "conflict_created_then_smart_conflict" ||
r.decision === "conflict_modified_then_smart_conflict"
) {
throw Error(`${r.decision} not implemented yet: ${JSON.stringify(r)}`);
// heavy lifting
if (isMergable(r.local!, r.remote!)) {
const origContent = await getFileContentHistoryByVaultAndProfile(
db,
vaultRandomID,
profileID,
r.local!
);
// console.debug(`we get origContent:`)
// console.debug(origContent)
const { entity, content } = await mergeFile(
r.key,
fsLocal,
fsEncrypt,
origContent
);
await upsertPrevSyncRecordByVaultAndProfile(
db,
vaultRandomID,
profileID,
entity
);
await upsertFileContentHistoryByVaultAndProfile(
db,
vaultRandomID,
profileID,
entity,
content
);
} else {
// duplicate the files
await clearPrevSyncRecordByVaultAndProfile(
db,
vaultRandomID,
profileID,
r.key
);
const mtimeCli = (await fsLocal.stat(r.key)).mtimeCli!;
const { upload, download } = await duplicateFile(
r.key,
fsLocal,
fsEncrypt,
async (upload) => {
// TODO: abstract away the dirty hack
fullfillMTimeOfRemoteEntityInplace(upload, mtimeCli);
await upsertPrevSyncRecordByVaultAndProfile(
db,
vaultRandomID,
profileID,
upload
);
},
async (download) => {
await upsertPrevSyncRecordByVaultAndProfile(
db,
vaultRandomID,
profileID,
download
);
}
);
}
} else if (r.decision === "folder_to_be_created") {
await fsLocal.mkdir(r.key);
const entity = await copyFolder(r.key, fsLocal, fsEncrypt);
const { entity } = await copyFolder(r.key, fsLocal, fsEncrypt);
await upsertPrevSyncRecordByVaultAndProfile(
db,
vaultRandomID,
profileID,
entity
);
// no need to record file content for folder here
} else if (
r.decision === "folder_to_be_deleted_on_both" ||
r.decision === "folder_to_be_deleted_on_local" ||
@@ -1180,6 +1280,7 @@ const dispatchOperationToActualV3 = async (
profileID,
r.key
);
// no need to record file content for folder here
} else {
throw Error(`don't know how to dispatch decision: ${JSON.stringify(r)}`);
}
@@ -1196,6 +1297,7 @@ export const doActualSync = async (
getProtectModifyPercentageErrorStrFunc: any,
db: InternalDBs,
profiler: Profiler | undefined,
conflictAction: ConflictActionType,
callbackSyncProcess?: any
) => {
profiler?.addIndent();
@@ -1318,7 +1420,8 @@ export const doActualSync = async (
val,
fsLocal,
fsEncrypt,
db
db,
conflictAction
);
// console.debug(`finished ${key}`);
@@ -1381,6 +1484,8 @@ export async function syncer(
vaultRandomID: string,
configDir: string,
settings: RemotelySavePluginSettings,
pluginVersion: string,
configSaver: () => Promise<any>,
getProtectModifyPercentageErrorStrFunc: any,
markIsSyncingFunc: (isSyncing: boolean) => void,
notifyFunc?: (s: SyncTriggerSourceType, step: number) => Promise<any>,
@@ -1397,17 +1502,27 @@ export async function syncer(
markIsSyncingFunc(true);
let everythingOk = true;
let step = 0; // dry mode only
await notifyFunc?.(triggerSource, step);
step = 1;
await notifyFunc?.(triggerSource, step);
await ribboonFunc?.(triggerSource, step);
await statusBarFunc?.(triggerSource, step, everythingOk);
profiler?.insert("start big sync func");
let step = 0;
try {
// check pro feature
// if anything goes wrong, it will throw
await checkProRunnableAndFixInplace(
["feature-smart_conflict"],
settings,
pluginVersion,
configSaver
);
// try mode?
await notifyFunc?.(triggerSource, step);
step = 1;
await notifyFunc?.(triggerSource, step);
await ribboonFunc?.(triggerSource, step);
await statusBarFunc?.(triggerSource, step, everythingOk);
profiler?.insert("start big sync func");
step = 2;
await notifyFunc?.(triggerSource, step);
await ribboonFunc?.(triggerSource, step);
@@ -1514,6 +1629,7 @@ export async function syncer(
getProtectModifyPercentageErrorStrFunc,
db,
profiler,
settings.conflictAction ?? "keep_newer",
callbackSyncProcess
);
profiler?.insert(`finish step${step} (actual sync)`);