From f1477eb4624caa009599696f583ecb74c8fcb02a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8C=85=E5=B0=94=E4=BF=8A?= Date: Thu, 22 Jan 2026 09:23:02 +0800 Subject: [PATCH] =?UTF-8?q?=E7=A7=BB=E9=99=A4gtask?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package-lock.json | 6 + src/Notesmaster/app/build.gradle.kts | 18 +- .../net/micode/notes/gtask/data/MetaData.java | 160 ---- .../net/micode/notes/gtask/data/Node.java | 245 ----- .../net/micode/notes/gtask/data/SqlData.java | 269 ------ .../net/micode/notes/gtask/data/SqlNote.java | 668 -------------- .../net/micode/notes/gtask/data/Task.java | 499 ---------- .../net/micode/notes/gtask/data/TaskList.java | 510 ----------- .../exception/ActionFailureException.java | 55 -- .../exception/NetworkFailureException.java | 55 -- .../notes/gtask/remote/GTaskASyncTask.java | 222 ----- .../notes/gtask/remote/GTaskClient.java | 784 ---------------- .../notes/gtask/remote/GTaskManager.java | 857 ------------------ .../notes/gtask/remote/GTaskSyncService.java | 241 ----- .../notes/ui/NotesPreferenceActivity.java | 142 +-- 15 files changed, 86 insertions(+), 4645 deletions(-) create mode 100644 package-lock.json delete mode 100644 src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/MetaData.java delete mode 100644 src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/Node.java delete mode 100644 src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/SqlData.java delete mode 100644 src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java delete mode 100644 src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/Task.java delete mode 100644 src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/TaskList.java delete mode 100644 src/Notesmaster/app/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java delete mode 100644 src/Notesmaster/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java delete mode 100644 src/Notesmaster/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java delete mode 100644 src/Notesmaster/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java delete mode 100644 src/Notesmaster/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java delete mode 100644 src/Notesmaster/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..f855d66 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,6 @@ +{ + "name": "git", + "lockfileVersion": 3, + "requires": true, + "packages": {} +} diff --git a/src/Notesmaster/app/build.gradle.kts b/src/Notesmaster/app/build.gradle.kts index 8f118ed..2332041 100644 --- a/src/Notesmaster/app/build.gradle.kts +++ b/src/Notesmaster/app/build.gradle.kts @@ -30,7 +30,7 @@ android { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 } - packaging { + packaging { resources.excludes.add("META-INF/DEPENDENCIES"); resources.excludes.add("META-INF/NOTICE"); resources.excludes.add("META-INF/LICENSE"); @@ -52,19 +52,3 @@ dependencies { androidTestImplementation(libs.ext.junit) androidTestImplementation(libs.espresso.core) } - -// ==================== 条件编译配置 ==================== -// 暂时禁用Google Tasks同步功能,保留代码为未来开发准备 -// -// gtask包说明: -// - gtask包中包含Google Tasks同步相关代码 -// - 依赖Apache HttpClient 4.5.14库(已移除) -// - AndroidManifest.xml中已注释GTaskSyncService -// -// 未来若需启用同步功能,请执行以下步骤: -// 1. 重命名或删除gtask包(重命名为gtask.disabled避免编译) -// 2. 在dependencies块中添加以下依赖(替换路径为实际路径): -// implementation(files("/httpclient-osgi-4.5.14.jar")) -// implementation(files("/httpclient-win-4.5.14.jar")) -// implementation(files("/httpcore-4.4.16.jar")) -// 3. 在AndroidManifest.xml中取消注释GTaskSyncService(第85-90行) diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/MetaData.java b/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/MetaData.java deleted file mode 100644 index 28f6294..0000000 --- a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/MetaData.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * 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. - */ - -package net.micode.notes.gtask.data; - -import android.database.Cursor; -import android.util.Log; - -import net.micode.notes.tool.GTaskStringUtils; - -import org.json.JSONException; -import org.json.JSONObject; - - -/** - * Google Tasks 元数据类 - *

- * 继承自 Task,用于存储和管理 Google Tasks 同步的元数据信息。 - * 元数据以特殊任务的形式存储在 Google Tasks 中,用于关联本地笔记和远程任务的对应关系。 - * 该类不应通过本地 JSON 或数据库游标进行操作,仅用于远程同步场景。 - *

- */ -public class MetaData extends Task { - /** - * 日志标签 - */ - private final static String TAG = MetaData.class.getSimpleName(); - - /** - * 关联的 Google Tasks ID - */ - private String mRelatedGid = null; - - /** - * 设置元数据信息 - *

- * 将 Google Tasks ID 添加到元信息 JSON 对象中,并设置任务名称为元数据专用名称。 - * 元信息以 JSON 字符串形式存储在任务的 notes 字段中。 - *

- * - * @param gid 关联的 Google Tasks ID - * @param metaInfo 元信息 JSON 对象 - */ - public void setMeta(String gid, JSONObject metaInfo) { - try { - // 将关联的 GID 添加到元信息中 - metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); - } catch (JSONException e) { - Log.e(TAG, "failed to put related gid"); - } - // 将元信息转换为字符串并设置为任务备注 - setNotes(metaInfo.toString()); - // 设置为元数据专用名称 - setName(GTaskStringUtils.META_NOTE_NAME); - } - - /** - * 获取关联的 Google Tasks ID - * - * @return 关联的 Google Tasks ID,如果未设置则返回 null - */ - public String getRelatedGid() { - return mRelatedGid; - } - - /** - * 判断是否值得保存 - *

- * 只有当 notes 字段不为空时才值得保存,因为元数据信息存储在 notes 中。 - *

- * - * @return 如果 notes 不为 null 返回 true,否则返回 false - */ - @Override - public boolean isWorthSaving() { - return getNotes() != null; - } - - /** - * 根据远程 JSON 设置内容 - *

- * 从远程服务器返回的 JSON 对象中解析元数据信息,提取关联的 Google Tasks ID。 - *

- * - * @param js 远程服务器返回的 JSON 对象 - */ - @Override - public void setContentByRemoteJSON(JSONObject js) { - super.setContentByRemoteJSON(js); - if (getNotes() != null) { - try { - // 从 notes 字段中解析元信息 JSON - JSONObject metaInfo = new JSONObject(getNotes().trim()); - // 提取关联的 GID - mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); - } catch (JSONException e) { - Log.w(TAG, "failed to get related gid"); - mRelatedGid = null; - } - } - } - - /** - * 根据本地 JSON 设置内容 - *

- * 此方法不应被调用,因为元数据不通过本地 JSON 进行操作。 - *

- * - * @param js 本地 JSON 对象 - * @throws IllegalAccessError 总是抛出此异常,表示不应调用此方法 - */ - @Override - public void setContentByLocalJSON(JSONObject js) { - // this function should not be called - throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); - } - - /** - * 从内容生成本地 JSON 对象 - *

- * 此方法不应被调用,因为元数据不通过本地 JSON 进行操作。 - *

- * - * @return 无返回值,总是抛出异常 - * @throws IllegalAccessError 总是抛出此异常,表示不应调用此方法 - */ - @Override - public JSONObject getLocalJSONFromContent() { - throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); - } - - /** - * 根据数据库游标获取同步动作 - *

- * 此方法不应被调用,因为元数据不通过数据库游标进行操作。 - *

- * - * @param c 数据库游标 - * @return 无返回值,总是抛出异常 - * @throws IllegalAccessError 总是抛出此异常,表示不应调用此方法 - */ - @Override - public int getSyncAction(Cursor c) { - throw new IllegalAccessError("MetaData:getSyncAction should not be called"); - } - -} diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/Node.java b/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/Node.java deleted file mode 100644 index ad7e431..0000000 --- a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/Node.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * 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. - */ - -package net.micode.notes.gtask.data; - -import android.database.Cursor; - -import org.json.JSONObject; - -/** - * Google Tasks 同步节点抽象基类 - *

- * 定义所有可同步数据模型(Task、TaskList、MetaData)的公共属性和抽象方法。 - * 负责管理同步状态、Google ID、名称、最后修改时间和删除标记等通用属性。 - * 子类需要实现具体的 JSON 转换和同步动作生成逻辑。 - *

- */ -public abstract class Node { - /** - * 无需同步操作 - */ - public static final int SYNC_ACTION_NONE = 0; - - /** - * 需要添加到远程服务器 - */ - public static final int SYNC_ACTION_ADD_REMOTE = 1; - - /** - * 需要添加到本地数据库 - */ - public static final int SYNC_ACTION_ADD_LOCAL = 2; - - /** - * 需要从远程服务器删除 - */ - public static final int SYNC_ACTION_DEL_REMOTE = 3; - - /** - * 需要从本地数据库删除 - */ - public static final int SYNC_ACTION_DEL_LOCAL = 4; - - /** - * 需要更新到远程服务器 - */ - public static final int SYNC_ACTION_UPDATE_REMOTE = 5; - - /** - * 需要更新到本地数据库 - */ - public static final int SYNC_ACTION_UPDATE_LOCAL = 6; - - /** - * 同步冲突,需要特殊处理 - */ - public static final int SYNC_ACTION_UPDATE_CONFLICT = 7; - - /** - * 同步错误 - */ - public static final int SYNC_ACTION_ERROR = 8; - - /** - * Google Tasks ID,用于唯一标识远程任务 - */ - private String mGid; - - /** - * 节点名称 - */ - private String mName; - - /** - * 最后修改时间(时间戳) - */ - private long mLastModified; - - /** - * 删除标记,true 表示已删除 - */ - private boolean mDeleted; - - /** - * 构造一个新的节点实例 - *

- * 初始化所有属性为默认值:GID 为 null,名称为空字符串,最后修改时间为 0,删除标记为 false。 - *

- */ - public Node() { - mGid = null; - mName = ""; - mLastModified = 0; - mDeleted = false; - } - - /** - * 获取创建动作的 JSON 对象 - *

- * 根据指定的动作 ID 生成用于在远程服务器创建节点的 JSON 请求。 - *

- * - * @param actionId 动作 ID,标识具体的创建操作类型 - * @return 包含创建动作信息的 JSON 对象 - */ - public abstract JSONObject getCreateAction(int actionId); - - /** - * 获取更新动作的 JSON 对象 - *

- * 根据指定的动作 ID 生成用于在远程服务器更新节点的 JSON 请求。 - *

- * - * @param actionId 动作 ID,标识具体的更新操作类型 - * @return 包含更新动作信息的 JSON 对象 - */ - public abstract JSONObject getUpdateAction(int actionId); - - /** - * 根据远程 JSON 设置节点内容 - *

- * 从远程服务器返回的 JSON 对象中解析并设置节点的属性值。 - *

- * - * @param js 远程服务器返回的 JSON 对象 - */ - public abstract void setContentByRemoteJSON(JSONObject js); - - /** - * 根据本地 JSON 设置节点内容 - *

- * 从本地数据库存储的 JSON 对象中解析并设置节点的属性值。 - *

- * - * @param js 本地数据库存储的 JSON 对象 - */ - public abstract void setContentByLocalJSON(JSONObject js); - - /** - * 从节点内容生成本地 JSON 对象 - *

- * 将节点的当前属性值转换为 JSON 对象,用于存储到本地数据库。 - *

- * - * @return 包含节点内容的 JSON 对象 - */ - public abstract JSONObject getLocalJSONFromContent(); - - /** - * 根据数据库游标获取同步动作 - *

- * 比较本地数据库中的数据与当前节点状态,确定需要执行的同步动作类型。 - *

- * - * @param c 指向本地数据库记录的游标 - * @return 同步动作类型,取值为 SYNC_ACTION_* 常量之一 - */ - public abstract int getSyncAction(Cursor c); - - /** - * 设置 Google Tasks ID - * - * @param gid Google Tasks ID,用于唯一标识远程任务 - */ - public void setGid(String gid) { - this.mGid = gid; - } - - /** - * 设置节点名称 - * - * @param name 节点名称 - */ - public void setName(String name) { - this.mName = name; - } - - /** - * 设置最后修改时间 - * - * @param lastModified 最后修改时间(时间戳) - */ - public void setLastModified(long lastModified) { - this.mLastModified = lastModified; - } - - /** - * 设置删除标记 - * - * @param deleted 删除标记,true 表示已删除 - */ - public void setDeleted(boolean deleted) { - this.mDeleted = deleted; - } - - /** - * 获取 Google Tasks ID - * - * @return Google Tasks ID,如果未设置则返回 null - */ - public String getGid() { - return this.mGid; - } - - /** - * 获取节点名称 - * - * @return 节点名称 - */ - public String getName() { - return this.mName; - } - - /** - * 获取最后修改时间 - * - * @return 最后修改时间(时间戳) - */ - public long getLastModified() { - return this.mLastModified; - } - - /** - * 获取删除标记 - * - * @return 删除标记,true 表示已删除 - */ - public boolean getDeleted() { - return this.mDeleted; - } - -} diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/SqlData.java b/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/SqlData.java deleted file mode 100644 index 174560e..0000000 --- a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/SqlData.java +++ /dev/null @@ -1,269 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * 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. - */ - -package net.micode.notes.gtask.data; - -import android.content.ContentResolver; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.database.Cursor; -import android.net.Uri; -import android.util.Log; - -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.DataColumns; -import net.micode.notes.data.Notes.DataConstants; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.data.NotesDatabaseHelper.TABLE; -import net.micode.notes.gtask.exception.ActionFailureException; - -import org.json.JSONException; -import org.json.JSONObject; - - -/** - * SQLite 数据内容类 - *

- * 表示笔记的一条数据记录,存储笔记的具体内容信息。 - * 每条数据记录包含 MIME 类型、内容文本和扩展数据字段。 - * 支持从 JSON 对象加载内容或将内容导出为 JSON,用于与 Google Tasks 的数据同步。 - *

- */ -public class SqlData { - private static final String TAG = SqlData.class.getSimpleName(); - - /** 无效 ID 标识符 */ - private static final int INVALID_ID = -99999; - - /** 数据表查询投影字段数组 */ - public static final String[] PROJECTION_DATA = new String[] { - DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1, - DataColumns.DATA3 - }; - - /** ID 字段在投影数组中的索引 */ - public static final int DATA_ID_COLUMN = 0; - - /** MIME 类型字段在投影数组中的索引 */ - public static final int DATA_MIME_TYPE_COLUMN = 1; - - /** 内容字段在投影数组中的索引 */ - public static final int DATA_CONTENT_COLUMN = 2; - - /** 扩展数据 1 字段在投影数组中的索引 */ - public static final int DATA_CONTENT_DATA_1_COLUMN = 3; - - /** 扩展数据 3 字段在投影数组中的索引 */ - public static final int DATA_CONTENT_DATA_3_COLUMN = 4; - - private ContentResolver mContentResolver; - - private boolean mIsCreate; - - private long mDataId; - - private String mDataMimeType; - - private String mDataContent; - - private long mDataContentData1; - - private String mDataContentData3; - - private ContentValues mDiffDataValues; - - /** - * 构造一个新建的数据对象 - *

- * 创建一个尚未保存到数据库的新数据记录,初始化所有字段为默认值。 - * 标记为创建状态,后续调用 commit 方法时会执行插入操作。 - *

- * - * @param context 上下文对象,用于获取 ContentResolver - */ - public SqlData(Context context) { - mContentResolver = context.getContentResolver(); - mIsCreate = true; - mDataId = INVALID_ID; - mDataMimeType = DataConstants.NOTE; - mDataContent = ""; - mDataContentData1 = 0; - mDataContentData3 = ""; - mDiffDataValues = new ContentValues(); - } - - /** - * 从数据库游标构造数据对象 - *

- * 从游标中读取数据记录并初始化对象。 - * 标记为非创建状态,后续调用 commit 方法时会执行更新操作。 - *

- * - * @param context 上下文对象 - * @param c 指向数据记录的数据库游标 - */ - public SqlData(Context context, Cursor c) { - mContentResolver = context.getContentResolver(); - mIsCreate = false; - loadFromCursor(c); - mDiffDataValues = new ContentValues(); - } - - /** - * 从数据库游标加载数据内容 - *

- * 从游标的当前行读取所有数据字段值并初始化对象的成员变量。 - *

- * - * @param c 指向数据记录的数据库游标 - */ - private void loadFromCursor(Cursor c) { - mDataId = c.getLong(DATA_ID_COLUMN); - mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); - mDataContent = c.getString(DATA_CONTENT_COLUMN); - mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN); - mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); - } - - /** - * 从 JSON 对象设置数据内容 - *

- * 解析 JSON 对象中的数据字段,更新当前对象的成员变量。 - * 比较新旧值,将变更记录到差异值集合中。 - *

- * - * @param js 包含数据信息的 JSON 对象 - * @throws JSONException 如果 JSON 解析失败 - */ - public void setContent(JSONObject js) throws JSONException { - long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; - if (mIsCreate || mDataId != dataId) { - mDiffDataValues.put(DataColumns.ID, dataId); - } - mDataId = dataId; - - String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE) - : DataConstants.NOTE; - if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { - mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); - } - mDataMimeType = dataMimeType; - - String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; - if (mIsCreate || !mDataContent.equals(dataContent)) { - mDiffDataValues.put(DataColumns.CONTENT, dataContent); - } - mDataContent = dataContent; - - long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; - if (mIsCreate || mDataContentData1 != dataContentData1) { - mDiffDataValues.put(DataColumns.DATA1, dataContentData1); - } - mDataContentData1 = dataContentData1; - - String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; - if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { - mDiffDataValues.put(DataColumns.DATA3, dataContentData3); - } - mDataContentData3 = dataContentData3; - } - - /** - * 获取数据内容的 JSON 对象 - *

- * 将当前数据的所有字段导出为 JSON 对象格式。 - *

- * - * @return 包含数据信息的 JSON 对象,如果尚未创建到数据库则返回 null - * @throws JSONException 如果 JSON 生成失败 - */ - public JSONObject getContent() throws JSONException { - if (mIsCreate) { - Log.e(TAG, "it seems that we haven't created this in database yet"); - return null; - } - JSONObject js = new JSONObject(); - js.put(DataColumns.ID, mDataId); - js.put(DataColumns.MIME_TYPE, mDataMimeType); - js.put(DataColumns.CONTENT, mDataContent); - js.put(DataColumns.DATA1, mDataContentData1); - js.put(DataColumns.DATA3, mDataContentData3); - return js; - } - - /** - * 提交数据变更到数据库 - *

- * 根据当前状态执行插入或更新操作: - * - 如果是新建数据,插入新记录并获取生成的 ID - * - 如果是已存在的数据,更新变更的字段 - *

- * - * @param noteId 关联的笔记 ID - * @param validateVersion 是否验证版本号,为 true 时仅更新版本号匹配的记录 - * @param version 笔记的版本号,用于版本验证 - * @throws ActionFailureException 如果创建数据失败 - */ - public void commit(long noteId, boolean validateVersion, long version) { - - if (mIsCreate) { - if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) { - mDiffDataValues.remove(DataColumns.ID); - } - - mDiffDataValues.put(DataColumns.NOTE_ID, noteId); - Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); - try { - mDataId = Long.valueOf(uri.getPathSegments().get(1)); - } catch (NumberFormatException e) { - Log.e(TAG, "Get note id error :" + e.toString()); - throw new ActionFailureException("create note failed"); - } - } else { - if (mDiffDataValues.size() > 0) { - int result = 0; - if (!validateVersion) { - result = mContentResolver.update(ContentUris.withAppendedId( - Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); - } else { - // 仅更新笔记版本号匹配的记录,防止并发更新冲突 - result = mContentResolver.update(ContentUris.withAppendedId( - Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, - " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE - + " WHERE " + NoteColumns.VERSION + "=?)", new String[] { - String.valueOf(noteId), String.valueOf(version) - }); - } - if (result == 0) { - Log.w(TAG, "there is no update. maybe user updates note when syncing"); - } - } - } - - mDiffDataValues.clear(); - mIsCreate = false; - } - - /** - * 获取数据 ID - * - * @return 数据在数据库中的 ID - */ - public long getId() { - return mDataId; - } -} diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java b/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java deleted file mode 100644 index 3355141..0000000 --- a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/SqlNote.java +++ /dev/null @@ -1,668 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * 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. - */ - -package net.micode.notes.gtask.data; - -import android.appwidget.AppWidgetManager; -import android.content.ContentResolver; -import android.content.ContentValues; -import android.content.Context; -import android.database.Cursor; -import android.net.Uri; -import android.util.Log; - -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.DataColumns; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.gtask.exception.ActionFailureException; -import net.micode.notes.tool.GTaskStringUtils; -import net.micode.notes.tool.ResourceParser; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.ArrayList; - - -/** - * SQLite 笔记数据类 - *

- * 表示本地数据库中的一条笔记记录,负责笔记数据的增删改查操作。 - * 支持与 Google Tasks 的双向同步,能够从 JSON 对象加载内容或将内容导出为 JSON。 - * 区分普通笔记、文件夹和系统文件夹三种类型,提供版本控制和本地修改标记功能。 - *

- */ -public class SqlNote { - private static final String TAG = SqlNote.class.getSimpleName(); - - /** 无效 ID 标识符 */ - private static final int INVALID_ID = -99999; - - /** 笔记表查询投影字段数组 */ - public static final String[] PROJECTION_NOTE = new String[] { - NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID, - NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE, - NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE, - NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE, NoteColumns.SYNC_ID, - NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID, - NoteColumns.VERSION - }; - - /** ID 字段在投影数组中的索引 */ - public static final int ID_COLUMN = 0; - - /** 提醒日期字段在投影数组中的索引 */ - public static final int ALERTED_DATE_COLUMN = 1; - - /** 背景颜色 ID 字段在投影数组中的索引 */ - public static final int BG_COLOR_ID_COLUMN = 2; - - /** 创建日期字段在投影数组中的索引 */ - public static final int CREATED_DATE_COLUMN = 3; - - /** 是否有附件字段在投影数组中的索引 */ - public static final int HAS_ATTACHMENT_COLUMN = 4; - - /** 修改日期字段在投影数组中的索引 */ - public static final int MODIFIED_DATE_COLUMN = 5; - - /** 子笔记数量字段在投影数组中的索引 */ - public static final int NOTES_COUNT_COLUMN = 6; - - /** 父文件夹 ID 字段在投影数组中的索引 */ - public static final int PARENT_ID_COLUMN = 7; - - /** 摘要文本字段在投影数组中的索引 */ - public static final int SNIPPET_COLUMN = 8; - - /** 笔记类型字段在投影数组中的索引 */ - public static final int TYPE_COLUMN = 9; - - /** Widget ID 字段在投影数组中的索引 */ - public static final int WIDGET_ID_COLUMN = 10; - - /** Widget 类型字段在投影数组中的索引 */ - public static final int WIDGET_TYPE_COLUMN = 11; - - /** 同步 ID 字段在投影数组中的索引 */ - public static final int SYNC_ID_COLUMN = 12; - - /** 本地修改标记字段在投影数组中的索引 */ - public static final int LOCAL_MODIFIED_COLUMN = 13; - - /** 原始父文件夹 ID 字段在投影数组中的索引 */ - public static final int ORIGIN_PARENT_ID_COLUMN = 14; - - /** Google Tasks ID 字段在投影数组中的索引 */ - public static final int GTASK_ID_COLUMN = 15; - - /** 版本号字段在投影数组中的索引 */ - public static final int VERSION_COLUMN = 16; - - private Context mContext; - - private ContentResolver mContentResolver; - - private boolean mIsCreate; - - private long mId; - - private long mAlertDate; - - private int mBgColorId; - - private long mCreatedDate; - - private int mHasAttachment; - - private long mModifiedDate; - - private long mParentId; - - private String mSnippet; - - private int mType; - - private int mWidgetId; - - private int mWidgetType; - - private long mOriginParent; - - private long mVersion; - - private ContentValues mDiffNoteValues; - - private ArrayList mDataList; - - /** - * 构造一个新建的笔记对象 - *

- * 创建一个尚未保存到数据库的新笔记,初始化所有字段为默认值。 - * 标记为创建状态,后续调用 commit 方法时会执行插入操作。 - *

- * - * @param context 上下文对象,用于获取 ContentResolver 和默认资源 - */ - public SqlNote(Context context) { - mContext = context; - mContentResolver = context.getContentResolver(); - mIsCreate = true; - mId = INVALID_ID; - mAlertDate = 0; - mBgColorId = ResourceParser.getDefaultBgId(context); - mCreatedDate = System.currentTimeMillis(); - mHasAttachment = 0; - mModifiedDate = System.currentTimeMillis(); - mParentId = 0; - mSnippet = ""; - mType = Notes.TYPE_NOTE; - mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; - mWidgetType = Notes.TYPE_WIDGET_INVALIDE; - mOriginParent = 0; - mVersion = 0; - mDiffNoteValues = new ContentValues(); - mDataList = new ArrayList(); - } - - /** - * 从数据库游标构造笔记对象 - *

- * 从游标中读取笔记数据并初始化对象,如果笔记类型为普通笔记则加载其数据内容。 - * 标记为非创建状态,后续调用 commit 方法时会执行更新操作。 - *

- * - * @param context 上下文对象 - * @param c 指向笔记记录的数据库游标 - */ - public SqlNote(Context context, Cursor c) { - mContext = context; - mContentResolver = context.getContentResolver(); - mIsCreate = false; - loadFromCursor(c); - mDataList = new ArrayList(); - if (mType == Notes.TYPE_NOTE) - loadDataContent(); - mDiffNoteValues = new ContentValues(); - } - - /** - * 从数据库 ID 构造笔记对象 - *

- * 根据笔记 ID 从数据库查询记录并初始化对象,如果笔记类型为普通笔记则加载其数据内容。 - * 标记为非创建状态,后续调用 commit 方法时会执行更新操作。 - *

- * - * @param context 上下文对象 - * @param id 笔记在数据库中的 ID - */ - public SqlNote(Context context, long id) { - mContext = context; - mContentResolver = context.getContentResolver(); - mIsCreate = false; - loadFromCursor(id); - mDataList = new ArrayList(); - if (mType == Notes.TYPE_NOTE) - loadDataContent(); - mDiffNoteValues = new ContentValues(); - - } - - /** - * 从数据库 ID 加载笔记数据 - *

- * 根据笔记 ID 查询数据库获取笔记记录,并调用 loadFromCursor(Cursor) 加载数据。 - *

- * - * @param id 笔记在数据库中的 ID - */ - private void loadFromCursor(long id) { - Cursor c = null; - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)", - new String[] { - String.valueOf(id) - }, null); - if (c != null) { - c.moveToNext(); - loadFromCursor(c); - } else { - Log.w(TAG, "loadFromCursor: cursor = null"); - } - } finally { - if (c != null) - c.close(); - } - } - - /** - * 从数据库游标加载笔记数据 - *

- * 从游标的当前行读取所有笔记字段值并初始化对象的成员变量。 - *

- * - * @param c 指向笔记记录的数据库游标 - */ - private void loadFromCursor(Cursor c) { - mId = c.getLong(ID_COLUMN); - mAlertDate = c.getLong(ALERTED_DATE_COLUMN); - mBgColorId = c.getInt(BG_COLOR_ID_COLUMN); - mCreatedDate = c.getLong(CREATED_DATE_COLUMN); - mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN); - mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN); - mParentId = c.getLong(PARENT_ID_COLUMN); - mSnippet = c.getString(SNIPPET_COLUMN); - mType = c.getInt(TYPE_COLUMN); - mWidgetId = c.getInt(WIDGET_ID_COLUMN); - mWidgetType = c.getInt(WIDGET_TYPE_COLUMN); - mVersion = c.getLong(VERSION_COLUMN); - } - - /** - * 加载笔记的数据内容 - *

- * 从数据库查询当前笔记的所有数据记录(Data 表),并创建 SqlData 对象列表。 - * 仅对普通笔记类型有效,文件夹类型没有数据内容。 - *

- */ - private void loadDataContent() { - Cursor c = null; - mDataList.clear(); - try { - c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA, - "(note_id=?)", new String[] { - String.valueOf(mId) - }, null); - if (c != null) { - if (c.getCount() == 0) { - Log.w(TAG, "it seems that the note has not data"); - return; - } - while (c.moveToNext()) { - SqlData data = new SqlData(mContext, c); - mDataList.add(data); - } - } else { - Log.w(TAG, "loadDataContent: cursor = null"); - } - } finally { - if (c != null) - c.close(); - } - } - - /** - * 从 JSON 对象设置笔记内容 - *

- * 解析 JSON 对象中的笔记信息和数据,更新当前笔记的字段值。 - * 根据笔记类型(系统文件夹、文件夹、普通笔记)执行不同的更新逻辑。 - * 对于普通笔记,会同时更新其数据内容列表。 - *

- * - * @param js 包含笔记信息的 JSON 对象 - * @return 如果设置成功返回 true,否则返回 false - */ - public boolean setContent(JSONObject js) { - try { - JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { - Log.w(TAG, "cannot set system folder"); - } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { - // for folder we can only update the snnipet and type - String snippet = note.has(NoteColumns.SNIPPET) ? note - .getString(NoteColumns.SNIPPET) : ""; - if (mIsCreate || !mSnippet.equals(snippet)) { - mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); - } - mSnippet = snippet; - - int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) - : Notes.TYPE_NOTE; - if (mIsCreate || mType != type) { - mDiffNoteValues.put(NoteColumns.TYPE, type); - } - mType = type; - } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) { - JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); - long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID; - if (mIsCreate || mId != id) { - mDiffNoteValues.put(NoteColumns.ID, id); - } - mId = id; - - long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note - .getLong(NoteColumns.ALERTED_DATE) : 0; - if (mIsCreate || mAlertDate != alertDate) { - mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate); - } - mAlertDate = alertDate; - - int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note - .getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext); - if (mIsCreate || mBgColorId != bgColorId) { - mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId); - } - mBgColorId = bgColorId; - - long createDate = note.has(NoteColumns.CREATED_DATE) ? note - .getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis(); - if (mIsCreate || mCreatedDate != createDate) { - mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate); - } - mCreatedDate = createDate; - - int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note - .getInt(NoteColumns.HAS_ATTACHMENT) : 0; - if (mIsCreate || mHasAttachment != hasAttachment) { - mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment); - } - mHasAttachment = hasAttachment; - - long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note - .getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis(); - if (mIsCreate || mModifiedDate != modifiedDate) { - mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate); - } - mModifiedDate = modifiedDate; - - long parentId = note.has(NoteColumns.PARENT_ID) ? note - .getLong(NoteColumns.PARENT_ID) : 0; - if (mIsCreate || mParentId != parentId) { - mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId); - } - mParentId = parentId; - - String snippet = note.has(NoteColumns.SNIPPET) ? note - .getString(NoteColumns.SNIPPET) : ""; - if (mIsCreate || !mSnippet.equals(snippet)) { - mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); - } - mSnippet = snippet; - - int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) - : Notes.TYPE_NOTE; - if (mIsCreate || mType != type) { - mDiffNoteValues.put(NoteColumns.TYPE, type); - } - mType = type; - - int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID) - : AppWidgetManager.INVALID_APPWIDGET_ID; - if (mIsCreate || mWidgetId != widgetId) { - mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId); - } - mWidgetId = widgetId; - - int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note - .getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE; - if (mIsCreate || mWidgetType != widgetType) { - mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType); - } - mWidgetType = widgetType; - - long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note - .getLong(NoteColumns.ORIGIN_PARENT_ID) : 0; - if (mIsCreate || mOriginParent != originParent) { - mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent); - } - mOriginParent = originParent; - - for (int i = 0; i < dataArray.length(); i++) { - JSONObject data = dataArray.getJSONObject(i); - SqlData sqlData = null; - if (data.has(DataColumns.ID)) { - long dataId = data.getLong(DataColumns.ID); - for (SqlData temp : mDataList) { - if (dataId == temp.getId()) { - sqlData = temp; - } - } - } - - if (sqlData == null) { - sqlData = new SqlData(mContext); - mDataList.add(sqlData); - } - - sqlData.setContent(data); - } - } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return false; - } - return true; - } - - /** - * 获取笔记内容的 JSON 对象 - *

- * 将当前笔记的所有字段和数据内容导出为 JSON 对象格式。 - * 根据笔记类型生成不同结构的 JSON,普通笔记包含数据数组。 - *

- * - * @return 包含笔记信息的 JSON 对象,如果尚未创建到数据库则返回 null - */ - public JSONObject getContent() { - try { - JSONObject js = new JSONObject(); - - if (mIsCreate) { - Log.e(TAG, "it seems that we haven't created this in database yet"); - return null; - } - - JSONObject note = new JSONObject(); - if (mType == Notes.TYPE_NOTE) { - note.put(NoteColumns.ID, mId); - note.put(NoteColumns.ALERTED_DATE, mAlertDate); - note.put(NoteColumns.BG_COLOR_ID, mBgColorId); - note.put(NoteColumns.CREATED_DATE, mCreatedDate); - note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment); - note.put(NoteColumns.MODIFIED_DATE, mModifiedDate); - note.put(NoteColumns.PARENT_ID, mParentId); - note.put(NoteColumns.SNIPPET, mSnippet); - note.put(NoteColumns.TYPE, mType); - note.put(NoteColumns.WIDGET_ID, mWidgetId); - note.put(NoteColumns.WIDGET_TYPE, mWidgetType); - note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent); - js.put(GTaskStringUtils.META_HEAD_NOTE, note); - - JSONArray dataArray = new JSONArray(); - for (SqlData sqlData : mDataList) { - JSONObject data = sqlData.getContent(); - if (data != null) { - dataArray.put(data); - } - } - js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); - } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) { - note.put(NoteColumns.ID, mId); - note.put(NoteColumns.TYPE, mType); - note.put(NoteColumns.SNIPPET, mSnippet); - js.put(GTaskStringUtils.META_HEAD_NOTE, note); - } - - return js; - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - } - return null; - } - - /** - * 设置父文件夹 ID - *

- * 更新笔记的父文件夹 ID,并将变更记录到差异值集合中。 - *

- * - * @param id 新的父文件夹 ID - */ - public void setParentId(long id) { - mParentId = id; - mDiffNoteValues.put(NoteColumns.PARENT_ID, id); - } - - /** - * 设置 Google Tasks ID - *

- * 将 Google Tasks 的任务 ID 关联到当前笔记,用于同步标识。 - *

- * - * @param gid Google Tasks 任务 ID - */ - public void setGtaskId(String gid) { - mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); - } - - /** - * 设置同步 ID - *

- * 记录最后一次同步的时间戳,用于判断本地和远程数据的同步状态。 - *

- * - * @param syncId 同步时间戳 - */ - public void setSyncId(long syncId) { - mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); - } - - /** - * 重置本地修改标记 - *

- * 将本地修改标记设置为 0,表示笔记已同步,无待同步的本地修改。 - *

- */ - public void resetLocalModified() { - mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); - } - - /** - * 获取笔记 ID - * - * @return 笔记在数据库中的 ID,如果尚未创建则返回 INVALID_ID - */ - public long getId() { - return mId; - } - - /** - * 获取父文件夹 ID - * - * @return 父文件夹在数据库中的 ID - */ - public long getParentId() { - return mParentId; - } - - /** - * 获取笔记摘要文本 - * - * @return 笔记的摘要文本 - */ - public String getSnippet() { - return mSnippet; - } - - /** - * 判断是否为普通笔记类型 - * - * @return 如果是普通笔记返回 true,否则返回 false - */ - public boolean isNoteType() { - return mType == Notes.TYPE_NOTE; - } - - /** - * 提交笔记变更到数据库 - *

- * 根据当前状态执行插入或更新操作: - * - 如果是新建笔记,插入新记录并获取生成的 ID - * - 如果是已存在的笔记,更新变更的字段 - * - 对于普通笔记,同时提交其数据内容 - *

- * - * @param validateVersion 是否验证版本号,为 true 时仅更新版本号不大于当前版本的记录 - * @throws ActionFailureException 如果创建笔记失败 - * @throws IllegalStateException 如果尝试更新无效 ID 的笔记 - */ - public void commit(boolean validateVersion) { - if (mIsCreate) { - if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { - mDiffNoteValues.remove(NoteColumns.ID); - } - - Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues); - try { - mId = Long.valueOf(uri.getPathSegments().get(1)); - } catch (NumberFormatException e) { - Log.e(TAG, "Get note id error :" + e.toString()); - throw new ActionFailureException("create note failed"); - } - if (mId == 0) { - throw new IllegalStateException("Create thread id failed"); - } - - if (mType == Notes.TYPE_NOTE) { - for (SqlData sqlData : mDataList) { - sqlData.commit(mId, false, -1); - } - } - } else { - if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) { - Log.e(TAG, "No such note"); - throw new IllegalStateException("Try to update note with invalid id"); - } - if (mDiffNoteValues.size() > 0) { - mVersion ++; - int result = 0; - if (!validateVersion) { - result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" - + NoteColumns.ID + "=?)", new String[] { - String.valueOf(mId) - }); - } else { - // 仅更新版本号不大于当前版本的记录,防止并发更新冲突 - result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" - + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)", - new String[] { - String.valueOf(mId), String.valueOf(mVersion) - }); - } - if (result == 0) { - Log.w(TAG, "there is no update. maybe user updates note when syncing"); - } - } - - if (mType == Notes.TYPE_NOTE) { - for (SqlData sqlData : mDataList) { - sqlData.commit(mId, validateVersion, mVersion); - } - } - } - - // 从数据库重新加载最新数据,确保内存状态与数据库一致 - loadFromCursor(mId); - if (mType == Notes.TYPE_NOTE) - loadDataContent(); - - mDiffNoteValues.clear(); - mIsCreate = false; - } -} diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/Task.java b/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/Task.java deleted file mode 100644 index f9f0ef3..0000000 --- a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/Task.java +++ /dev/null @@ -1,499 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * 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. - */ - -package net.micode.notes.gtask.data; - -import android.database.Cursor; -import android.text.TextUtils; -import android.util.Log; - -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.DataColumns; -import net.micode.notes.data.Notes.DataConstants; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.gtask.exception.ActionFailureException; -import net.micode.notes.tool.GTaskStringUtils; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - - -/** - * Google Tasks 任务类 - *

- * 继承自 Node,表示 Google Tasks 中的一个任务项。 - * 负责管理任务的完成状态、备注信息、元数据、前驱兄弟节点和父任务列表。 - * 支持与本地笔记的双向同步,能够生成创建和更新动作的 JSON 对象。 - *

- */ -public class Task extends Node { - /** - * 日志标签 - */ - private static final String TAG = Task.class.getSimpleName(); - - /** - * 完成状态标记,true 表示已完成 - */ - private boolean mCompleted; - - /** - * 任务备注信息 - */ - private String mNotes; - - /** - * 元数据 JSON 对象,包含本地笔记的完整信息 - */ - private JSONObject mMetaInfo; - - /** - * 前驱兄弟任务,用于维护任务在列表中的顺序 - */ - private Task mPriorSibling; - - /** - * 父任务列表 - */ - private TaskList mParent; - - /** - * 构造一个新的任务实例 - *

- * 初始化所有属性为默认值:未完成、备注为 null、无前驱兄弟、无父列表、无元数据。 - *

- */ - public Task() { - super(); - mCompleted = false; - mNotes = null; - mPriorSibling = null; - mParent = null; - mMetaInfo = null; - } - - /** - * 获取创建动作的 JSON 对象 - *

- * 生成用于在远程服务器创建任务的 JSON 请求,包含任务名称、备注、父列表 ID 等信息。 - *

- * - * @param actionId 动作 ID,标识具体的创建操作 - * @return 包含创建动作信息的 JSON 对象 - * @throws ActionFailureException 如果生成 JSON 对象失败 - */ - public JSONObject getCreateAction(int actionId) { - JSONObject js = new JSONObject(); - - try { - // action_type - js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); - - // action_id - js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); - - // index - js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this)); - - // entity_delta - JSONObject entity = new JSONObject(); - entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); - entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); - entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, - GTaskStringUtils.GTASK_JSON_TYPE_TASK); - if (getNotes() != null) { - entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); - } - js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); - - // parent_id - js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); - - // dest_parent_type - js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE, - GTaskStringUtils.GTASK_JSON_TYPE_GROUP); - - // list_id - js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); - - // prior_sibling_id - if (mPriorSibling != null) { - js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid()); - } - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to generate task-create jsonobject"); - } - - return js; - } - - /** - * 获取更新动作的 JSON 对象 - *

- * 生成用于在远程服务器更新任务的 JSON 请求,包含任务名称、备注、删除状态等信息。 - *

- * - * @param actionId 动作 ID,标识具体的更新操作 - * @return 包含更新动作信息的 JSON 对象 - * @throws ActionFailureException 如果生成 JSON 对象失败 - */ - public JSONObject getUpdateAction(int actionId) { - JSONObject js = new JSONObject(); - - try { - // action_type - js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); - - // action_id - js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); - - // id - js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); - - // entity_delta - JSONObject entity = new JSONObject(); - entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); - if (getNotes() != null) { - entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); - } - entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); - js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to generate task-update jsonobject"); - } - - return js; - } - - /** - * 根据远程 JSON 设置内容 - *

- * 从远程服务器返回的 JSON 对象中解析并设置任务的属性值,包括 ID、名称、备注、完成状态等。 - *

- * - * @param js 远程服务器返回的 JSON 对象 - * @throws ActionFailureException 如果解析 JSON 失败 - */ - public void setContentByRemoteJSON(JSONObject js) { - if (js != null) { - try { - // id - if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { - setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); - } - - // last_modified - if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { - setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); - } - - // name - if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { - setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); - } - - // notes - if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) { - setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES)); - } - - // deleted - if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) { - setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED)); - } - - // completed - if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) { - setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED)); - } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to get task content from jsonobject"); - } - } - } - - /** - * 根据本地 JSON 设置内容 - *

- * 从本地数据库存储的 JSON 对象中解析并设置任务的属性值。 - * 从笔记数据中提取内容作为任务名称。 - *

- * - * @param js 本地数据库存储的 JSON 对象 - */ - public void setContentByLocalJSON(JSONObject js) { - if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) - || !js.has(GTaskStringUtils.META_HEAD_DATA)) { - Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); - } - - try { - JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); - - if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { - Log.e(TAG, "invalid type"); - return; - } - - // 遍历数据数组,查找笔记内容 - for (int i = 0; i < dataArray.length(); i++) { - JSONObject data = dataArray.getJSONObject(i); - if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { - setName(data.getString(DataColumns.CONTENT)); - break; - } - } - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - } - } - - /** - * 从内容生成本地 JSON 对象 - *

- * 将任务的当前属性值转换为 JSON 对象,用于存储到本地数据库。 - * 如果是新建任务,创建新的 JSON 结构;如果是已同步任务,更新现有元数据。 - *

- * - * @return 包含任务内容的 JSON 对象,如果生成失败则返回 null - */ - public JSONObject getLocalJSONFromContent() { - String name = getName(); - try { - if (mMetaInfo == null) { - // new task created from web - if (name == null) { - Log.w(TAG, "the note seems to be an empty one"); - return null; - } - - JSONObject js = new JSONObject(); - JSONObject note = new JSONObject(); - JSONArray dataArray = new JSONArray(); - JSONObject data = new JSONObject(); - data.put(DataColumns.CONTENT, name); - dataArray.put(data); - js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); - note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); - js.put(GTaskStringUtils.META_HEAD_NOTE, note); - return js; - } else { - // synced task - JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); - - // 更新数据数组中的笔记内容 - for (int i = 0; i < dataArray.length(); i++) { - JSONObject data = dataArray.getJSONObject(i); - if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { - data.put(DataColumns.CONTENT, getName()); - break; - } - } - - note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); - return mMetaInfo; - } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return null; - } - } - - /** - * 设置元数据信息 - *

- * 从元数据对象中解析并设置任务的元信息 JSON 对象。 - * 元信息包含本地笔记的完整结构,用于双向同步。 - *

- * - * @param metaData 元数据对象 - */ - public void setMetaInfo(MetaData metaData) { - if (metaData != null && metaData.getNotes() != null) { - try { - mMetaInfo = new JSONObject(metaData.getNotes()); - } catch (JSONException e) { - Log.w(TAG, e.toString()); - mMetaInfo = null; - } - } - } - - /** - * 根据数据库游标获取同步动作 - *

- * 比较本地数据库中的数据与当前任务状态,确定需要执行的同步动作类型。 - * 处理各种同步场景:无更新、本地更新、远程更新、冲突、错误等。 - *

- * - * @param c 指向本地数据库记录的游标 - * @return 同步动作类型,取值为 SYNC_ACTION_* 常量之一 - */ - public int getSyncAction(Cursor c) { - try { - JSONObject noteInfo = null; - if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { - noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - } - - if (noteInfo == null) { - Log.w(TAG, "it seems that note meta has been deleted"); - return SYNC_ACTION_UPDATE_REMOTE; - } - - if (!noteInfo.has(NoteColumns.ID)) { - Log.w(TAG, "remote note id seems to be deleted"); - return SYNC_ACTION_UPDATE_LOCAL; - } - - // validate the note id now - if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { - Log.w(TAG, "note id doesn't match"); - return SYNC_ACTION_UPDATE_LOCAL; - } - - if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { - // there is no local update - if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { - // no update both side - return SYNC_ACTION_NONE; - } else { - // apply remote to local - return SYNC_ACTION_UPDATE_LOCAL; - } - } else { - // validate gtask id - if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { - Log.e(TAG, "gtask id doesn't match"); - return SYNC_ACTION_ERROR; - } - if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { - // local modification only - return SYNC_ACTION_UPDATE_REMOTE; - } else { - return SYNC_ACTION_UPDATE_CONFLICT; - } - } - } catch (Exception e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - } - - return SYNC_ACTION_ERROR; - } - - /** - * 判断是否值得保存 - *

- * 只有当任务有元数据、非空名称或非空备注时才值得保存。 - *

- * - * @return 如果有元数据、非空名称或非空备注返回 true,否则返回 false - */ - public boolean isWorthSaving() { - return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) - || (getNotes() != null && getNotes().trim().length() > 0); - } - - /** - * 设置完成状态 - * - * @param completed 完成状态,true 表示已完成 - */ - public void setCompleted(boolean completed) { - this.mCompleted = completed; - } - - /** - * 设置备注信息 - * - * @param notes 备注信息 - */ - public void setNotes(String notes) { - this.mNotes = notes; - } - - /** - * 设置前驱兄弟任务 - * - * @param priorSibling 前驱兄弟任务 - */ - public void setPriorSibling(Task priorSibling) { - this.mPriorSibling = priorSibling; - } - - /** - * 设置父任务列表 - * - * @param parent 父任务列表 - */ - public void setParent(TaskList parent) { - this.mParent = parent; - } - - /** - * 获取完成状态 - * - * @return 完成状态,true 表示已完成 - */ - public boolean getCompleted() { - return this.mCompleted; - } - - /** - * 获取备注信息 - * - * @return 备注信息 - */ - public String getNotes() { - return this.mNotes; - } - - /** - * 获取前驱兄弟任务 - * - * @return 前驱兄弟任务 - */ - public Task getPriorSibling() { - return this.mPriorSibling; - } - - /** - * 获取父任务列表 - * - * @return 父任务列表 - */ - public TaskList getParent() { - return this.mParent; - } - -} diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/TaskList.java b/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/TaskList.java deleted file mode 100644 index d454fe7..0000000 --- a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/data/TaskList.java +++ /dev/null @@ -1,510 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * 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. - */ - -package net.micode.notes.gtask.data; - -import android.database.Cursor; -import android.util.Log; - -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.gtask.exception.ActionFailureException; -import net.micode.notes.tool.GTaskStringUtils; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.ArrayList; - - -/** - * Google Tasks 任务列表类 - *

- * 继承自 Node,表示 Google Tasks 中的一个任务列表(文件夹)。 - * 负责管理任务列表的子任务集合,提供任务的增删改查操作。 - * 支持与本地笔记文件夹的双向同步,能够生成创建和更新动作的 JSON 对象。 - *

- */ -public class TaskList extends Node { - /** - * 日志标签 - */ - private static final String TAG = TaskList.class.getSimpleName(); - - /** - * 任务列表索引 - */ - private int mIndex; - - /** - * 子任务列表 - */ - private ArrayList mChildren; - - /** - * 构造一个新的任务列表实例 - *

- * 初始化子任务列表为空,索引设置为 1。 - *

- */ - public TaskList() { - super(); - mChildren = new ArrayList(); - mIndex = 1; - } - - /** - * 获取创建动作的 JSON 对象 - *

- * 生成用于在远程服务器创建任务列表的 JSON 请求,包含列表名称等信息。 - *

- * - * @param actionId 动作 ID,标识具体的创建操作 - * @return 包含创建动作信息的 JSON 对象 - * @throws ActionFailureException 如果生成 JSON 对象失败 - */ - public JSONObject getCreateAction(int actionId) { - JSONObject js = new JSONObject(); - - try { - // action_type - js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); - - // action_id - js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); - - // index - js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex); - - // entity_delta - JSONObject entity = new JSONObject(); - entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); - entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); - entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, - GTaskStringUtils.GTASK_JSON_TYPE_GROUP); - js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to generate tasklist-create jsonobject"); - } - - return js; - } - - /** - * 获取更新动作的 JSON 对象 - *

- * 生成用于在远程服务器更新任务列表的 JSON 请求,包含列表名称、删除状态等信息。 - *

- * - * @param actionId 动作 ID,标识具体的更新操作 - * @return 包含更新动作信息的 JSON 对象 - * @throws ActionFailureException 如果生成 JSON 对象失败 - */ - public JSONObject getUpdateAction(int actionId) { - JSONObject js = new JSONObject(); - - try { - // action_type - js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); - - // action_id - js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); - - // id - js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); - - // entity_delta - JSONObject entity = new JSONObject(); - entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); - entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); - js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to generate tasklist-update jsonobject"); - } - - return js; - } - - /** - * 根据远程 JSON 设置内容 - *

- * 从远程服务器返回的 JSON 对象中解析并设置任务列表的属性值。 - *

- * - * @param js 远程服务器返回的 JSON 对象 - * @throws ActionFailureException 如果解析 JSON 失败 - */ - public void setContentByRemoteJSON(JSONObject js) { - if (js != null) { - try { - // id - if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { - setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); - } - - // last_modified - if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { - setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); - } - - // name - if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { - setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); - } - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("fail to get tasklist content from jsonobject"); - } - } - } - - /** - * 根据本地 JSON 设置内容 - *

- * 从本地数据库存储的 JSON 对象中解析并设置任务列表的属性值。 - * 根据文件夹类型(普通文件夹或系统文件夹)设置对应的名称。 - *

- * - * @param js 本地数据库存储的 JSON 对象 - */ - public void setContentByLocalJSON(JSONObject js) { - if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) { - Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); - } - - try { - JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - - if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { - // 普通文件夹,使用文件夹名称 - String name = folder.getString(NoteColumns.SNIPPET); - setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name); - } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { - // 系统文件夹,根据 ID 设置对应的名称 - if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER) - setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT); - else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER) - setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_CALL_NOTE); - else - Log.e(TAG, "invalid system folder"); - } else { - Log.e(TAG, "error type"); - } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - } - } - - /** - * 从内容生成本地 JSON 对象 - *

- * 将任务列表的当前属性值转换为 JSON 对象,用于存储到本地数据库。 - * 根据文件夹名称判断是系统文件夹还是普通文件夹。 - *

- * - * @return 包含任务列表内容的 JSON 对象,如果生成失败则返回 null - */ - public JSONObject getLocalJSONFromContent() { - try { - JSONObject js = new JSONObject(); - JSONObject folder = new JSONObject(); - - // 去除文件夹名称前缀 - String folderName = getName(); - if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) - folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), - folderName.length()); - folder.put(NoteColumns.SNIPPET, folderName); - // 根据文件夹名称判断类型 - if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT) - || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE)) - folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); - else - folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); - - js.put(GTaskStringUtils.META_HEAD_NOTE, folder); - - return js; - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return null; - } - } - - /** - * 根据数据库游标获取同步动作 - *

- * 比较本地数据库中的数据与当前任务列表状态,确定需要执行的同步动作类型。 - * 对于文件夹冲突,优先应用本地修改。 - *

- * - * @param c 指向本地数据库记录的游标 - * @return 同步动作类型,取值为 SYNC_ACTION_* 常量之一 - */ - public int getSyncAction(Cursor c) { - try { - if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { - // there is no local update - if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { - // no update both side - return SYNC_ACTION_NONE; - } else { - // apply remote to local - return SYNC_ACTION_UPDATE_LOCAL; - } - } else { - // validate gtask id - if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { - Log.e(TAG, "gtask id doesn't match"); - return SYNC_ACTION_ERROR; - } - if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { - // local modification only - return SYNC_ACTION_UPDATE_REMOTE; - } else { - // for folder conflicts, just apply local modification - return SYNC_ACTION_UPDATE_REMOTE; - } - } - } catch (Exception e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - } - - return SYNC_ACTION_ERROR; - } - - /** - * 获取子任务数量 - * - * @return 子任务的数量 - */ - public int getChildTaskCount() { - return mChildren.size(); - } - - /** - * 添加子任务到列表末尾 - *

- * 将任务添加到子任务列表的末尾,并设置其前驱兄弟和父列表。 - *

- * - * @param task 要添加的子任务 - * @return 如果添加成功返回 true,否则返回 false - */ - public boolean addChildTask(Task task) { - boolean ret = false; - if (task != null && !mChildren.contains(task)) { - ret = mChildren.add(task); - if (ret) { - // need to set prior sibling and parent - task.setPriorSibling(mChildren.isEmpty() ? null : mChildren - .get(mChildren.size() - 1)); - task.setParent(this); - } - } - return ret; - } - - /** - * 在指定位置添加子任务 - *

- * 将任务插入到子任务列表的指定位置,并更新相关任务的前驱兄弟关系。 - *

- * - * @param task 要添加的子任务 - * @param index 插入位置索引,必须在 0 到子任务数量之间 - * @return 如果添加成功返回 true,否则返回 false - */ - public boolean addChildTask(Task task, int index) { - if (index < 0 || index > mChildren.size()) { - Log.e(TAG, "add child task: invalid index"); - return false; - } - - int pos = mChildren.indexOf(task); - if (task != null && pos == -1) { - mChildren.add(index, task); - - // update the task list - Task preTask = null; - Task afterTask = null; - if (index != 0) - preTask = mChildren.get(index - 1); - if (index != mChildren.size() - 1) - afterTask = mChildren.get(index + 1); - - task.setPriorSibling(preTask); - if (afterTask != null) - afterTask.setPriorSibling(task); - } - - return true; - } - - /** - * 移除子任务 - *

- * 从子任务列表中移除指定任务,并重置其前驱兄弟和父列表关系。 - * 同时更新后续任务的前驱兄弟关系。 - *

- * - * @param task 要移除的子任务 - * @return 如果移除成功返回 true,否则返回 false - */ - public boolean removeChildTask(Task task) { - boolean ret = false; - int index = mChildren.indexOf(task); - if (index != -1) { - ret = mChildren.remove(task); - - if (ret) { - // reset prior sibling and parent - task.setPriorSibling(null); - task.setParent(null); - - // update the task list - if (index != mChildren.size()) { - mChildren.get(index).setPriorSibling( - index == 0 ? null : mChildren.get(index - 1)); - } - } - } - return ret; - } - - /** - * 移动子任务到指定位置 - *

- * 将子任务从当前位置移动到目标位置,通过先移除再添加实现。 - *

- * - * @param task 要移动的子任务 - * @param index 目标位置索引,必须在 0 到子任务数量减 1 之间 - * @return 如果移动成功返回 true,否则返回 false - */ - public boolean moveChildTask(Task task, int index) { - - if (index < 0 || index >= mChildren.size()) { - Log.e(TAG, "move child task: invalid index"); - return false; - } - - int pos = mChildren.indexOf(task); - if (pos == -1) { - Log.e(TAG, "move child task: the task should in the list"); - return false; - } - - if (pos == index) - return true; - return (removeChildTask(task) && addChildTask(task, index)); - } - - /** - * 根据 GID 查找子任务 - * - * @param gid Google Tasks ID - * @return 找到的子任务,如果未找到则返回 null - */ - public Task findChildTaskByGid(String gid) { - for (int i = 0; i < mChildren.size(); i++) { - Task t = mChildren.get(i); - if (t.getGid().equals(gid)) { - return t; - } - } - return null; - } - - /** - * 获取子任务的索引位置 - * - * @param task 子任务 - * @return 子任务的索引位置,如果未找到则返回 -1 - */ - public int getChildTaskIndex(Task task) { - return mChildren.indexOf(task); - } - - /** - * 根据索引获取子任务 - * - * @param index 索引位置,必须在 0 到子任务数量减 1 之间 - * @return 对应的子任务,如果索引无效则返回 null - */ - public Task getChildTaskByIndex(int index) { - if (index < 0 || index >= mChildren.size()) { - Log.e(TAG, "getTaskByIndex: invalid index"); - return null; - } - return mChildren.get(index); - } - - /** - * 根据 GID 获取子任务 - * - * @param gid Google Tasks ID - * @return 对应的子任务,如果未找到则返回 null - */ - public Task getChilTaskByGid(String gid) { - for (Task task : mChildren) { - if (task.getGid().equals(gid)) - return task; - } - return null; - } - - /** - * 获取子任务列表 - * - * @return 子任务列表的副本 - */ - public ArrayList getChildTaskList() { - return this.mChildren; - } - - /** - * 设置任务列表索引 - * - * @param index 任务列表索引 - */ - public void setIndex(int index) { - this.mIndex = index; - } - - /** - * 获取任务列表索引 - * - * @return 任务列表索引 - */ - public int getIndex() { - return this.mIndex; - } -} diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java b/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java deleted file mode 100644 index 12b3bcd..0000000 --- a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/exception/ActionFailureException.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * 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. - */ - -package net.micode.notes.gtask.exception; - -/** - * 操作失败异常类 - *

- * 用于表示 Google Tasks 同步过程中操作执行失败的情况。 - * 当同步操作(如创建、更新、删除任务或任务列表)失败时抛出此异常。 - * 该异常继承自 RuntimeException,属于非受检异常,调用方可以选择性处理。 - *

- */ -public class ActionFailureException extends RuntimeException { - private static final long serialVersionUID = 4425249765923293627L; - - /** - * 构造一个无详细信息的操作失败异常 - */ - public ActionFailureException() { - super(); - } - - /** - * 构造一个带有详细信息的操作失败异常 - * - * @param paramString 异常的详细信息,描述操作失败的具体原因 - */ - public ActionFailureException(String paramString) { - super(paramString); - } - - /** - * 构造一个带有详细信息和原因的操作失败异常 - * - * @param paramString 异常的详细信息,描述操作失败的具体原因 - * @param paramThrowable 导致此异常的底层异常或错误 - */ - public ActionFailureException(String paramString, Throwable paramThrowable) { - super(paramString, paramThrowable); - } -} diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java b/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java deleted file mode 100644 index a7aeedf..0000000 --- a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/exception/NetworkFailureException.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * 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. - */ - -package net.micode.notes.gtask.exception; - -/** - * 网络异常类 - *

- * 用于表示 Google Tasks 同步过程中发生的网络相关错误。 - * 当网络连接失败、超时或无法访问 Google Tasks 服务时抛出此异常。 - * 该异常继承自 Exception,属于受检异常,调用方必须处理或继续抛出。 - *

- */ -public class NetworkFailureException extends Exception { - private static final long serialVersionUID = 2107610287180234136L; - - /** - * 构造一个无详细信息的网络异常 - */ - public NetworkFailureException() { - super(); - } - - /** - * 构造一个带有详细信息的网络异常 - * - * @param paramString 异常的详细信息,描述网络失败的具体原因 - */ - public NetworkFailureException(String paramString) { - super(paramString); - } - - /** - * 构造一个带有详细信息和原因的网络异常 - * - * @param paramString 异常的详细信息,描述网络失败的具体原因 - * @param paramThrowable 导致此异常的底层异常或错误 - */ - public NetworkFailureException(String paramString, Throwable paramThrowable) { - super(paramString, paramThrowable); - } -} diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java b/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java deleted file mode 100644 index f8ea190..0000000 --- a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/remote/GTaskASyncTask.java +++ /dev/null @@ -1,222 +0,0 @@ - -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * 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. - */ - -package net.micode.notes.gtask.remote; - -import android.app.Notification; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.Context; -import android.content.Intent; -import android.os.AsyncTask; - -import net.micode.notes.R; -import net.micode.notes.ui.NotesListActivity; -import net.micode.notes.ui.NotesPreferenceActivity; - - -/** - * Google Tasks 同步异步任务 - *

- * 继承自 AsyncTask,用于在后台执行 Google Tasks 同步操作。 - * 支持进度更新、通知显示和同步完成回调。 - *

- */ -public class GTaskASyncTask extends AsyncTask { - - /** 同步通知的唯一标识符 */ - private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; - - /** - * 同步完成监听器接口 - *

- * 定义同步完成时的回调方法,用于通知调用方同步任务已结束。 - *

- */ - public interface OnCompleteListener { - /** - * 同步完成时的回调方法 - */ - void onComplete(); - } - - /** 应用上下文 */ - private Context mContext; - - /** 通知管理器 */ - private NotificationManager mNotifiManager; - - /** Google Tasks 管理器实例 */ - private GTaskManager mTaskManager; - - /** 同步完成监听器 */ - private OnCompleteListener mOnCompleteListener; - - /** - * 构造函数 - *

- * 初始化异步任务所需的上下文、监听器、通知管理器和任务管理器。 - *

- * - * @param context 应用上下文 - * @param listener 同步完成监听器 - */ - public GTaskASyncTask(Context context, OnCompleteListener listener) { - mContext = context; - mOnCompleteListener = listener; - // 获取系统通知服务 - mNotifiManager = (NotificationManager) mContext - .getSystemService(Context.NOTIFICATION_SERVICE); - // 获取 GTaskManager 单例 - mTaskManager = GTaskManager.getInstance(); - } - - /** - * 取消同步操作 - *

- * 调用 GTaskManager 的 cancelSync() 方法取消正在进行的同步。 - *

- */ - public void cancelSync() { - mTaskManager.cancelSync(); - } - - /** - * 发布同步进度 - *

- * 调用 AsyncTask 的 publishProgress() 方法发布进度消息到 UI 线程。 - *

- * - * @param message 进度消息 - */ - public void publishProgess(String message) { - publishProgress(new String[] { - message - }); - } - - /** - * 显示同步通知 - *

- * 在状态栏显示同步进度或结果通知。 - * 同步成功时跳转到笔记列表,其他情况跳转到设置页面。 - *

- * - * @param tickerId 通知标题字符串资源 ID - * @param content 通知内容文本 - */ - private void showNotification(int tickerId, String content) { - PendingIntent pendingIntent; - // 根据同步结果选择跳转目标 - if (tickerId != R.string.ticker_success) { - // 同步失败或取消,跳转到设置页面 - pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, - NotesPreferenceActivity.class), PendingIntent.FLAG_IMMUTABLE); - } else { - // 同步成功,跳转到笔记列表 - pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, - NotesListActivity.class), PendingIntent.FLAG_IMMUTABLE); - } - // 构建通知 - Notification.Builder builder = new Notification.Builder(mContext) - .setAutoCancel(true) - .setContentTitle(mContext.getString(R.string.app_name)) - .setContentText(content) - .setContentIntent(pendingIntent) - .setWhen(System.currentTimeMillis()) - .setOngoing(true); - Notification notification=builder.getNotification(); - // 显示通知 - mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); - } - - /** - * 后台执行同步操作 - *

- * 在后台线程执行 Google Tasks 同步,发布登录进度并返回同步结果。 - *

- * - * @param unused 未使用的参数 - * @return 同步状态码(GTaskManager.STATE_SUCCESS、STATE_NETWORK_ERROR、STATE_INTERNAL_ERROR、STATE_SYNC_IN_PROGRESS 或 STATE_SYNC_CANCELLED) - */ - @Override - protected Integer doInBackground(Void... unused) { - // 发布登录进度 - publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity - .getSyncAccountName(mContext))); - // 执行同步并返回结果 - return mTaskManager.sync(mContext, this); - } - - /** - * 进度更新回调 - *

- * 在 UI 线程更新同步进度,显示通知并发送广播。 - *

- * - * @param progress 进度消息数组 - */ - @Override - protected void onProgressUpdate(String... progress) { - // 显示进度通知 - showNotification(R.string.ticker_syncing, progress[0]); - // 如果上下文是 GTaskSyncService,发送广播 - if (mContext instanceof GTaskSyncService) { - ((GTaskSyncService) mContext).sendBroadcast(progress[0]); - } - } - - /** - * 同步完成回调 - *

- * 根据同步结果显示相应的通知,并调用完成监听器。 - * 更新最后同步时间(仅在同步成功时)。 - *

- * - * @param result 同步结果状态码 - */ - @Override - protected void onPostExecute(Integer result) { - // 根据同步结果显示相应通知 - if (result == GTaskManager.STATE_SUCCESS) { - // 同步成功 - showNotification(R.string.ticker_success, mContext.getString( - R.string.success_sync_account, mTaskManager.getSyncAccount())); - // 更新最后同步时间 - NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); - } else if (result == GTaskManager.STATE_NETWORK_ERROR) { - // 网络错误 - showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network)); - } else if (result == GTaskManager.STATE_INTERNAL_ERROR) { - // 内部错误 - showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal)); - } else if (result == GTaskManager.STATE_SYNC_CANCELLED) { - // 同步已取消 - showNotification(R.string.ticker_cancel, mContext - .getString(R.string.error_sync_cancelled)); - } - // 调用完成监听器 - if (mOnCompleteListener != null) { - new Thread(new Runnable() { - - public void run() { - mOnCompleteListener.onComplete(); - } - }).start(); - } - } -} diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java b/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java deleted file mode 100644 index 8201fbd..0000000 --- a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/remote/GTaskClient.java +++ /dev/null @@ -1,784 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * 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. - */ - -package net.micode.notes.gtask.remote; - -import android.accounts.Account; -import android.accounts.AccountManager; -import android.accounts.AccountManagerFuture; -import android.app.Activity; -import android.os.Bundle; -import android.text.TextUtils; -import android.util.Log; - -import net.micode.notes.gtask.data.Node; -import net.micode.notes.gtask.data.Task; -import net.micode.notes.gtask.data.TaskList; -import net.micode.notes.gtask.exception.ActionFailureException; -import net.micode.notes.gtask.exception.NetworkFailureException; -import net.micode.notes.tool.GTaskStringUtils; -import net.micode.notes.ui.NotesPreferenceActivity; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.cookie.Cookie; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpConnectionParams; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.LinkedList; -import java.util.List; -import java.util.zip.GZIPInputStream; -import java.util.zip.Inflater; -import java.util.zip.InflaterInputStream; - - -/** - * Google Tasks 客户端类 - *

- * 单例模式实现的 Google Tasks API 客户端,负责与 Google Tasks 服务器的网络通信。 - * 提供登录认证、任务列表和任务的增删改查、批量更新等功能。 - * 使用 HTTP 协议与 Google Tasks API 交互,支持 Cookie 认证和会话管理。 - *

- */ -public class GTaskClient { - private static final String TAG = GTaskClient.class.getSimpleName(); - - /** Google Tasks 基础 URL */ - private static final String GTASK_URL = "https://mail.google.com/tasks/"; - - /** Google Tasks GET 请求 URL */ - private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; - - /** Google Tasks POST 请求 URL */ - private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; - - /** 单例实例 */ - private static GTaskClient mInstance = null; - - private DefaultHttpClient mHttpClient; - - private String mGetUrl; - - private String mPostUrl; - - private long mClientVersion; - - private boolean mLoggedin; - - private long mLastLoginTime; - - private int mActionId; - - private Account mAccount; - - private JSONArray mUpdateArray; - - /** - * 私有构造函数 - *

- * 初始化所有成员变量为默认值,防止外部直接实例化。 - *

- */ - private GTaskClient() { - mHttpClient = null; - mGetUrl = GTASK_GET_URL; - mPostUrl = GTASK_POST_URL; - mClientVersion = -1; - mLoggedin = false; - mLastLoginTime = 0; - mActionId = 1; - mAccount = null; - mUpdateArray = null; - } - - /** - * 获取 GTaskClient 单例实例 - *

- * 使用双重检查锁定确保线程安全的单例实现。 - *

- * - * @return GTaskClient 单例实例 - */ - public static synchronized GTaskClient getInstance() { - if (mInstance == null) { - mInstance = new GTaskClient(); - } - return mInstance; - } - - /** - * 登录 Google Tasks - *

- * 检查登录状态和账户信息,必要时重新登录。 - * Cookie 有效期为 5 分钟,超时后需要重新登录。 - * 支持自定义域名账户和标准 Gmail/Googlemail 账户。 - *

- * - * @param activity Activity 上下文,用于账户管理 - * @return 如果登录成功返回 true,否则返回 false - */ - public boolean login(Activity activity) { - // we suppose that the cookie would expire after 5 minutes - // then we need to re-login - final long interval = 1000 * 60 * 5; - if (mLastLoginTime + interval < System.currentTimeMillis()) { - mLoggedin = false; - } - - // need to re-login after account switch - if (mLoggedin - && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity - .getSyncAccountName(activity))) { - mLoggedin = false; - } - - if (mLoggedin) { - Log.d(TAG, "already logged in"); - return true; - } - - mLastLoginTime = System.currentTimeMillis(); - String authToken = loginGoogleAccount(activity, false); - if (authToken == null) { - Log.e(TAG, "login google account failed"); - return false; - } - - // login with custom domain if necessary - if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() - .endsWith("googlemail.com"))) { - StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); - int index = mAccount.name.indexOf('@') + 1; - String suffix = mAccount.name.substring(index); - url.append(suffix + "/"); - mGetUrl = url.toString() + "ig"; - mPostUrl = url.toString() + "r/ig"; - - if (tryToLoginGtask(activity, authToken)) { - mLoggedin = true; - } - } - - // try to login with google official url - if (!mLoggedin) { - mGetUrl = GTASK_GET_URL; - mPostUrl = GTASK_POST_URL; - if (!tryToLoginGtask(activity, authToken)) { - return false; - } - } - - mLoggedin = true; - return true; - } - - - - /** - * 登录 Google 账户获取认证令牌 - *

- * 从系统账户管理器获取 Google 账户的认证令牌。 - * 如果 invalidateToken 为 true,会先使旧令牌失效再获取新令牌。 - *

- * - * @param activity Activity 上下文 - * @param invalidateToken 是否使旧令牌失效 - * @return 认证令牌,如果失败则返回 null - */ - private String loginGoogleAccount(Activity activity, boolean invalidateToken) { - String authToken; - AccountManager accountManager = AccountManager.get(activity); - Account[] accounts = accountManager.getAccountsByType("com.google"); - - if (accounts.length == 0) { - Log.e(TAG, "there is no available google account"); - return null; - } - - String accountName = NotesPreferenceActivity.getSyncAccountName(activity); - Account account = null; - for (Account a : accounts) { - if (a.name.equals(accountName)) { - account = a; - break; - } - } - if (account != null) { - mAccount = account; - } else { - Log.e(TAG, "unable to get an account with the same name in the settings"); - return null; - } - - // get the token now - AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account, - "goanna_mobile", null, activity, null, null); - try { - Bundle authTokenBundle = accountManagerFuture.getResult(); - authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); - if (invalidateToken) { - accountManager.invalidateAuthToken("com.google", authToken); - loginGoogleAccount(activity, false); - } - } catch (Exception e) { - Log.e(TAG, "get auth token failed"); - authToken = null; - } - - return authToken; - } - - /** - * 尝试登录 Google Tasks - *

- * 使用认证令牌尝试登录 Google Tasks,如果失败则使令牌失效并重试。 - *

- * - * @param activity Activity 上下文 - * @param authToken 认证令牌 - * @return 如果登录成功返回 true,否则返回 false - */ - private boolean tryToLoginGtask(Activity activity, String authToken) { - if (!loginGtask(authToken)) { - // maybe the auth token is out of date, now let's invalidate the - // token and try again - authToken = loginGoogleAccount(activity, true); - if (authToken == null) { - Log.e(TAG, "login google account failed"); - return false; - } - - if (!loginGtask(authToken)) { - Log.e(TAG, "login gtask failed"); - return false; - } - } - return true; - } - - /** - * 使用认证令牌登录 Google Tasks - *

- * 向 Google Tasks 服务器发送 GET 请求进行认证,获取 Cookie 和客户端版本号。 - *

- * - * @param authToken 认证令牌 - * @return 如果登录成功返回 true,否则返回 false - */ - private boolean loginGtask(String authToken) { - int timeoutConnection = 10000; - int timeoutSocket = 15000; - HttpParams httpParameters = new BasicHttpParams(); - HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); - HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); - mHttpClient = new DefaultHttpClient(httpParameters); - BasicCookieStore localBasicCookieStore = new BasicCookieStore(); - mHttpClient.setCookieStore(localBasicCookieStore); - HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); - - // login gtask - try { - String loginUrl = mGetUrl + "?auth=" + authToken; - HttpGet httpGet = new HttpGet(loginUrl); - HttpResponse response = null; - response = mHttpClient.execute(httpGet); - - // get the cookie now - List cookies = mHttpClient.getCookieStore().getCookies(); - boolean hasAuthCookie = false; - for (Cookie cookie : cookies) { - if (cookie.getName().contains("GTL")) { - hasAuthCookie = true; - } - } - if (!hasAuthCookie) { - Log.w(TAG, "it seems that there is no auth cookie"); - } - - // get the client version - String resString = getResponseContent(response.getEntity()); - String jsBegin = "_setup("; - String jsEnd = ")}"; - int begin = resString.indexOf(jsBegin); - int end = resString.lastIndexOf(jsEnd); - String jsString = null; - if (begin != -1 && end != -1 && begin < end) { - jsString = resString.substring(begin + jsBegin.length(), end); - } - JSONObject js = new JSONObject(jsString); - mClientVersion = js.getLong("v"); - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return false; - } catch (Exception e) { - // simply catch all exceptions - Log.e(TAG, "httpget gtask_url failed"); - return false; - } - - return true; - } - - /** - * 获取下一个动作 ID - *

- * 每次调用返回递增的动作 ID,用于标识不同的操作请求。 - *

- * - * @return 动作 ID - */ - private int getActionId() { - return mActionId++; - } - - /** - * 创建 HTTP POST 请求对象 - *

- * 配置请求头,设置内容类型为 application/x-www-form-urlencoded。 - *

- * - * @return 配置好的 HttpPost 对象 - */ - private HttpPost createHttpPost() { - HttpPost httpPost = new HttpPost(mPostUrl); - httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); - httpPost.setHeader("AT", "1"); - return httpPost; - } - - /** - * 获取 HTTP 响应内容 - *

- * 解析 HTTP 实体的内容,支持 gzip 和 deflate 压缩格式。 - *

- * - * @param entity HTTP 响应实体 - * @return 响应内容的字符串 - * @throws IOException 如果读取响应内容失败 - */ - private String getResponseContent(HttpEntity entity) throws IOException { - String contentEncoding = null; - if (entity.getContentEncoding() != null) { - contentEncoding = entity.getContentEncoding().getValue(); - Log.d(TAG, "encoding: " + contentEncoding); - } - - InputStream input = entity.getContent(); - if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { - input = new GZIPInputStream(entity.getContent()); - } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) { - Inflater inflater = new Inflater(true); - input = new InflaterInputStream(entity.getContent(), inflater); - } - - try { - InputStreamReader isr = new InputStreamReader(input); - BufferedReader br = new BufferedReader(isr); - StringBuilder sb = new StringBuilder(); - - while (true) { - String buff = br.readLine(); - if (buff == null) { - return sb.toString(); - } - sb = sb.append(buff); - } - } finally { - input.close(); - } - } - - /** - * 发送 POST 请求到 Google Tasks 服务器 - *

- * 将 JSON 数据封装为 POST 请求发送到服务器,并解析返回的 JSON 响应。 - *

- * - * @param js 要发送的 JSON 对象 - * @return 服务器返回的 JSON 对象 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果未登录或 JSON 解析失败 - */ - private JSONObject postRequest(JSONObject js) throws NetworkFailureException { - if (!mLoggedin) { - Log.e(TAG, "please login first"); - throw new ActionFailureException("not logged in"); - } - - HttpPost httpPost = createHttpPost(); - try { - LinkedList list = new LinkedList(); - list.add(new BasicNameValuePair("r", js.toString())); - UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); - httpPost.setEntity(entity); - - // execute the post - HttpResponse response = mHttpClient.execute(httpPost); - String jsString = getResponseContent(response.getEntity()); - return new JSONObject(jsString); - - } catch (ClientProtocolException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("postRequest failed"); - } catch (IOException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("postRequest failed"); - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("unable to convert response content to jsonobject"); - } catch (Exception e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("error occurs when posting request"); - } - } - - /** - * 创建新的任务 - *

- * 向 Google Tasks 服务器发送创建任务请求,获取服务器分配的任务 ID。 - *

- * - * @param task 要创建的任务对象 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果 JSON 处理失败 - */ - public void createTask(Task task) throws NetworkFailureException { - commitUpdate(); - try { - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - - // action_list - actionList.put(task.getCreateAction(getActionId())); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // client_version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - // post - JSONObject jsResponse = postRequest(jsPost); - JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( - GTaskStringUtils.GTASK_JSON_RESULTS).get(0); - task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("create task: handing jsonobject failed"); - } - } - - /** - * 创建新的任务列表 - *

- * 向 Google Tasks 服务器发送创建任务列表请求,获取服务器分配的任务列表 ID。 - *

- * - * @param tasklist 要创建的任务列表对象 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果 JSON 处理失败 - */ - public void createTaskList(TaskList tasklist) throws NetworkFailureException { - commitUpdate(); - try { - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - - // action_list - actionList.put(tasklist.getCreateAction(getActionId())); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // client version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - // post - JSONObject jsResponse = postRequest(jsPost); - JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( - GTaskStringUtils.GTASK_JSON_RESULTS).get(0); - tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("create tasklist: handing jsonobject failed"); - } - } - - /** - * 提交批量更新请求 - *

- * 将待更新的节点批量发送到 Google Tasks 服务器。 - * 如果没有待更新的节点,则不执行任何操作。 - *

- * - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果 JSON 处理失败 - */ - public void commitUpdate() throws NetworkFailureException { - if (mUpdateArray != null) { - try { - JSONObject jsPost = new JSONObject(); - - // action_list - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); - - // client_version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - postRequest(jsPost); - mUpdateArray = null; - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("commit update: handing jsonobject failed"); - } - } - } - - /** - * 添加待更新节点到批量更新队列 - *

- * 将节点添加到更新队列中,当队列超过 10 个节点时自动提交。 - *

- * - * @param node 要更新的节点,如果为 null 则不执行任何操作 - * @throws NetworkFailureException 如果提交更新时网络请求失败 - */ - public void addUpdateNode(Node node) throws NetworkFailureException { - if (node != null) { - // too many update items may result in an error - // set max to 10 items - if (mUpdateArray != null && mUpdateArray.length() > 10) { - commitUpdate(); - } - - if (mUpdateArray == null) - mUpdateArray = new JSONArray(); - mUpdateArray.put(node.getUpdateAction(getActionId())); - } - } - - /** - * 移动任务到新的任务列表或新位置 - *

- * 将任务从一个任务列表移动到另一个任务列表,或在同一任务列表中调整顺序。 - *

- * - * @param task 要移动的任务 - * @param preParent 任务的原父任务列表 - * @param curParent 任务的新父任务列表 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果 JSON 处理失败 - */ - public void moveTask(Task task, TaskList preParent, TaskList curParent) - throws NetworkFailureException { - commitUpdate(); - try { - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - JSONObject action = new JSONObject(); - - // action_list - action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); - action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); - action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); - if (preParent == curParent && task.getPriorSibling() != null) { - // put prioring_sibing_id only if moving within the tasklist and - // it is not the first one - action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); - } - action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); - action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); - if (preParent != curParent) { - // put the dest_list only if moving between tasklists - action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); - } - actionList.put(action); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // client_version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - postRequest(jsPost); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("move task: handing jsonobject failed"); - } - } - - /** - * 删除节点 - *

- * 向 Google Tasks 服务器发送删除节点请求,将节点标记为已删除。 - *

- * - * @param node 要删除的节点 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果 JSON 处理失败 - */ - public void deleteNode(Node node) throws NetworkFailureException { - commitUpdate(); - try { - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - - // action_list - node.setDeleted(true); - actionList.put(node.getUpdateAction(getActionId())); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // client_version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - postRequest(jsPost); - mUpdateArray = null; - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("delete node: handing jsonobject failed"); - } - } - - /** - * 获取所有任务列表 - *

- * 从 Google Tasks 服务器获取当前账户的所有任务列表。 - *

- * - * @return 包含所有任务列表信息的 JSON 数组 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果未登录或 JSON 解析失败 - */ - public JSONArray getTaskLists() throws NetworkFailureException { - if (!mLoggedin) { - Log.e(TAG, "please login first"); - throw new ActionFailureException("not logged in"); - } - - try { - HttpGet httpGet = new HttpGet(mGetUrl); - HttpResponse response = null; - response = mHttpClient.execute(httpGet); - - // get the task list - String resString = getResponseContent(response.getEntity()); - String jsBegin = "_setup("; - String jsEnd = ")}"; - int begin = resString.indexOf(jsBegin); - int end = resString.lastIndexOf(jsEnd); - String jsString = null; - if (begin != -1 && end != -1 && begin < end) { - jsString = resString.substring(begin + jsBegin.length(), end); - } - JSONObject js = new JSONObject(jsString); - return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); - } catch (ClientProtocolException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("gettasklists: httpget failed"); - } catch (IOException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("gettasklists: httpget failed"); - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("get task lists: handing jasonobject failed"); - } - } - - /** - * 获取指定任务列表中的所有任务 - *

- * 从 Google Tasks 服务器获取指定任务列表中的所有任务。 - *

- * - * @param listGid 任务列表的 Google ID - * @return 包含该任务列表中所有任务信息的 JSON 数组 - * @throws NetworkFailureException 如果网络请求失败 - * @throws ActionFailureException 如果 JSON 处理失败 - */ - public JSONArray getTaskList(String listGid) throws NetworkFailureException { - commitUpdate(); - try { - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - JSONObject action = new JSONObject(); - - // action_list - action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); - action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); - action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); - action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); - actionList.put(action); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // client_version - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - JSONObject jsResponse = postRequest(jsPost); - return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("get task list: handing jsonobject failed"); - } - } - - /** - * 获取同步账户 - * - * @return 当前登录的 Google 账户 - */ - public Account getSyncAccount() { - return mAccount; - } - - /** - * 重置更新数组 - *

- * 清空待更新的节点队列,取消所有未提交的更新操作。 - *

- */ - public void resetUpdateArray() { - mUpdateArray = null; - } -} diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java b/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java deleted file mode 100644 index 6beb7a7..0000000 --- a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/remote/GTaskManager.java +++ /dev/null @@ -1,857 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * 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. - */ - -package net.micode.notes.gtask.remote; - -import android.app.Activity; -import android.content.ContentResolver; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.database.Cursor; -import android.util.Log; - -import net.micode.notes.R; -import net.micode.notes.data.Notes; -import net.micode.notes.data.Notes.DataColumns; -import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.gtask.data.MetaData; -import net.micode.notes.gtask.data.Node; -import net.micode.notes.gtask.data.SqlNote; -import net.micode.notes.gtask.data.Task; -import net.micode.notes.gtask.data.TaskList; -import net.micode.notes.gtask.exception.ActionFailureException; -import net.micode.notes.gtask.exception.NetworkFailureException; -import net.micode.notes.tool.DataUtils; -import net.micode.notes.tool.GTaskStringUtils; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; - - -/** - * Google Tasks 同步管理器 - *

- * 单例模式实现的同步管理器,负责本地笔记与 Google Tasks 之间的数据同步。 - * 提供完整的双向同步功能,包括文件夹、笔记的增删改查操作。 - * 支持同步状态管理、冲突解决和元数据维护。 - *

- */ -public class GTaskManager { - private static final String TAG = GTaskManager.class.getSimpleName(); - - /** 同步成功状态码 */ - public static final int STATE_SUCCESS = 0; - - /** 网络错误状态码 */ - public static final int STATE_NETWORK_ERROR = 1; - - /** 内部错误状态码 */ - public static final int STATE_INTERNAL_ERROR = 2; - - /** 同步进行中状态码 */ - public static final int STATE_SYNC_IN_PROGRESS = 3; - - /** 同步已取消状态码 */ - public static final int STATE_SYNC_CANCELLED = 4; - - private static GTaskManager mInstance = null; - - private Activity mActivity; - - private Context mContext; - - private ContentResolver mContentResolver; - - private boolean mSyncing; - - private boolean mCancelled; - - private HashMap mGTaskListHashMap; - - private HashMap mGTaskHashMap; - - private HashMap mMetaHashMap; - - private TaskList mMetaList; - - private HashSet mLocalDeleteIdMap; - - private HashMap mGidToNid; - - private HashMap mNidToGid; - - /** - * 私有构造函数 - *

- * 初始化所有成员变量,防止外部直接实例化。 - *

- */ - private GTaskManager() { - mSyncing = false; - mCancelled = false; - mGTaskListHashMap = new HashMap(); - mGTaskHashMap = new HashMap(); - mMetaHashMap = new HashMap(); - mMetaList = null; - mLocalDeleteIdMap = new HashSet(); - mGidToNid = new HashMap(); - mNidToGid = new HashMap(); - } - - /** - * 获取 GTaskManager 单例实例 - *

- * 使用双重检查锁定确保线程安全的单例实现。 - *

- * - * @return GTaskManager 单例实例 - */ - public static synchronized GTaskManager getInstance() { - if (mInstance == null) { - mInstance = new GTaskManager(); - } - return mInstance; - } - - /** - * 设置 Activity 上下文 - *

- * 用于获取 Google 账户的认证令牌。 - *

- * - * @param activity Activity 上下文 - */ - public synchronized void setActivityContext(Activity activity) { - // used for getting authtoken - mActivity = activity; - } - - /** - * 执行同步操作 - *

- * 执行本地笔记与 Google Tasks 之间的双向同步。 - * 包括登录 Google Tasks、初始化任务列表、同步内容等步骤。 - *

- * - * @param context 应用上下文 - * @param asyncTask 异步任务对象,用于发布进度 - * @return 同步状态码(STATE_SUCCESS、STATE_NETWORK_ERROR、STATE_INTERNAL_ERROR、STATE_SYNC_IN_PROGRESS 或 STATE_SYNC_CANCELLED) - */ - public int sync(Context context, GTaskASyncTask asyncTask) { - if (mSyncing) { - Log.d(TAG, "Sync is in progress"); - return STATE_SYNC_IN_PROGRESS; - } - mContext = context; - mContentResolver = mContext.getContentResolver(); - mSyncing = true; - mCancelled = false; - mGTaskListHashMap.clear(); - mGTaskHashMap.clear(); - mMetaHashMap.clear(); - mLocalDeleteIdMap.clear(); - mGidToNid.clear(); - mNidToGid.clear(); - - try { - GTaskClient client = GTaskClient.getInstance(); - client.resetUpdateArray(); - - // login google task - if (!mCancelled) { - if (!client.login(mActivity)) { - throw new NetworkFailureException("login google task failed"); - } - } - - // get the task list from google - asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); - initGTaskList(); - - // do content sync work - asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); - syncContent(); - } catch (NetworkFailureException e) { - Log.e(TAG, e.toString()); - return STATE_NETWORK_ERROR; - } catch (ActionFailureException e) { - Log.e(TAG, e.toString()); - return STATE_INTERNAL_ERROR; - } catch (Exception e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return STATE_INTERNAL_ERROR; - } finally { - mGTaskListHashMap.clear(); - mGTaskHashMap.clear(); - mMetaHashMap.clear(); - mLocalDeleteIdMap.clear(); - mGidToNid.clear(); - mNidToGid.clear(); - mSyncing = false; - } - - return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; - } - - private void initGTaskList() throws NetworkFailureException { - if (mCancelled) - return; - GTaskClient client = GTaskClient.getInstance(); - try { - JSONArray jsTaskLists = client.getTaskLists(); - - // init meta list first - mMetaList = null; - for (int i = 0; i < jsTaskLists.length(); i++) { - JSONObject object = jsTaskLists.getJSONObject(i); - String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); - String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); - - if (name - .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { - mMetaList = new TaskList(); - mMetaList.setContentByRemoteJSON(object); - - // load meta data - JSONArray jsMetas = client.getTaskList(gid); - for (int j = 0; j < jsMetas.length(); j++) { - object = (JSONObject) jsMetas.getJSONObject(j); - MetaData metaData = new MetaData(); - metaData.setContentByRemoteJSON(object); - if (metaData.isWorthSaving()) { - mMetaList.addChildTask(metaData); - if (metaData.getGid() != null) { - mMetaHashMap.put(metaData.getRelatedGid(), metaData); - } - } - } - } - } - - // create meta list if not existed - if (mMetaList == null) { - mMetaList = new TaskList(); - mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_META); - GTaskClient.getInstance().createTaskList(mMetaList); - } - - // init task list - for (int i = 0; i < jsTaskLists.length(); i++) { - JSONObject object = jsTaskLists.getJSONObject(i); - String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); - String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); - - if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) - && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_META)) { - TaskList tasklist = new TaskList(); - tasklist.setContentByRemoteJSON(object); - mGTaskListHashMap.put(gid, tasklist); - mGTaskHashMap.put(gid, tasklist); - - // load tasks - JSONArray jsTasks = client.getTaskList(gid); - for (int j = 0; j < jsTasks.length(); j++) { - object = (JSONObject) jsTasks.getJSONObject(j); - gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); - Task task = new Task(); - task.setContentByRemoteJSON(object); - if (task.isWorthSaving()) { - task.setMetaInfo(mMetaHashMap.get(gid)); - tasklist.addChildTask(task); - mGTaskHashMap.put(gid, task); - } - } - } - } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("initGTaskList: handing JSONObject failed"); - } - } - - private void syncContent() throws NetworkFailureException { - int syncType; - Cursor c = null; - String gid; - Node node; - - mLocalDeleteIdMap.clear(); - - if (mCancelled) { - return; - } - - // for local deleted note - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, - "(type<>? AND parent_id=?)", new String[] { - String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) - }, null); - if (c != null) { - while (c.moveToNext()) { - gid = c.getString(SqlNote.GTASK_ID_COLUMN); - node = mGTaskHashMap.get(gid); - if (node != null) { - mGTaskHashMap.remove(gid); - doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c); - } - - mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); - } - } else { - Log.w(TAG, "failed to query trash folder"); - } - } finally { - if (c != null) { - c.close(); - c = null; - } - } - - // sync folder first - syncFolder(); - - // for note existing in database - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, - "(type=? AND parent_id<>?)", new String[] { - String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER) - }, NoteColumns.TYPE + " DESC"); - if (c != null) { - while (c.moveToNext()) { - gid = c.getString(SqlNote.GTASK_ID_COLUMN); - node = mGTaskHashMap.get(gid); - if (node != null) { - mGTaskHashMap.remove(gid); - mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); - mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); - syncType = node.getSyncAction(c); - } else { - if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { - // local add - syncType = Node.SYNC_ACTION_ADD_REMOTE; - } else { - // remote delete - syncType = Node.SYNC_ACTION_DEL_LOCAL; - } - } - doContentSync(syncType, node, c); - } - } else { - Log.w(TAG, "failed to query existing note in database"); - } - - } finally { - if (c != null) { - c.close(); - c = null; - } - } - - // go through remaining items - Iterator> iter = mGTaskHashMap.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = iter.next(); - node = entry.getValue(); - doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); - } - - // mCancelled can be set by another thread, so we neet to check one by - // one - // clear local delete table - if (!mCancelled) { - if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) { - throw new ActionFailureException("failed to batch-delete local deleted notes"); - } - } - - // refresh local sync id - if (!mCancelled) { - GTaskClient.getInstance().commitUpdate(); - refreshLocalSyncId(); - } - - } - - private void syncFolder() throws NetworkFailureException { - Cursor c = null; - String gid; - Node node; - int syncType; - - if (mCancelled) { - return; - } - - // for root folder - try { - c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, - Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null); - if (c != null) { - c.moveToNext(); - gid = c.getString(SqlNote.GTASK_ID_COLUMN); - node = mGTaskHashMap.get(gid); - if (node != null) { - mGTaskHashMap.remove(gid); - mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER); - mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid); - // for system folder, only update remote name if necessary - if (!node.getName().equals( - GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) - doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); - } else { - doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); - } - } else { - Log.w(TAG, "failed to query root folder"); - } - } finally { - if (c != null) { - c.close(); - c = null; - } - } - - // for call-note folder - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)", - new String[] { - String.valueOf(Notes.ID_CALL_RECORD_FOLDER) - }, null); - if (c != null) { - if (c.moveToNext()) { - gid = c.getString(SqlNote.GTASK_ID_COLUMN); - node = mGTaskHashMap.get(gid); - if (node != null) { - mGTaskHashMap.remove(gid); - mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER); - mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid); - // for system folder, only update remote name if - // necessary - if (!node.getName().equals( - GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_CALL_NOTE)) - doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); - } else { - doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); - } - } - } else { - Log.w(TAG, "failed to query call note folder"); - } - } finally { - if (c != null) { - c.close(); - c = null; - } - } - - // for local existing folders - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, - "(type=? AND parent_id<>?)", new String[] { - String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER) - }, NoteColumns.TYPE + " DESC"); - if (c != null) { - while (c.moveToNext()) { - gid = c.getString(SqlNote.GTASK_ID_COLUMN); - node = mGTaskHashMap.get(gid); - if (node != null) { - mGTaskHashMap.remove(gid); - mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); - mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); - syncType = node.getSyncAction(c); - } else { - if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { - // local add - syncType = Node.SYNC_ACTION_ADD_REMOTE; - } else { - // remote delete - syncType = Node.SYNC_ACTION_DEL_LOCAL; - } - } - doContentSync(syncType, node, c); - } - } else { - Log.w(TAG, "failed to query existing folder"); - } - } finally { - if (c != null) { - c.close(); - c = null; - } - } - - // for remote add folders - Iterator> iter = mGTaskListHashMap.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = iter.next(); - gid = entry.getKey(); - node = entry.getValue(); - if (mGTaskHashMap.containsKey(gid)) { - mGTaskHashMap.remove(gid); - doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); - } - } - - if (!mCancelled) - GTaskClient.getInstance().commitUpdate(); - } - - private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException { - if (mCancelled) { - return; - } - - MetaData meta; - switch (syncType) { - case Node.SYNC_ACTION_ADD_LOCAL: - addLocalNode(node); - break; - case Node.SYNC_ACTION_ADD_REMOTE: - addRemoteNode(node, c); - break; - case Node.SYNC_ACTION_DEL_LOCAL: - meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN)); - if (meta != null) { - GTaskClient.getInstance().deleteNode(meta); - } - mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); - break; - case Node.SYNC_ACTION_DEL_REMOTE: - meta = mMetaHashMap.get(node.getGid()); - if (meta != null) { - GTaskClient.getInstance().deleteNode(meta); - } - GTaskClient.getInstance().deleteNode(node); - break; - case Node.SYNC_ACTION_UPDATE_LOCAL: - updateLocalNode(node, c); - break; - case Node.SYNC_ACTION_UPDATE_REMOTE: - updateRemoteNode(node, c); - break; - case Node.SYNC_ACTION_UPDATE_CONFLICT: - // merging both modifications maybe a good idea - // right now just use local update simply - updateRemoteNode(node, c); - break; - case Node.SYNC_ACTION_NONE: - break; - case Node.SYNC_ACTION_ERROR: - default: - throw new ActionFailureException("unkown sync action type"); - } - } - - private void addLocalNode(Node node) throws NetworkFailureException { - if (mCancelled) { - return; - } - - SqlNote sqlNote; - if (node instanceof TaskList) { - if (node.getName().equals( - GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) { - sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER); - } else if (node.getName().equals( - GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) { - sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER); - } else { - sqlNote = new SqlNote(mContext); - sqlNote.setContent(node.getLocalJSONFromContent()); - sqlNote.setParentId(Notes.ID_ROOT_FOLDER); - } - } else { - sqlNote = new SqlNote(mContext); - JSONObject js = node.getLocalJSONFromContent(); - try { - if (js.has(GTaskStringUtils.META_HEAD_NOTE)) { - JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); - if (note.has(NoteColumns.ID)) { - long id = note.getLong(NoteColumns.ID); - if (DataUtils.existInNoteDatabase(mContentResolver, id)) { - // the id is not available, have to create a new one - note.remove(NoteColumns.ID); - } - } - } - - if (js.has(GTaskStringUtils.META_HEAD_DATA)) { - JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); - for (int i = 0; i < dataArray.length(); i++) { - JSONObject data = dataArray.getJSONObject(i); - if (data.has(DataColumns.ID)) { - long dataId = data.getLong(DataColumns.ID); - if (DataUtils.existInDataDatabase(mContentResolver, dataId)) { - // the data id is not available, have to create - // a new one - data.remove(DataColumns.ID); - } - } - } - - } - } catch (JSONException e) { - Log.w(TAG, e.toString()); - e.printStackTrace(); - } - sqlNote.setContent(js); - - Long parentId = mGidToNid.get(((Task) node).getParent().getGid()); - if (parentId == null) { - Log.e(TAG, "cannot find task's parent id locally"); - throw new ActionFailureException("cannot add local node"); - } - sqlNote.setParentId(parentId.longValue()); - } - - // create the local node - sqlNote.setGtaskId(node.getGid()); - sqlNote.commit(false); - - // update gid-nid mapping - mGidToNid.put(node.getGid(), sqlNote.getId()); - mNidToGid.put(sqlNote.getId(), node.getGid()); - - // update meta - updateRemoteMeta(node.getGid(), sqlNote); - } - - private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException { - if (mCancelled) { - return; - } - - SqlNote sqlNote; - // update the note locally - sqlNote = new SqlNote(mContext, c); - sqlNote.setContent(node.getLocalJSONFromContent()); - - Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid()) - : new Long(Notes.ID_ROOT_FOLDER); - if (parentId == null) { - Log.e(TAG, "cannot find task's parent id locally"); - throw new ActionFailureException("cannot update local node"); - } - sqlNote.setParentId(parentId.longValue()); - sqlNote.commit(true); - - // update meta info - updateRemoteMeta(node.getGid(), sqlNote); - } - - private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException { - if (mCancelled) { - return; - } - - SqlNote sqlNote = new SqlNote(mContext, c); - Node n; - - // update remotely - if (sqlNote.isNoteType()) { - Task task = new Task(); - task.setContentByLocalJSON(sqlNote.getContent()); - - String parentGid = mNidToGid.get(sqlNote.getParentId()); - if (parentGid == null) { - Log.e(TAG, "cannot find task's parent tasklist"); - throw new ActionFailureException("cannot add remote task"); - } - mGTaskListHashMap.get(parentGid).addChildTask(task); - - GTaskClient.getInstance().createTask(task); - n = (Node) task; - - // add meta - updateRemoteMeta(task.getGid(), sqlNote); - } else { - TaskList tasklist = null; - - // we need to skip folder if it has already existed - String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX; - if (sqlNote.getId() == Notes.ID_ROOT_FOLDER) - folderName += GTaskStringUtils.FOLDER_DEFAULT; - else if (sqlNote.getId() == Notes.ID_CALL_RECORD_FOLDER) - folderName += GTaskStringUtils.FOLDER_CALL_NOTE; - else - folderName += sqlNote.getSnippet(); - - Iterator> iter = mGTaskListHashMap.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = iter.next(); - String gid = entry.getKey(); - TaskList list = entry.getValue(); - - if (list.getName().equals(folderName)) { - tasklist = list; - if (mGTaskHashMap.containsKey(gid)) { - mGTaskHashMap.remove(gid); - } - break; - } - } - - // no match we can add now - if (tasklist == null) { - tasklist = new TaskList(); - tasklist.setContentByLocalJSON(sqlNote.getContent()); - GTaskClient.getInstance().createTaskList(tasklist); - mGTaskListHashMap.put(tasklist.getGid(), tasklist); - } - n = (Node) tasklist; - } - - // update local note - sqlNote.setGtaskId(n.getGid()); - sqlNote.commit(false); - sqlNote.resetLocalModified(); - sqlNote.commit(true); - - // gid-id mapping - mGidToNid.put(n.getGid(), sqlNote.getId()); - mNidToGid.put(sqlNote.getId(), n.getGid()); - } - - private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException { - if (mCancelled) { - return; - } - - SqlNote sqlNote = new SqlNote(mContext, c); - - // update remotely - node.setContentByLocalJSON(sqlNote.getContent()); - GTaskClient.getInstance().addUpdateNode(node); - - // update meta - updateRemoteMeta(node.getGid(), sqlNote); - - // move task if necessary - if (sqlNote.isNoteType()) { - Task task = (Task) node; - TaskList preParentList = task.getParent(); - - String curParentGid = mNidToGid.get(sqlNote.getParentId()); - if (curParentGid == null) { - Log.e(TAG, "cannot find task's parent tasklist"); - throw new ActionFailureException("cannot update remote task"); - } - TaskList curParentList = mGTaskListHashMap.get(curParentGid); - - if (preParentList != curParentList) { - preParentList.removeChildTask(task); - curParentList.addChildTask(task); - GTaskClient.getInstance().moveTask(task, preParentList, curParentList); - } - } - - // clear local modified flag - sqlNote.resetLocalModified(); - sqlNote.commit(true); - } - - private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException { - if (sqlNote != null && sqlNote.isNoteType()) { - MetaData metaData = mMetaHashMap.get(gid); - if (metaData != null) { - metaData.setMeta(gid, sqlNote.getContent()); - GTaskClient.getInstance().addUpdateNode(metaData); - } else { - metaData = new MetaData(); - metaData.setMeta(gid, sqlNote.getContent()); - mMetaList.addChildTask(metaData); - mMetaHashMap.put(gid, metaData); - GTaskClient.getInstance().createTask(metaData); - } - } - } - - private void refreshLocalSyncId() throws NetworkFailureException { - if (mCancelled) { - return; - } - - // get the latest gtask list - mGTaskHashMap.clear(); - mGTaskListHashMap.clear(); - mMetaHashMap.clear(); - initGTaskList(); - - Cursor c = null; - try { - c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, - "(type<>? AND parent_id<>?)", new String[] { - String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) - }, NoteColumns.TYPE + " DESC"); - if (c != null) { - while (c.moveToNext()) { - String gid = c.getString(SqlNote.GTASK_ID_COLUMN); - Node node = mGTaskHashMap.get(gid); - if (node != null) { - mGTaskHashMap.remove(gid); - ContentValues values = new ContentValues(); - values.put(NoteColumns.SYNC_ID, node.getLastModified()); - mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, - c.getLong(SqlNote.ID_COLUMN)), values, null, null); - } else { - Log.e(TAG, "something is missed"); - throw new ActionFailureException( - "some local items don't have gid after sync"); - } - } - } else { - Log.w(TAG, "failed to query local note to refresh sync id"); - } - } finally { - if (c != null) { - c.close(); - c = null; - } - } - } - - /** - * 获取同步账户名称 - * - * @return 当前同步的 Google 账户名称 - */ - public String getSyncAccount() { - return mActivity == null ? null : GTaskClient.getInstance().getSyncAccount().name; - } - - /** - * 取消同步操作 - *

- * 设置取消标志,停止正在进行的同步操作。 - *

- */ - public void cancelSync() { - mCancelled = true; - } -} diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java b/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java deleted file mode 100644 index d207f97..0000000 --- a/src/Notesmaster/app/src/main/java/net/micode/notes/gtask/remote/GTaskSyncService.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * 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. - */ - -package net.micode.notes.gtask.remote; - -import android.app.Activity; -import android.app.Service; -import android.content.Context; -import android.content.Intent; -import android.os.Bundle; -import android.os.IBinder; - -/** - * Google Tasks 同步服务 - *

- * 负责管理本地笔记与 Google Tasks 之间的后台同步操作。 - * 通过异步任务执行同步,支持同步状态广播和进度更新。 - *

- */ -public class GTaskSyncService extends Service { - /** Intent 附加参数名称,用于指定同步操作类型 */ - public final static String ACTION_STRING_NAME = "sync_action_type"; - - /** 启动同步操作的 Action 值 */ - public final static int ACTION_START_SYNC = 0; - - /** 取消同步操作的 Action 值 */ - public final static int ACTION_CANCEL_SYNC = 1; - - /** 无效的 Action 值 */ - public final static int ACTION_INVALID = 2; - - /** 同步服务广播名称 */ - public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service"; - - /** 广播附加参数名称,用于标识是否正在同步 */ - public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing"; - - /** 广播附加参数名称,用于传递同步进度消息 */ - public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg"; - - /** 同步异步任务实例 */ - private static GTaskASyncTask mSyncTask = null; - - /** 同步进度消息 */ - private static String mSyncProgress = ""; - - /** - * 启动同步操作 - *

- * 创建并执行 GTaskASyncTask 异步任务,监听同步完成事件。 - * 同步完成后发送广播并停止服务。 - *

- */ - private void startSync() { - // 检查是否已有同步任务在运行 - if (mSyncTask == null) { - mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { - public void onComplete() { - // 清空同步任务引用 - mSyncTask = null; - // 发送同步完成广播 - sendBroadcast(""); - // 停止服务 - stopSelf(); - } - }); - // 发送同步开始广播 - sendBroadcast(""); - // 执行异步同步任务 - mSyncTask.execute(); - } - } - - /** - * 取消同步操作 - *

- * 如果存在正在运行的同步任务,则调用其 cancelSync() 方法取消同步。 - *

- */ - private void cancelSync() { - if (mSyncTask != null) { - // 取消异步同步任务 - mSyncTask.cancelSync(); - } - } - - /** - * 服务创建时的回调 - *

- * 初始化同步任务为 null。 - *

- */ - @Override - public void onCreate() { - mSyncTask = null; - } - - /** - * 服务启动命令的回调 - *

- * 根据 Intent 中的 Action 类型执行相应的同步操作。 - * 支持 ACTION_START_SYNC 和 ACTION_CANCEL_SYNC 两种操作。 - *

- * - * @param intent 启动服务的 Intent,包含 Action 类型参数 - * @param flags 启动标志 - * @param startId 启动 ID - * @return START_STICKY 表示服务被杀死后会自动重启 - */ - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - Bundle bundle = intent.getExtras(); - // 检查 Intent 是否包含 Action 参数 - if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { - // 根据 Action 类型执行相应操作 - switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { - case ACTION_START_SYNC: - startSync(); - break; - case ACTION_CANCEL_SYNC: - cancelSync(); - break; - default: - break; - } - return START_STICKY; - } - return super.onStartCommand(intent, flags, startId); - } - - /** - * 系统内存不足时的回调 - *

- * 取消正在进行的同步操作以释放资源。 - *

- */ - @Override - public void onLowMemory() { - if (mSyncTask != null) { - // 取消同步任务以释放内存 - mSyncTask.cancelSync(); - } - } - - /** - * 绑定服务的回调 - *

- * 本服务不支持绑定,返回 null。 - *

- * - * @param intent 绑定服务的 Intent - * @return null,表示不支持绑定 - */ - public IBinder onBind(Intent intent) { - return null; - } - - /** - * 发送同步状态广播 - *

- * 向应用发送广播,包含当前同步状态和进度消息。 - *

- * - * @param msg 同步进度消息 - */ - public void sendBroadcast(String msg) { - // 更新同步进度消息 - mSyncProgress = msg; - Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); - // 添加是否正在同步的标志 - intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); - // 添加进度消息 - intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); - // 发送广播 - sendBroadcast(intent); - } - - /** - * 启动同步服务 - *

- * 设置 Activity 上下文到 GTaskManager,然后启动同步服务执行同步操作。 - *

- * - * @param activity Activity 上下文,用于获取 Google 账户认证信息 - */ - public static void startSync(Activity activity) { - // 设置 Activity 上下文用于账户认证 - GTaskManager.getInstance().setActivityContext(activity); - Intent intent = new Intent(activity, GTaskSyncService.class); - intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); - // 启动同步服务 - activity.startService(intent); - } - - /** - * 取消同步服务 - *

- * 启动同步服务并发送取消同步的命令。 - *

- * - * @param context 应用上下文 - */ - public static void cancelSync(Context context) { - Intent intent = new Intent(context, GTaskSyncService.class); - intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); - // 启动服务发送取消命令 - context.startService(intent); - } - - /** - * 检查是否正在同步 - * - * @return 如果正在同步返回 true,否则返回 false - */ - public static boolean isSyncing() { - return mSyncTask != null; - } - - /** - * 获取同步进度消息 - * - * @return 当前同步进度消息字符串 - */ - public static String getProgressString() { - return mSyncProgress; - } -} diff --git a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java b/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java index 2de6ec3..76aebfa 100644 --- a/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java +++ b/src/Notesmaster/app/src/main/java/net/micode/notes/ui/NotesPreferenceActivity.java @@ -45,7 +45,8 @@ import android.widget.Toast; import net.micode.notes.R; import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.NoteColumns; -import net.micode.notes.gtask.remote.GTaskSyncService; +// Google Tasks同步功能已禁用 +// import net.micode.notes.gtask.remote.GTaskSyncService; import net.micode.notes.tool.SecurityManager; import net.micode.notes.ui.PasswordActivity; @@ -141,17 +142,18 @@ public class NotesPreferenceActivity extends PreferenceActivity { addPreferencesFromResource(R.xml.preferences); mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); - mReceiver = new GTaskReceiver(); - IntentFilter filter = new IntentFilter(); - filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); + // Google Tasks同步功能已禁用 + // mReceiver = new GTaskReceiver(); + // IntentFilter filter = new IntentFilter(); + // filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); //registerReceiver(mReceiver, filter); - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) { - // Android 13 (API 33) 及以上版本需要指定导出标志 - registerReceiver(mReceiver, filter, Context.RECEIVER_NOT_EXPORTED); - } else { - // Android 12 及以下版本使用旧方法 - registerReceiver(mReceiver, filter); - } + // if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) { + // // Android 13 (API 33) 及以上版本需要指定导出标志 + // registerReceiver(mReceiver, filter, Context.RECEIVER_NOT_EXPORTED); + // } else { + // // Android 12 及以下版本使用旧方法 + // registerReceiver(mReceiver, filter); + // } mOriAccounts = null; View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); getListView().addHeaderView(header, null, true); @@ -202,9 +204,10 @@ public class NotesPreferenceActivity extends PreferenceActivity { */ @Override protected void onDestroy() { - if (mReceiver != null) { - unregisterReceiver(mReceiver); - } + // Google Tasks同步功能已禁用 + // if (mReceiver != null) { + // unregisterReceiver(mReceiver); + // } super.onDestroy(); } @@ -283,20 +286,24 @@ public class NotesPreferenceActivity extends PreferenceActivity { accountPref.setSummary(getString(R.string.preferences_account_summary)); accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { - if (!GTaskSyncService.isSyncing()) { - if (TextUtils.isEmpty(defaultAccount)) { - // the first time to set account - showSelectAccountAlertDialog(); - } else { - // if the account has already been set, we need to promp - // user about the risk - showChangeAccountConfirmAlertDialog(); - } - } else { - Toast.makeText(NotesPreferenceActivity.this, - R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT) - .show(); - } + // Google Tasks同步功能已禁用 + // if (!GTaskSyncService.isSyncing()) { + // if (TextUtils.isEmpty(defaultAccount)) { + // // first time to set account + // showSelectAccountAlertDialog(); + // } else { + // // if account has already been set, we need to promp + // // user about risk + // showChangeAccountConfirmAlertDialog(); + // } + // } else { + // Toast.makeText(NotesPreferenceActivity.this, + // R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT) + // .show(); + // } + Toast.makeText(NotesPreferenceActivity.this, + "Google Tasks同步功能已禁用", Toast.LENGTH_SHORT) + .show(); return true; } }); @@ -319,39 +326,47 @@ public class NotesPreferenceActivity extends PreferenceActivity { Button syncButton = (Button) findViewById(R.id.preference_sync_button); TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview); + // Google Tasks同步功能已禁用 // set button state - if (GTaskSyncService.isSyncing()) { - syncButton.setText(getString(R.string.preferences_button_sync_cancel)); - syncButton.setOnClickListener(new View.OnClickListener() { - public void onClick(View v) { - GTaskSyncService.cancelSync(NotesPreferenceActivity.this); - } - }); - } else { - syncButton.setText(getString(R.string.preferences_button_sync_immediately)); - syncButton.setOnClickListener(new View.OnClickListener() { - public void onClick(View v) { - GTaskSyncService.startSync(NotesPreferenceActivity.this); - } - }); - } - syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); + // if (GTaskSyncService.isSyncing()) { + // syncButton.setText(getString(R.string.preferences_button_sync_cancel)); + // syncButton.setOnClickListener(new View.OnClickListener() { + // public void onClick(View v) { + // GTaskSyncService.cancelSync(NotesPreferenceActivity.this); + // } + // }); + // } else { + // syncButton.setText(getString(R.string.preferences_button_sync_immediately)); + // syncButton.setOnClickListener(new View.OnClickListener() { + // public void onClick(View v) { + // GTaskSyncService.startSync(NotesPreferenceActivity.this); + // } + // }); + // } + // syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); + + // 禁用同步按钮 + syncButton.setEnabled(false); + syncButton.setText("同步功能已禁用"); // set last sync time - if (GTaskSyncService.isSyncing()) { - lastSyncTimeView.setText(GTaskSyncService.getProgressString()); - lastSyncTimeView.setVisibility(View.VISIBLE); - } else { - long lastSyncTime = getLastSyncTime(this); - if (lastSyncTime != 0) { - lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time, - DateFormat.format(getString(R.string.preferences_last_sync_time_format), - lastSyncTime))); - lastSyncTimeView.setVisibility(View.VISIBLE); - } else { - lastSyncTimeView.setVisibility(View.GONE); - } - } + // if (GTaskSyncService.isSyncing()) { + // lastSyncTimeView.setText(GTaskSyncService.getProgressString()); + // lastSyncTimeView.setVisibility(View.VISIBLE); + // } else { + // long lastSyncTime = getLastSyncTime(this); + // if (lastSyncTime != 0) { + // lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time, + // DateFormat.format(getString(R.string.preferences_last_sync_time_format), + // lastSyncTime))); + // lastSyncTimeView.setVisibility(View.VISIBLE); + // } else { + // lastSyncTimeView.setVisibility(View.GONE); + // } + // } + + lastSyncTimeView.setText("Google Tasks同步功能已禁用"); + lastSyncTimeView.setVisibility(View.VISIBLE); } /** @@ -613,11 +628,12 @@ public class NotesPreferenceActivity extends PreferenceActivity { @Override public void onReceive(Context context, Intent intent) { refreshUI(); - if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) { - TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview); - syncStatus.setText(intent - .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); - } + // Google Tasks同步功能已禁用 + // if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) { + // TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview); + // syncStatus.setText(intent + // .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); + // } } } -- 2.34.1