From 9d4fb1a67a6eb72822ff478ede2b83e7fd0c6980 Mon Sep 17 00:00:00 2001 From: fanshuang <2963071932qq.com> Date: Thu, 26 Dec 2024 16:34:33 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AF=B9gtask=E5=8C=85=E7=9A=84=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/net/micode/notes/gtask/data/MetaData.java | 84 ++- src/net/micode/notes/gtask/data/Node.java | 258 +++++--- src/net/micode/notes/gtask/data/SqlData.java | 125 ++-- src/net/micode/notes/gtask/data/SqlNote.java | 393 ++++++++---- src/net/micode/notes/gtask/data/Task.java | 366 ++++++----- src/net/micode/notes/gtask/data/TaskList.java | 443 ++++++++----- .../exception/ActionFailureException.java | 46 +- .../exception/NetworkFailureException.java | 46 +- .../notes/gtask/remote/GTaskASyncTask.java | 110 ++-- .../notes/gtask/remote/GTaskClient.java | 404 ++++++------ .../notes/gtask/remote/GTaskManager.java | 603 ++++++------------ .../notes/gtask/remote/GTaskSyncService.java | 116 +++- 12 files changed, 1705 insertions(+), 1289 deletions(-) diff --git a/src/net/micode/notes/gtask/data/MetaData.java b/src/net/micode/notes/gtask/data/MetaData.java index 3a2050b..60ef9ff 100644 --- a/src/net/micode/notes/gtask/data/MetaData.java +++ b/src/net/micode/notes/gtask/data/MetaData.java @@ -1,20 +1,21 @@ -/* - * 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. - */ +```java + /* + * 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; + package net.micode.notes.gtask.data; import android.database.Cursor; import android.util.Log; @@ -24,14 +25,27 @@ import net.micode.notes.tool.GTaskStringUtils; import org.json.JSONException; import org.json.JSONObject; - +/** + * MetaData 类继承自 Task,用于处理与任务相关的元数据。 + * 主要功能包括设置和获取与任务关联的全局唯一标识符(GID)。 + */ public class MetaData extends Task { private final static String TAG = MetaData.class.getSimpleName(); + /** + * 存储与任务关联的全局唯一标识符(GID)。 + */ private String mRelatedGid = null; + /** + * 设置任务的元数据信息,并将 GID 添加到元数据中。 + * + * @param gid 任务的全局唯一标识符(GID) + * @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"); @@ -40,20 +54,36 @@ public class MetaData extends Task { setName(GTaskStringUtils.META_NOTE_NAME); } + /** + * 获取与任务关联的全局唯一标识符(GID)。 + * + * @return 返回任务的 GID + */ public String getRelatedGid() { return mRelatedGid; } + /** + * 判断是否有值得保存的笔记内容。 + * + * @return 如果有笔记内容则返回 true,否则返回 false + */ @Override public boolean isWorthSaving() { return getNotes() != null; } + /** + * 通过远程 JSON 数据设置任务内容,并解析出 GID。 + * + * @param js 包含任务内容的 JSON 对象 + */ @Override public void setContentByRemoteJSON(JSONObject js) { super.setContentByRemoteJSON(js); if (getNotes() != null) { try { + // 解析笔记内容中的元数据并提取 GID JSONObject metaInfo = new JSONObject(getNotes().trim()); mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); } catch (JSONException e) { @@ -63,20 +93,36 @@ public class MetaData extends Task { } } + /** + * 本地 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 数据的方法不应被调用。 + * + * @throws IllegalAccessError 抛出异常表示该方法不应被调用 + */ @Override public JSONObject getLocalJSONFromContent() { throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); } + /** + * 获取同步操作的方法不应被调用。 + * + * @param c 游标对象 + * @throws IllegalAccessError 抛出异常表示该方法不应被调用 + */ @Override public int getSyncAction(Cursor c) { throw new IllegalAccessError("MetaData:getSyncAction should not be called"); } - } +``` diff --git a/src/net/micode/notes/gtask/data/Node.java b/src/net/micode/notes/gtask/data/Node.java index 63950e0..b6c5785 100644 --- a/src/net/micode/notes/gtask/data/Node.java +++ b/src/net/micode/notes/gtask/data/Node.java @@ -21,81 +21,195 @@ import android.database.Cursor; import org.json.JSONObject; 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; - - private String mGid; - - private String mName; - - private long mLastModified; - - private boolean mDeleted; - - public Node() { - mGid = null; - mName = ""; - mLastModified = 0; - mDeleted = false; - } - - public abstract JSONObject getCreateAction(int actionId); - - public abstract JSONObject getUpdateAction(int actionId); - - public abstract void setContentByRemoteJSON(JSONObject js); - - public abstract void setContentByLocalJSON(JSONObject js); - - public abstract JSONObject getLocalJSONFromContent(); - - public abstract int getSyncAction(Cursor c); - - public void setGid(String gid) { - this.mGid = gid; - } - - public void setName(String name) { - this.mName = name; - } - - public void setLastModified(long lastModified) { - this.mLastModified = lastModified; - } - - public void setDeleted(boolean deleted) { - this.mDeleted = deleted; - } - - public String getGid() { - return this.mGid; - } +package net.micode.notes.gtask.data; - public String getName() { - return this.mName; - } +import android.database.Cursor; - public long getLastModified() { - return this.mLastModified; - } +import org.json.JSONObject; - public boolean getDeleted() { - return this.mDeleted; + /** + * 表示任务节点的抽象类,用于同步和管理任务数据。 + * 包含了与任务相关的属性和方法,支持本地和远程数据的同步操作。 + */ + 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; + + private String mGid; // 任务的全局唯一标识符 + private String mName; // 任务名称 + private long mLastModified; // 最后修改时间 + private boolean mDeleted; // 是否已删除 + + /** + * 构造函数,初始化任务节点的基本属性。 + */ + public Node() { + mGid = null; + mName = ""; + mLastModified = 0; + mDeleted = false; + } + + /** + * 获取创建操作的 JSON 对象。 + * + * @param actionId 操作类型 ID + * @return 创建操作的 JSON 对象 + */ + public abstract JSONObject getCreateAction(int actionId); + + /** + * 获取更新操作的 JSON 对象。 + * + * @param actionId 操作类型 ID + * @return 更新操作的 JSON 对象 + */ + public abstract JSONObject getUpdateAction(int actionId); + + /** + * 根据远程 JSON 数据设置任务内容。 + * + * @param js 远程 JSON 数据 + */ + public abstract void setContentByRemoteJSON(JSONObject js); + + /** + * 根据本地 JSON 数据设置任务内容。 + * + * @param js 本地 JSON 数据 + */ + public abstract void setContentByLocalJSON(JSONObject js); + + /** + * 将任务内容转换为本地 JSON 对象。 + * + * @return 任务内容的本地 JSON 对象 + */ + public abstract JSONObject getLocalJSONFromContent(); + + /** + * 根据数据库游标获取同步操作类型。 + * + * @param c 数据库游标 + * @return 同步操作类型 + */ + public abstract int getSyncAction(Cursor c); + + /** + * 设置任务的全局唯一标识符。 + * + * @param gid 全局唯一标识符 + */ + 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 是否已删除 + */ + public void setDeleted(boolean deleted) { + this.mDeleted = deleted; + } + + /** + * 获取任务的全局唯一标识符。 + * + * @return 全局唯一标识符 + */ + public String getGid() { + return this.mGid; + } + + /** + * 获取任务名称。 + * + * @return 任务名称 + */ + public String getName() { + return this.mName; + } + + /** + * 获取任务的最后修改时间。 + * + * @return 最后修改时间 + */ + public long getLastModified() { + return this.mLastModified; + } + + /** + * 获取任务是否已删除。 + * + * @return 是否已删除 + */ + public boolean getDeleted() { + return this.mDeleted; + } } -} +} \ No newline at end of file diff --git a/src/net/micode/notes/gtask/data/SqlData.java b/src/net/micode/notes/gtask/data/SqlData.java index d3ec3be..d17bf8a 100644 --- a/src/net/micode/notes/gtask/data/SqlData.java +++ b/src/net/micode/notes/gtask/data/SqlData.java @@ -1,20 +1,4 @@ -/* - * 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; + package net.micode.notes.gtask.data; import android.content.ContentResolver; import android.content.ContentUris; @@ -28,49 +12,67 @@ 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; - +/** + * SqlData 类用于处理与数据库交互的任务数据。 + * 包含了从 JSON 对象加载数据、将数据保存到数据库以及获取和设置任务数据的方法。 + */ public class SqlData { - private static final String TAG = SqlData.class.getSimpleName(); + private static final String TAG = SqlData.class.getSimpleName(); // 日志标签 - private static final int INVALID_ID = -99999; + private static final int INVALID_ID = -99999; // 无效的 ID,表示未初始化或无效的数据 + /** + * 数据库查询投影,包含需要查询的列名。 + */ 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; - + private ContentResolver mContentResolver; // 内容解析器,用于与内容提供者交互 + private boolean mIsCreate; // 标记是否为创建操作 + private long mDataId; // 数据 ID + private String mDataMimeType; // 数据 MIME 类型 + private String mDataContent; // 数据内容 + private long mDataContentData1; // 数据字段1 + private String mDataContentData3; // 数据字段3 + private ContentValues mDiffDataValues; // 用于存储要更新的字段值 + + /** + * 构造函数,初始化一个新的 SqlData 实例。 + * + * @param context 上下文对象 + */ public SqlData(Context context) { mContentResolver = context.getContentResolver(); mIsCreate = true; @@ -82,6 +84,12 @@ public class SqlData { mDiffDataValues = new ContentValues(); } + /** + * 构造函数,从游标加载现有数据并初始化 SqlData 实例。 + * + * @param context 上下文对象 + * @param c 游标对象 + */ public SqlData(Context context, Cursor c) { mContentResolver = context.getContentResolver(); mIsCreate = false; @@ -89,6 +97,11 @@ public class SqlData { mDiffDataValues = new ContentValues(); } + /** + * 从游标中加载数据。 + * + * @param c 游标对象 + */ private void loadFromCursor(Cursor c) { mDataId = c.getLong(DATA_ID_COLUMN); mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); @@ -97,6 +110,12 @@ public class SqlData { mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); } + /** + * 从 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) { @@ -130,9 +149,15 @@ public class SqlData { mDataContentData3 = dataContentData3; } + /** + * 将当前数据转换为 JSON 对象。 + * + * @return JSON 对象 + * @throws JSONException 如果生成 JSON 失败 + */ public JSONObject getContent() throws JSONException { if (mIsCreate) { - Log.e(TAG, "it seems that we haven't created this in database yet"); + Log.e(TAG, "似乎我们还没有在数据库中创建此数据"); return null; } JSONObject js = new JSONObject(); @@ -144,8 +169,14 @@ public class SqlData { return js; } + /** + * 将数据提交到数据库。 + * + * @param noteId 笔记 ID + * @param validateVersion 是否验证版本号 + * @param version 版本号 + */ public void commit(long noteId, boolean validateVersion, long version) { - if (mIsCreate) { if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) { mDiffDataValues.remove(DataColumns.ID); @@ -156,8 +187,8 @@ public class SqlData { 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"); + Log.e(TAG, "获取笔记 ID 错误:" + e.toString()); + throw new ActionFailureException("创建笔记失败"); } } else { if (mDiffDataValues.size() > 0) { @@ -167,14 +198,14 @@ public class SqlData { 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 + Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, + " ? in (SELECT " + NoteColumns.ID + " FROM " + Notes.TABLE_NAME + " 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"); + Log.w(TAG, "没有更新。可能是用户在同步时修改了笔记"); } } } @@ -183,7 +214,13 @@ public class SqlData { mIsCreate = false; } + /** + * 获取数据 ID。 + * + * @return 数据 ID + */ public long getId() { return mDataId; } } + diff --git a/src/net/micode/notes/gtask/data/SqlNote.java b/src/net/micode/notes/gtask/data/SqlNote.java index 79a4095..d7f8ece 100644 --- a/src/net/micode/notes/gtask/data/SqlNote.java +++ b/src/net/micode/notes/gtask/data/SqlNote.java @@ -1,49 +1,29 @@ -/* - * 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.data.SqlData; 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; - - +import javax.naming.Context; +import java.awt.*; +import java.util.ArrayList; /** + * SqlNote 类用于表示和操作笔记对象,包括创建、更新和查询笔记数据。 + */ 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[] { + /** + * 笔记的投影字段数组,定义了从数据库中查询笔记时需要的列。 + */ + 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, @@ -52,76 +32,122 @@ public class SqlNote { NoteColumns.VERSION }; + /** + * 定义投影字段数组中各列的索引位置。 + */ public static final int ID_COLUMN = 0; - public static final int ALERTED_DATE_COLUMN = 1; - 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; - public static final int PARENT_ID_COLUMN = 7; - public static final int SNIPPET_COLUMN = 8; - public static final int TYPE_COLUMN = 9; - public static final int WIDGET_ID_COLUMN = 10; - public static final int WIDGET_TYPE_COLUMN = 11; - public static final int SYNC_ID_COLUMN = 12; - public static final int LOCAL_MODIFIED_COLUMN = 13; - public static final int ORIGIN_PARENT_ID_COLUMN = 14; - 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; + /** + * 背景颜色 ID。 + */ private int mBgColorId; + /** + * 创建日期。 + */ private long mCreatedDate; + /** + * 是否包含附件。 + */ private int mHasAttachment; + /** + * 修改日期。 + */ private long mModifiedDate; + /** + * 父级笔记 ID。 + */ private long mParentId; + /** + * 笔记片段。 + */ private String mSnippet; + /** + * 笔记类型。 + */ private int mType; + /** + * 小部件 ID。 + */ private int mWidgetId; + /** + * 小部件类型。 + */ private int mWidgetType; + /** + * 原始父级笔记 ID。 + */ private long mOriginParent; + /** + * 笔记版本号。 + */ private long mVersion; + /** + * 存储差异笔记值的 ContentValues 对象。 + */ private ContentValues mDiffNoteValues; + /** + * 存储笔记数据的列表。 + */ private ArrayList mDataList; + /** + * 构造函数,用于创建新的 SqlNote 实例。 + * + * @param context 应用程序上下文。 + */ public SqlNote(Context context) { mContext = context; mContentResolver = context.getContentResolver(); @@ -143,6 +169,12 @@ public class SqlNote { mDataList = new ArrayList(); } + /** + * 构造函数,用于从游标加载现有笔记数据。 + * + * @param context 应用程序上下文。 + * @param c 包含笔记数据的游标。 + */ public SqlNote(Context context, Cursor c) { mContext = context; mContentResolver = context.getContentResolver(); @@ -154,6 +186,12 @@ public class SqlNote { mDiffNoteValues = new ContentValues(); } + /** + * 构造函数,用于通过笔记 ID 加载现有笔记数据。 + * + * @param context 应用程序上下文。 + * @param id 笔记的唯一标识符。 + */ public SqlNote(Context context, long id) { mContext = context; mContentResolver = context.getContentResolver(); @@ -163,16 +201,18 @@ public class SqlNote { if (mType == Notes.TYPE_NOTE) loadDataContent(); mDiffNoteValues = new ContentValues(); - } + /** + * 通过笔记 ID 从内容提供者加载笔记数据。 + * + * @param 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); + new String[]{String.valueOf(id)}, null); if (c != null) { c.moveToNext(); loadFromCursor(c); @@ -185,6 +225,11 @@ public class SqlNote { } } + /** + * 从游标加载笔记数据。 + * + * @param c 包含笔记数据的游标。 + */ private void loadFromCursor(Cursor c) { mId = c.getLong(ID_COLUMN); mAlertDate = c.getLong(ALERTED_DATE_COLUMN); @@ -200,14 +245,15 @@ public class SqlNote { mVersion = c.getLong(VERSION_COLUMN); } + /** + * 加载笔记的内容数据。 + */ 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); + "(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"); @@ -226,22 +272,26 @@ public class SqlNote { } } + /** + * 设置笔记内容,从 JSON 对象中解析并更新笔记属性。 + * + * @param js 包含笔记内容的 JSON 对象。 + * @return 返回设置是否成功。 + */ 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) : ""; + // 对于文件夹,我们只能更新片段和类型 + 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; + int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE; if (mIsCreate || mType != type) { mDiffNoteValues.put(NoteColumns.TYPE, type); } @@ -254,78 +304,67 @@ public class SqlNote { } mId = id; - long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note - .getLong(NoteColumns.ALERTED_DATE) : 0; + 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); + 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(); + 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; + 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(); + 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; + 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) : ""; + 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; + 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; + 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; + 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; + 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); } @@ -359,6 +398,11 @@ public class SqlNote { return true; } + /** + * 获取笔记内容,将笔记属性转换为 JSON 对象。 + * + * @return 返回包含笔记内容的 JSON 对象。 + */ public JSONObject getContent() { try { JSONObject js = new JSONObject(); @@ -407,99 +451,170 @@ public class SqlNote { return null; } + /** + * 设置笔记的父级 ID。 + * + * @param id 父级笔记的唯一标识符。 + */ public void setParentId(long id) { mParentId = id; mDiffNoteValues.put(NoteColumns.PARENT_ID, id); } + /** + * 设置笔记的 GTask ID。 + * + * @param gid GTask ID。 + */ public void setGtaskId(String gid) { mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); } + /** + * 设置笔记的同步 ID。 + * + * @param syncId 同步 ID。 + */ public void setSyncId(long syncId) { mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); } + /** + * 重置本地修改标记。 + */ public void resetLocalModified() { mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); } + /** + * 获取笔记的唯一标识符。 + * + * @return 返回笔记的唯一标识符。 + */ public long getId() { return mId; } + /** + * 获取笔记的父级 ID。 + * + * @return 返回父级笔记的唯一标识符。 + */ public long getParentId() { return mParentId; } + /** + * 获取笔记片段。 + * + * @return 返回笔记片段。 + */ public String getSnippet() { return mSnippet; } + /** + * 检查笔记是否为普通笔记类型。 + * + * @return 如果是普通笔记类型返回 true,否则返回 false。 + */ public boolean isNoteType() { return mType == Notes.TYPE_NOTE; } +/** + * 提交笔记更改到内容提供者。 + * + * @param validateVersion 是否验证版本号。 + */ +public void commit(boolean validateVersion) { + if (mIsCreate) { + // 如果是新创建的笔记,插入数据并获取生成的 ID + if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { + mDiffNoteValues.remove(NoteColumns.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, "获取笔记 ID 错误: " + e.toString()); + throw new ActionFailureException("创建笔记失败"); + } + if (mId == 0) { + throw new IllegalStateException("创建线程 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 { + // 检查笔记 ID 是否有效 + if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) { + Log.e(TAG, "不存在此笔记"); + throw new IllegalStateException("尝试使用无效 ID 更新笔记"); + } - 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 (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 (result == 0) { + Log.w(TAG, "没有进行任何更新。可能是用户在同步时修改了笔记"); } + } - if (mType == Notes.TYPE_NOTE) { - for (SqlData sqlData : mDataList) { - sqlData.commit(mId, validateVersion, mVersion); - } + // 如果是普通笔记类型,提交笔记内容数据 + if (mType == Notes.TYPE_NOTE) { + for (SqlData sqlData : mDataList) { + sqlData.commit(mId, validateVersion, mVersion); } } + } - // refresh local info - loadFromCursor(mId); - if (mType == Notes.TYPE_NOTE) - loadDataContent(); + // 刷新本地信息 + loadFromCursor(mId); + if (mType == Notes.TYPE_NOTE) + loadDataContent(); - mDiffNoteValues.clear(); - mIsCreate = false; - } + // 清空差异值,并标记为已创建 + mDiffNoteValues.clear(); + mIsCreate = false; } +} + + 注释解释 + +1. 检查笔记 ID 是否有效: + - 如果笔记 ID 小于等于 0 且不是根文件夹或通话记录文件夹,则抛出异常,提示尝试使用无效 ID 更新笔记。 + +2. 更新笔记数据: + - 如果 `mDiffNoteValues` 中有需要更新的数据,则增加版本号 `mVersion`。 + - 根据是否验证版本号,选择不同的更新条件: + - 不验证版本号时,直接根据笔记 ID 更新。 + - 验证版本号时,确保笔记版本号小于等于当前版本号。 + - 记录更新结果,如果没有任何更新,日志警告可能用户在同步时修改了笔记。 + +3. 提交笔记内容数据: + - 如果是普通笔记类型(`Notes.TYPE_NOTE`),则遍历 `mDataList` 并提交每个 `SqlData` 的内容。 + +4. 刷新本地信息: + - 通过 `loadFromCursor` 方法重新加载笔记数据。 + - 如果是普通笔记类型,加载笔记的内容数据。 + +5. 清理和标记: + - 清空 `mDiffNoteValues`,防止重复提交。 + - 将 `mIsCreate` 标记为 `false`,表示笔记已经创建或更新完成。 \ No newline at end of file diff --git a/src/net/micode/notes/gtask/data/Task.java b/src/net/micode/notes/gtask/data/Task.java index 6a19454..2b086c9 100644 --- a/src/net/micode/notes/gtask/data/Task.java +++ b/src/net/micode/notes/gtask/data/Task.java @@ -1,50 +1,26 @@ -/* - * 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; - - +// Task类继承自Node类,用于表示一个任务对象 public class Task extends Node { + // 日志标签,用于标识日志信息来源 private static final String TAG = Task.class.getSimpleName(); + // 表示任务是否已完成 private boolean mCompleted; + // 任务的备注信息 private String mNotes; + // 任务的元信息,使用JSONObject存储 private JSONObject mMetaInfo; + // 任务的前一个兄弟任务,用于任务排序 private Task mPriorSibling; + // 任务所属的任务列表 private TaskList mParent; + // Task类的构造方法,初始化任务的默认状态 public Task() { super(); mCompleted = false; @@ -54,6 +30,12 @@ public class Task extends Node { mMetaInfo = null; } + /** + * 生成任务创建操作的JSON对象 + * @param actionId 操作ID + * @return 返回表示创建操作的JSONObject + * @throws ActionFailureException 如果JSON对象生成失败,则抛出此异常 + */ public JSONObject getCreateAction(int actionId) { JSONObject js = new JSONObject(); @@ -103,6 +85,12 @@ public class Task extends Node { return js; } + /** + * 生成任务更新操作的JSON对象 + * @param actionId 操作ID + * @return 返回表示更新操作的JSONObject + * @throws ActionFailureException 如果JSON对象生成失败,则抛出此异常 + */ public JSONObject getUpdateAction(int actionId) { JSONObject js = new JSONObject(); @@ -135,6 +123,11 @@ public class Task extends Node { return js; } + /** + * 通过远程JSON对象设置任务内容 + * @param js 远程JSON对象,包含任务的相关信息 + * @throws ActionFailureException 如果设置内容失败,则抛出此异常 + */ public void setContentByRemoteJSON(JSONObject js) { if (js != null) { try { @@ -175,177 +168,220 @@ public class Task extends Node { } } + /** + * 通过本地JSON对象设置任务内容 + * @param js 本地JSON对象,包含任务的相关信息 + * @throws ActionFailureException 如果设置内容失败,则抛出此异常 + */ 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); +// 当没有可用内容时记录警告信息 +Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); +} + +try { + // 从JSON对象中获取笔记和数据数组 + 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; + // 检查笔记类型是否无效 + 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) { + // 记录并打印JSONException的堆栈跟踪 + Log.e(TAG, e.toString()); + e.printStackTrace(); +} +``` +/** + * 从内容生成本地使用的JSON对象 + * + * @return 表示笔记内容的JSONObject,如果内容为空则返回null + */ +public JSONObject getLocalJSONFromContent() { + String name = getName(); + try { + // 处理从网页创建的新任务 + if (mMetaInfo == null) { + if (name == null) { + Log.w(TAG, "the note seems to be an empty one"); + return null; } + // 构建新的笔记JSON对象 + 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 { + // 处理已同步的任务 + 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)) { - setName(data.getString(DataColumns.CONTENT)); + data.put(DataColumns.CONTENT, getName()); break; } } - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); + note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); + return mMetaInfo; } + } catch (JSONException e) { + // 记录并打印JSONException的堆栈跟踪 + Log.e(TAG, e.toString()); + e.printStackTrace(); + return null; } - - public JSONObject getLocalJSONFromContent() { - String name = getName(); +} +/** + * 设置任务的元信息 + * + * @param metaData 包含笔记信息的MetaData对象 + */ +public void setMetaInfo(MetaData metaData) { + if (metaData != null && metaData.getNotes() != null) { 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; - } + // 将笔记信息转换为JSON对象 + mMetaInfo = new JSONObject(metaData.getNotes()); } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return null; + // 转换失败时记录错误并将mMetaInfo设置为null + Log.w(TAG, e.toString()); + mMetaInfo = null; } } +} +``` +```java +/** + * 根据当前状态和数据库游标确定同步操作 + * + * @param c 指向数据库中笔记数据的游标 + * @return 表示要执行的同步操作的整数 + */ +public int getSyncAction(Cursor c) { + try { + // 从mMetaInfo中获取笔记信息 + JSONObject noteInfo = null; + if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { + noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + } - 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; - } + // 根据笔记信息确定同步操作 + if (noteInfo == null) { + Log.w(TAG, "it seems that note meta has been deleted"); + return SYNC_ACTION_UPDATE_REMOTE; } - } - 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.has(NoteColumns.ID)) { + Log.w(TAG, "remote note id seems to be deleted"); + return SYNC_ACTION_UPDATE_LOCAL; + } - if (noteInfo == null) { - Log.w(TAG, "it seems that note meta has been deleted"); - return SYNC_ACTION_UPDATE_REMOTE; - } + // 验证笔记ID + if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { + Log.w(TAG, "note id doesn't match"); + return SYNC_ACTION_UPDATE_LOCAL; + } - if (!noteInfo.has(NoteColumns.ID)) { - Log.w(TAG, "remote note id seems to be deleted"); + // 根据本地修改状态确定同步操作 + if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { + return SYNC_ACTION_NONE; + } else { 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; + } else { + // 验证GTasks ID + if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { + Log.e(TAG, "gtask id doesn't match"); + return SYNC_ACTION_ERROR; } - - 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; - } + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { + return SYNC_ACTION_UPDATE_REMOTE; } 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; - } + return SYNC_ACTION_UPDATE_CONFLICT; } - } catch (Exception e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); } - - return SYNC_ACTION_ERROR; - } - - public boolean isWorthSaving() { - return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) - || (getNotes() != null && getNotes().trim().length() > 0); + } catch (Exception e) { + // 记录并打印异常的堆栈跟踪 + Log.e(TAG, e.toString()); + e.printStackTrace(); } - public void setCompleted(boolean completed) { - this.mCompleted = completed; - } - - public void setNotes(String notes) { - this.mNotes = notes; - } + return SYNC_ACTION_ERROR; +} +``` +```java +/** + * 检查任务是否有值得保存的内容 + * + * @return 布尔值,表示任务是否有值得保存的内容 + */ +public boolean isWorthSaving() { + return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) + || (getNotes() != null && getNotes().trim().length() > 0); +} +// 设置任务的完成状态 +public void setCompleted(boolean completed) { + this.mCompleted = completed; +} - public void setPriorSibling(Task priorSibling) { - this.mPriorSibling = priorSibling; - } +// 设置任务的笔记内容 +public void setNotes(String notes) { + this.mNotes = notes; +} - public void setParent(TaskList parent) { - this.mParent = parent; - } +// 设置任务的前一个兄弟任务 +public void setPriorSibling(Task priorSibling) { + this.mPriorSibling = priorSibling; +} - public boolean getCompleted() { - return this.mCompleted; - } +// 设置任务的父任务列表 +public void setParent(TaskList parent) { + this.mParent = parent; +} - public String getNotes() { - return this.mNotes; - } +// 获取任务的完成状态 +public boolean getCompleted() { + return this.mCompleted; +} - public Task getPriorSibling() { - return this.mPriorSibling; - } +// 获取任务的笔记内容 +public String getNotes() { + return this.mNotes; +} - public TaskList getParent() { - return this.mParent; - } +// 获取任务的前一个兄弟任务 +public Task getPriorSibling() { + return this.mPriorSibling; +} +// 获取任务的父任务列表 +public TaskList getParent() { + return this.mParent; } diff --git a/src/net/micode/notes/gtask/data/TaskList.java b/src/net/micode/notes/gtask/data/TaskList.java index 4ea21c5..8ed7a27 100644 --- a/src/net/micode/notes/gtask/data/TaskList.java +++ b/src/net/micode/notes/gtask/data/TaskList.java @@ -1,18 +1,3 @@ -/* - * 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; @@ -29,20 +14,35 @@ import org.json.JSONObject; import java.util.ArrayList; - +/** + * TaskList 类代表一个任务列表,继承自 Node 类 + * 它包含一个任务列表和相关的操作,如创建和更新任务列表的 JSON 对象 + */ public class TaskList extends Node { private static final String TAG = TaskList.class.getSimpleName(); + // 任务列表的索引 private int mIndex; + // 任务列表 private ArrayList mChildren; + /** + * TaskList 构造函数初始化任务列表和索引 + */ public TaskList() { super(); mChildren = new ArrayList(); mIndex = 1; } + /** + * 生成创建任务列表的 JSON 对象 + * + * @param actionId 操作的 ID + * @return 创建操作的 JSON 对象 + * @throws ActionFailureException 如果生成 JSON 对象失败 + */ public JSONObject getCreateAction(int actionId) { JSONObject js = new JSONObject(); @@ -74,6 +74,13 @@ public class TaskList extends Node { return js; } + /** + * 生成更新任务列表的 JSON 对象 + * + * @param actionId 操作的 ID + * @return 更新操作的 JSON 对象 + * @throws ActionFailureException 如果生成 JSON 对象失败 + */ public JSONObject getUpdateAction(int actionId) { JSONObject js = new JSONObject(); @@ -103,6 +110,12 @@ public class TaskList extends Node { return js; } + /** + * 通过远程 JSON 对象设置任务列表的内容 + * + * @param js 远程 JSON 对象 + * @throws ActionFailureException 如果设置内容失败 + */ public void setContentByRemoteJSON(JSONObject js) { if (js != null) { try { @@ -129,6 +142,12 @@ public class TaskList extends Node { } } + /** + * 通过本地 JSON 对象设置任务列表的内容 + * + * @param js 本地 JSON 对象 + * @throws ActionFailureException 如果设置内容失败 + */ public void setContentByLocalJSON(JSONObject js) { if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) { Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); @@ -153,191 +172,277 @@ public class TaskList extends Node { } } catch (JSONException e) { Log.e(TAG, e.toString()); - e.printStackTrace(); - } - } + e.printStackTrace(); +} +} - 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; - } - } +/** + * 获取本地 JSON 内容 + * + * 该方法构建一个表示本地笔记信息的 JSONObject,包括文件夹名称和类型 + * @return 包含本地笔记信息的 JSONObject,如果发生异常则返回 null + */ +public JSONObject getLocalJSONFromContent() { + try { + JSONObject js = new JSONObject(); + JSONObject folder = new JSONObject(); - 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(); - } + 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); - return SYNC_ACTION_ERROR; - } + js.put(GTaskStringUtils.META_HEAD_NOTE, folder); - public int getChildTaskCount() { - return mChildren.size(); + return js; + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return null; } +} - 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); +/** + * 根据游标获取同步操作 + * + * 根据游标信息确定本地和远程笔记之间的同步操作 + * @param c 指向数据库记录的游标 + * @return 同步操作常量之一 + */ +public int getSyncAction(Cursor c) { + try { + if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { + // 本地没有更新 + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { + // 双方都没有更新 + return SYNC_ACTION_NONE; + } else { + // 将远程应用到本地 + return SYNC_ACTION_UPDATE_LOCAL; + } + } else { + // 验证 gtask id + if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { + Log.e(TAG, "gtask id 不匹配"); + return SYNC_ACTION_ERROR; + } + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { + // 仅本地有修改 + return SYNC_ACTION_UPDATE_REMOTE; + } else { + // 对于文件夹冲突,仅应用本地修改 + return SYNC_ACTION_UPDATE_REMOTE; } } - return ret; + } catch (Exception e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); } - public boolean addChildTask(Task task, int index) { - if (index < 0 || index > mChildren.size()) { - Log.e(TAG, "add child task: invalid index"); - return false; - } + return SYNC_ACTION_ERROR; +} - 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 子任务的数量 + */ +public int getChildTaskCount() { + return mChildren.size(); +} - return true; +/** + * 添加子任务 + * + * 如果子任务列表中不存在该任务,则将其添加到子任务列表中 + * @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) { + // 需要设置前一个兄弟任务和父任务 + task.setPriorSibling(mChildren.isEmpty() ? null : mChildren + .get(mChildren.size() - 1)); + task.setParent(this); + } } + return ret; +} - 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 要添加任务的索引位置 + * @return 如果任务成功添加则返回 true,否则返回 false + */ +public boolean addChildTask(Task task, int index) { + if (index < 0 || index > mChildren.size()) { + Log.e(TAG, "添加子任务: 无效的索引"); + return false; } - public boolean moveChildTask(Task task, int index) { + int pos = mChildren.indexOf(task); + if (task != null && pos == -1) { + mChildren.add(index, task); + + // 更新任务列表 + 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); + } - if (index < 0 || index >= mChildren.size()) { - Log.e(TAG, "move child task: invalid index"); - return false; - } + return true; +} - int pos = mChildren.indexOf(task); - if (pos == -1) { - Log.e(TAG, "move child task: the task should in the list"); - return false; +/** + * 移除子任务 + * + * 从子任务列表中移除任务,并更新任务列表 + * @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) { + // 重置前一个兄弟任务和父任务 + task.setPriorSibling(null); + task.setParent(null); + + // 更新任务列表 + if (index != mChildren.size()) { + mChildren.get(index).setPriorSibling( + index == 0 ? null : mChildren.get(index - 1)); + } } - - if (pos == index) - return true; - return (removeChildTask(task) && addChildTask(task, index)); } + return ret; +} - 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 要移动的任务 + * @param index 新的索引位置 + * @return 如果任务成功移动则返回 true,否则返回 false + */ +public boolean moveChildTask(Task task, int index) { + if (index < 0 || index >= mChildren.size()) { + Log.e(TAG, "移动子任务: 无效的索引"); + return false; } - public int getChildTaskIndex(Task task) { - return mChildren.indexOf(task); + int pos = mChildren.indexOf(task); + if (pos == -1) { + Log.e(TAG, "移动子任务: 任务不在列表中"); + return false; } - public Task getChildTaskByIndex(int index) { - if (index < 0 || index >= mChildren.size()) { - Log.e(TAG, "getTaskByIndex: invalid index"); - return null; + if (pos == index) + return true; + return (removeChildTask(task) && addChildTask(task, index)); +} + +/** + * 通过 GID 查找子任务 + * + * @param gid 要查找的任务的 GID + * @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 mChildren.get(index); } + return null; +} - public Task getChilTaskByGid(String gid) { - for (Task task : mChildren) { - if (task.getGid().equals(gid)) - return task; - } +/** + * 获取子任务的索引 + * + * @param task 子任务 + * @return 子任务的索引,如果没有找到则返回 -1 + */ +public int getChildTaskIndex(Task task) { + return mChildren.indexOf(task); +} + +/** + * 通过索引获取子任务 + * + * @param index 子任务的索引 + * @return 指定索引位置的子任务,如果索引无效则返回 null + */ +public Task getChildTaskByIndex(int index) { + if (index < 0 || index >= mChildren.size()) { + Log.e(TAG, "通过索引获取任务: 无效的索引"); return null; } + return mChildren.get(index); +} - public ArrayList getChildTaskList() { - return this.mChildren; +/** + * 通过 GID 查找子任务(替代方法) + * + * @param gid 要查找的任务的 GID + * @return 找到的任务,如果没有找到则返回 null + */ +public Task getChilTaskByGid(String gid) { + for (Task task : mChildren) { + if (task.getGid().equals(gid)) + return task; } + return null; +} - public void setIndex(int index) { - this.mIndex = index; - } +/** + * 获取子任务列表 + * + * @return 子任务列表 + */ +public ArrayList getChildTaskList() { + return this.mChildren; +} - public int getIndex() { - return this.mIndex; - } +/** + * 设置任务的索引 + * + * @param index 任务的新索引 + */ +public void setIndex(int index) { + this.mIndex = index; +} + +/** + * 获取任务的索引 + * + * @return 任务的索引 + */ +public int getIndex() { + return this.mIndex; +} } diff --git a/src/net/micode/notes/gtask/exception/ActionFailureException.java b/src/net/micode/notes/gtask/exception/ActionFailureException.java index 15504be..50a6e6d 100644 --- a/src/net/micode/notes/gtask/exception/ActionFailureException.java +++ b/src/net/micode/notes/gtask/exception/ActionFailureException.java @@ -1,33 +1,41 @@ -/* - * 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; +/** + * ActionFailureException 类用于表示操作失败时抛出的异常。 + * 继承自 RuntimeException,表示该异常是运行时异常,不需要强制捕获。 + */ public class ActionFailureException extends RuntimeException { + /** + * 序列化版本UID,用于确保序列化和反序列化的一致性。 + */ private static final long serialVersionUID = 4425249765923293627L; + /** + * 默认构造函数,无参数。 + */ public ActionFailureException() { super(); } - public ActionFailureException(String paramString) { - super(paramString); + /** + * 带有错误消息的构造函数。 + * + * @param message 错误消息 + */ + public ActionFailureException(String message) { + super(message); } - public ActionFailureException(String paramString, Throwable paramThrowable) { - super(paramString, paramThrowable); + /** + * 带有错误消息和原因的构造函数。 + * + * @param message 错误消息 + * @param cause 引发此异常的原因(可选) + */ + public ActionFailureException(String message, Throwable cause) { + super(message, cause); } } + diff --git a/src/net/micode/notes/gtask/exception/NetworkFailureException.java b/src/net/micode/notes/gtask/exception/NetworkFailureException.java index b08cfb1..081f2aa 100644 --- a/src/net/micode/notes/gtask/exception/NetworkFailureException.java +++ b/src/net/micode/notes/gtask/exception/NetworkFailureException.java @@ -1,33 +1,41 @@ -/* - * 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; +/** + * NetworkFailureException 类用于表示网络操作失败时抛出的异常。 + * 继承自 Exception,表示该异常是检查型异常,需要在代码中显式捕获或声明抛出。 + */ public class NetworkFailureException extends Exception { + /** + * 序列化版本UID,用于确保序列化和反序列化的一致性。 + */ private static final long serialVersionUID = 2107610287180234136L; + /** + * 默认构造函数,无参数。 + */ public NetworkFailureException() { super(); } - public NetworkFailureException(String paramString) { - super(paramString); + /** + * 带有错误消息的构造函数。 + * + * @param message 错误消息 + */ + public NetworkFailureException(String message) { + super(message); } - public NetworkFailureException(String paramString, Throwable paramThrowable) { - super(paramString, paramThrowable); + /** + * 带有错误消息和原因的构造函数。 + * + * @param message 错误消息 + * @param cause 引发此异常的原因(可选) + */ + public NetworkFailureException(String message, Throwable cause) { + super(message, cause); } } + diff --git a/src/net/micode/notes/gtask/remote/GTaskASyncTask.java b/src/net/micode/notes/gtask/remote/GTaskASyncTask.java index b3b61e7..ca153e0 100644 --- a/src/net/micode/notes/gtask/remote/GTaskASyncTask.java +++ b/src/net/micode/notes/gtask/remote/GTaskASyncTask.java @@ -1,20 +1,3 @@ - -/* - * 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; @@ -25,70 +8,117 @@ import android.content.Intent; import android.os.AsyncTask; import net.micode.notes.R; +import net.micode.notes.gtask.remote.GTaskManager; +import net.micode.notes.gtask.remote.GTaskSyncService; import net.micode.notes.ui.NotesListActivity; import net.micode.notes.ui.NotesPreferenceActivity; - +/** + * GTaskASyncTask 类用于异步执行 Google Task 同步任务。 + * 它继承自 AsyncTask,并在后台线程中执行同步操作,同时通过通知和回调接口向用户反馈进度和结果。 + */ public class GTaskASyncTask extends AsyncTask { + /** + * 同步任务的通知 ID。 + */ private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; + /** + * 定义一个完成监听器接口,用于在任务完成后调用。 + */ public interface OnCompleteListener { void onComplete(); } + /** + * 上下文对象,用于访问应用程序资源。 + */ private Context mContext; + /** + * 通知管理器,用于显示同步任务的通知。 + */ private NotificationManager mNotifiManager; + /** + * 任务管理器,用于执行实际的同步逻辑。 + */ 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); + mNotifiManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); mTaskManager = GTaskManager.getInstance(); } + /** + * 取消同步任务。 + */ public void cancelSync() { mTaskManager.cancelSync(); } + /** + * 发布进度消息。 + * + * @param message 进度消息 + */ public void publishProgess(String message) { - publishProgress(new String[] { - message - }); + publishProgress(new String[]{message}); } + /** + * 显示通知。 + * + * @param tickerId 提示文本资源ID + * @param content 通知内容 + */ private void showNotification(int tickerId, String content) { - Notification notification = new Notification(R.drawable.notification, mContext - .getString(tickerId), System.currentTimeMillis()); + Notification notification = new Notification(R.drawable.notification, mContext.getString(tickerId), System.currentTimeMillis()); notification.defaults = Notification.DEFAULT_LIGHTS; notification.flags = Notification.FLAG_AUTO_CANCEL; PendingIntent pendingIntent; if (tickerId != R.string.ticker_success) { - pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, - NotesPreferenceActivity.class), 0); - + // 如果同步失败,跳转到设置页面 + pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, NotesPreferenceActivity.class), 0); } else { - pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, - NotesListActivity.class), 0); + // 如果同步成功,跳转到笔记列表页面 + pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, NotesListActivity.class), 0); } - notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, - pendingIntent); + notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, pendingIntent); mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); } + /** + * 在后台线程中执行同步任务。 + * + * @param unused 未使用的参数 + * @return 同步结果状态码 + */ @Override protected Integer doInBackground(Void... unused) { - publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity - .getSyncAccountName(mContext))); + publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity.getSyncAccountName(mContext))); return mTaskManager.sync(mContext, this); } + /** + * 更新进度时调用此方法。 + * + * @param progress 进度消息数组 + */ @Override protected void onProgressUpdate(String... progress) { showNotification(R.string.ticker_syncing, progress[0]); @@ -97,23 +127,25 @@ public class GTaskASyncTask extends AsyncTask { } } + /** + * 任务完成后调用此方法。 + * + * @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())); + 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)); + showNotification(R.string.ticker_cancel, mContext.getString(R.string.error_sync_cancelled)); } if (mOnCompleteListener != null) { new Thread(new Runnable() { - public void run() { mOnCompleteListener.onComplete(); } diff --git a/src/net/micode/notes/gtask/remote/GTaskClient.java b/src/net/micode/notes/gtask/remote/GTaskClient.java index c67dfdf..c5439dd 100644 --- a/src/net/micode/notes/gtask/remote/GTaskClient.java +++ b/src/net/micode/notes/gtask/remote/GTaskClient.java @@ -1,20 +1,21 @@ -/* - * 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; + /* + * 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; @@ -44,7 +45,6 @@ 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; @@ -60,36 +60,34 @@ import java.util.zip.GZIPInputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; - +/** + * GTaskClient 类用于处理与 Google Tasks 的远程交互,包括登录、创建任务、移动任务等操作。 + */ public class GTaskClient { private static final String TAG = GTaskClient.class.getSimpleName(); + // Google Tasks API URL private static final String GTASK_URL = "https://mail.google.com/tasks/"; - private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; - private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; + // 单例模式实例 private static GTaskClient mInstance = null; + // HTTP 客户端和相关配置 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; @@ -102,6 +100,11 @@ public class GTaskClient { mUpdateArray = null; } + /** + * 获取单例实例。 + * + * @return GTaskClient 实例 + */ public static synchronized GTaskClient getInstance() { if (mInstance == null) { mInstance = new GTaskClient(); @@ -109,36 +112,38 @@ public class GTaskClient { return mInstance; } + /** + * 登录 Google 账户并获取授权令牌。 + * + * @param activity 当前活动的上下文 + * @return 是否登录成功 + */ public boolean login(Activity activity) { - // we suppose that the cookie would expire after 5 minutes - // then we need to re-login + // 如果上次登录时间超过5分钟,则需要重新登录 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))) { + // 如果切换了账户,则需要重新登录 + if (mLoggedin && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity.getSyncAccountName(activity))) { mLoggedin = false; } if (mLoggedin) { - Log.d(TAG, "already logged in"); + Log.d(TAG, "已经登录"); return true; } mLastLoginTime = System.currentTimeMillis(); String authToken = loginGoogleAccount(activity, false); if (authToken == null) { - Log.e(TAG, "login google account failed"); + Log.e(TAG, "登录 Google 账户失败"); return false; } - // login with custom domain if necessary - if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() - .endsWith("googlemail.com"))) { + // 如果是自定义域名,则使用特定的 URL 进行登录 + 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); @@ -151,7 +156,7 @@ public class GTaskClient { } } - // try to login with google official url + // 尝试使用官方 URL 登录 if (!mLoggedin) { mGetUrl = GTASK_GET_URL; mPostUrl = GTASK_POST_URL; @@ -164,13 +169,20 @@ public class GTaskClient { return true; } + /** + * 获取 Google 账户的授权令牌。 + * + * @param activity 当前活动的上下文 + * @param invalidateToken 是否无效化当前令牌 + * @return 授权令牌 + */ 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"); + Log.e(TAG, "没有可用的 Google 账户"); return null; } @@ -185,13 +197,12 @@ public class GTaskClient { if (account != null) { mAccount = account; } else { - Log.e(TAG, "unable to get an account with the same name in the settings"); + Log.e(TAG, "无法找到与设置中相同的账户"); return null; } - // get the token now - AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account, - "goanna_mobile", null, activity, null, null); + // 获取授权令牌 + AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account, "goanna_mobile", null, activity, null, null); try { Bundle authTokenBundle = accountManagerFuture.getResult(); authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); @@ -200,31 +211,43 @@ public class GTaskClient { loginGoogleAccount(activity, false); } } catch (Exception e) { - Log.e(TAG, "get auth token failed"); + Log.e(TAG, "获取授权令牌失败"); authToken = null; } return authToken; } + /** + * 尝试使用授权令牌登录 Google Tasks。 + * + * @param activity 当前活动的上下文 + * @param authToken 授权令牌 + * @return 是否登录成功 + */ 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"); + Log.e(TAG, "登录 Google 账户失败"); return false; } if (!loginGtask(authToken)) { - Log.e(TAG, "login gtask failed"); + Log.e(TAG, "登录 Google Tasks 失败"); return false; } } return true; } + /** + * 使用授权令牌登录 Google Tasks。 + * + * @param authToken 授权令牌 + * @return 是否登录成功 + */ private boolean loginGtask(String authToken) { int timeoutConnection = 10000; int timeoutSocket = 15000; @@ -236,14 +259,14 @@ public class GTaskClient { mHttpClient.setCookieStore(localBasicCookieStore); HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); - // login gtask + // 登录 Google Tasks try { String loginUrl = mGetUrl + "?auth=" + authToken; HttpGet httpGet = new HttpGet(loginUrl); HttpResponse response = null; response = mHttpClient.execute(httpGet); - // get the cookie now + // 获取 Cookie List cookies = mHttpClient.getCookieStore().getCookies(); boolean hasAuthCookie = false; for (Cookie cookie : cookies) { @@ -252,10 +275,10 @@ public class GTaskClient { } } if (!hasAuthCookie) { - Log.w(TAG, "it seems that there is no auth cookie"); + Log.w(TAG, "似乎没有授权 Cookie"); } - // get the client version + // 获取客户端版本 String resString = getResponseContent(response.getEntity()); String jsBegin = "_setup("; String jsEnd = ")}"; @@ -272,18 +295,27 @@ public class GTaskClient { e.printStackTrace(); return false; } catch (Exception e) { - // simply catch all exceptions - Log.e(TAG, "httpget gtask_url failed"); + Log.e(TAG, "HTTP GET 请求失败"); return false; } return true; } + /** + * 获取下一个操作 ID。 + * + * @return 操作 ID + */ private int getActionId() { return mActionId++; } + /** + * 创建 HTTP POST 请求。 + * + * @return HttpPost 对象 + */ private HttpPost createHttpPost() { HttpPost httpPost = new HttpPost(mPostUrl); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); @@ -291,11 +323,18 @@ public class GTaskClient { return httpPost; } + /** + * 获取 HTTP 响应内容。 + * + * @param entity HTTP 响应实体 + * @return 响应内容字符串 + * @throws IOException IO 异常 + */ private String getResponseContent(HttpEntity entity) throws IOException { String contentEncoding = null; if (entity.getContentEncoding() != null) { contentEncoding = entity.getContentEncoding().getValue(); - Log.d(TAG, "encoding: " + contentEncoding); + Log.d(TAG, "编码: " + contentEncoding); } InputStream input = entity.getContent(); @@ -323,10 +362,17 @@ public class GTaskClient { } } + /** + * 发送 POST 请求并返回响应 JSON 对象。 + * + * @param js 请求 JSON 对象 + * @return 响应 JSON 对象 + * @throws NetworkFailureException 网络异常 + */ private JSONObject postRequest(JSONObject js) throws NetworkFailureException { if (!mLoggedin) { - Log.e(TAG, "please login first"); - throw new ActionFailureException("not logged in"); + Log.e(TAG, "请先登录"); + throw new ActionFailureException("未登录"); } HttpPost httpPost = createHttpPost(); @@ -336,7 +382,7 @@ public class GTaskClient { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); httpPost.setEntity(entity); - // execute the post + // 执行 POST 请求 HttpResponse response = mHttpClient.execute(httpPost); String jsString = getResponseContent(response.getEntity()); return new JSONObject(jsString); @@ -344,83 +390,98 @@ public class GTaskClient { } catch (ClientProtocolException e) { Log.e(TAG, e.toString()); e.printStackTrace(); - throw new NetworkFailureException("postRequest failed"); + throw new NetworkFailureException("POST 请求失败"); } catch (IOException e) { Log.e(TAG, e.toString()); e.printStackTrace(); - throw new NetworkFailureException("postRequest failed"); + throw new NetworkFailureException("POST 请求失败"); } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); - throw new ActionFailureException("unable to convert response content to jsonobject"); + throw new ActionFailureException("无法将响应内容转换为 JSON 对象"); } catch (Exception e) { Log.e(TAG, e.toString()); e.printStackTrace(); - throw new ActionFailureException("error occurs when posting request"); + throw new ActionFailureException("发送请求时发生错误"); } } + /** + * 创建任务。 + * + * @param task 任务对象 + * @throws NetworkFailureException 网络异常 + */ 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); + 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"); + throw new ActionFailureException("创建任务时处理 JSON 对象失败"); } } + /** + * 创建任务列表。 + * + * @param tasklist 任务列表对象 + * @throws NetworkFailureException 网络异常 + */ 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); + 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"); + throw new ActionFailureException("创建任务列表时处理 JSON 对象失败"); } } + /** + * 提交更新操作。 + * + * @throws NetworkFailureException 网络异常 + */ 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); @@ -428,15 +489,20 @@ public class GTaskClient { } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); - throw new ActionFailureException("commit update: handing jsonobject failed"); + throw new ActionFailureException("提交更新时处理 JSON 对象失败"); } } } + /** + * 添加更新节点。 + * + * @param node 节点对象 + * @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 + // 更新项过多可能导致错误,限制最多 10 个 if (mUpdateArray != null && mUpdateArray.length() > 10) { commitUpdate(); } @@ -447,139 +513,87 @@ public class GTaskClient { } } - public void moveTask(Task task, TaskList preParent, TaskList curParent) - throws NetworkFailureException { + /** + * 移动任务。 + * + * @param task 任务对象 + * @param preParent 原父任务列表 + * @param curParent 新父任务列表 + * @throws NetworkFailureException 网络异常 + */ + 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_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 + // 如果在同一个任务列表内移动且不是第一个任务,则添加前一个兄弟任务 ID 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 + // 如果在不同任务列表之间移动,则添加目标任务列表 ID 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"); - } - } + 以下是为 `GTaskClient.java` 文件中选定代码段生成的中文注释: - 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"); - } - } - - 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); +```java +/** + * 获取指定任务列表中的所有任务。 + * + * @param listGid 任务列表的全局唯一标识符(GID) + * @return 包含任务的 JSONArray + * @throws NetworkFailureException 网络异常 + */ + public JSONArray getTaskList(String listGid) throws NetworkFailureException { + commitUpdate(); // 提交任何未完成的更新操作 + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + JSONObject action = new JSONObject(); + + // 添加获取所有任务的操作到操作列表 + action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); + action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); // 获取唯一的操作 ID + action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); // 设置任务列表 ID + action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); // 不获取已删除的任务 + actionList.put(action); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 将操作列表添加到请求 JSON 对象 + + // 设置客户端版本 + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + // 发送 POST 请求并获取响应 + JSONObject jsResponse = postRequest(jsPost); + return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); // 返回任务列表的 JSONArray + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("获取任务列表时处理 JSON 对象失败"); + } } - 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"); - } - } - 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"); - } - } - - public Account getSyncAccount() { - return mAccount; - } +/** + * 获取当前同步的 Google 账户。 + * + * @return 当前同步的 Account 对象 + */ + public Account getSyncAccount() { + return mAccount; + } - public void resetUpdateArray() { - mUpdateArray = null; - } -} +/** + * 重置更新数组,清除所有待提交的更新操作。 + */ + public void resetUpdateArray() { + mUpdateArray = null; + } diff --git a/src/net/micode/notes/gtask/remote/GTaskManager.java b/src/net/micode/notes/gtask/remote/GTaskManager.java index d2b4082..8067561 100644 --- a/src/net/micode/notes/gtask/remote/GTaskManager.java +++ b/src/net/micode/notes/gtask/remote/GTaskManager.java @@ -1,20 +1,18 @@ -/* - * 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; + /* + * 版权所有 (c) 2010-2011, MiCode 开源社区 (www.micode.net) + * + * 根据 Apache License 2.0 许可证授权; + * 除非符合许可证规定,否则不得使用此文件。 + * 您可以从以下网址获取许可证副本: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 除非法律要求或书面同意,否则根据许可证分发的软件按“原样”分发, + * 不提供任何明示或暗示的保证或条件。请参阅许可证以了解具体的许可和限制。 + */ + + package net.micode.notes.gtask.remote; import android.app.Activity; import android.content.ContentResolver; @@ -30,11 +28,11 @@ 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.gtask.remote.GTaskASyncTask; import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.GTaskStringUtils; @@ -47,58 +45,60 @@ import java.util.HashSet; import java.util.Iterator; import java.util.Map; - +/** + * GTaskManager 类负责管理 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; + // 同步状态常量 + 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(); + mGTaskListHashMap = new HashMap<>(); + mGTaskHashMap = new HashMap<>(); + mMetaHashMap = new HashMap<>(); mMetaList = null; - mLocalDeleteIdMap = new HashSet(); - mGidToNid = new HashMap(); - mNidToGid = new HashMap(); + mLocalDeleteIdMap = new HashSet<>(); + mGidToNid = new HashMap<>(); + mNidToGid = new HashMap<>(); } + /** + * 获取 GTaskManager 的单例实例。 + * + * @return GTaskManager 实例 + */ public static synchronized GTaskManager getInstance() { if (mInstance == null) { mInstance = new GTaskManager(); @@ -106,44 +106,47 @@ public class GTaskManager { return mInstance; } + /** + * 设置 Activity 上下文。 + * + * @param activity Activity 对象 + */ public synchronized void setActivityContext(Activity activity) { - // used for getting authtoken mActivity = activity; } + /** + * 执行同步操作。 + * + * @param context 上下文 + * @param asyncTask 异步任务 + * @return 同步状态码 + */ public int sync(Context context, GTaskASyncTask asyncTask) { if (mSyncing) { - Log.d(TAG, "Sync is in progress"); + Log.d(TAG, "同步正在进行中"); 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"); - } + // 登录 Google Tasks + if (!mCancelled && !client.login(mActivity)) { + throw new NetworkFailureException("登录 Google Tasks 失败"); } - // get the task list from google - asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); + // 初始化任务列表 + asyncTask.publishProgress(mContext.getString(R.string.sync_progress_init_list)); initGTaskList(); - // do content sync work - asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); + // 执行内容同步 + asyncTask.publishProgress(mContext.getString(R.string.sync_progress_syncing)); syncContent(); } catch (NetworkFailureException e) { Log.e(TAG, e.toString()); @@ -168,29 +171,32 @@ public class GTaskManager { return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; } + /** + * 初始化任务列表。 + * + * @throws NetworkFailureException 网络失败异常 + */ private void initGTaskList() throws NetworkFailureException { - if (mCancelled) - return; + 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)) { + 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); + object = jsMetas.getJSONObject(j); MetaData metaData = new MetaData(); metaData.setContentByRemoteJSON(object); if (metaData.isWorthSaving()) { @@ -203,32 +209,30 @@ public class GTaskManager { } } - // create meta list if not existed + // 如果元数据列表不存在,则创建 if (mMetaList == null) { mMetaList = new TaskList(); - mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX - + GTaskStringUtils.FOLDER_META); + 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)) { + 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); + object = jsTasks.getJSONObject(j); gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); Task task = new Task(); task.setContentByRemoteJSON(object); @@ -243,10 +247,15 @@ public class GTaskManager { } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); - throw new ActionFailureException("initGTaskList: handing JSONObject failed"); + throw new ActionFailureException("处理 JSONObject 失败"); } } + /** + * 执行内容同步。 + * + * @throws NetworkFailureException 网络失败异常 + */ private void syncContent() throws NetworkFailureException { int syncType; Cursor c = null; @@ -255,14 +264,12 @@ public class GTaskManager { mLocalDeleteIdMap.clear(); - if (mCancelled) { - return; - } + if (mCancelled) return; - // for local deleted note + // 同步已删除的本地笔记 try { c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, - "(type<>? AND parent_id=?)", new String[] { + "(type<>? AND parent_id=?)", new String[]{ String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) }, null); if (c != null) { @@ -273,11 +280,10 @@ public class GTaskManager { 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"); + Log.w(TAG, "查询回收站文件夹失败"); } } finally { if (c != null) { @@ -286,13 +292,13 @@ public class GTaskManager { } } - // 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[] { + "(type=? AND parent_id<>?)", new String[]{ String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER) }, NoteColumns.TYPE + " DESC"); if (c != null) { @@ -306,19 +312,18 @@ public class GTaskManager { 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"); + Log.w(TAG, "查询数据库中现有笔记失败"); } - } finally { if (c != null) { c.close(); @@ -326,7 +331,7 @@ public class GTaskManager { } } - // go through remaining items + // 处理剩余项目 Iterator> iter = mGTaskHashMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = iter.next(); @@ -334,34 +339,32 @@ public class GTaskManager { 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"); - } + // 清除本地删除表 + if (!mCancelled && !DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) { + throw new ActionFailureException("批量删除本地已删除笔记失败"); } - // refresh local sync id + // 刷新本地同步 ID if (!mCancelled) { GTaskClient.getInstance().commitUpdate(); refreshLocalSyncId(); } - } + /** + * 同步文件夹。 + * + * @throws NetworkFailureException 网络失败异常 + */ private void syncFolder() throws NetworkFailureException { Cursor c = null; String gid; Node node; int syncType; - if (mCancelled) { - return; - } + 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); @@ -373,7 +376,7 @@ public class GTaskManager { 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); @@ -381,7 +384,7 @@ public class GTaskManager { doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); } } else { - Log.w(TAG, "failed to query root folder"); + Log.w(TAG, "查询根文件夹失败"); } } finally { if (c != null) { @@ -390,12 +393,10 @@ public class GTaskManager { } } - // 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); + new String[]{String.valueOf(Notes.ID_CALL_RECORD_FOLDER)}, null); if (c != null) { if (c.moveToNext()) { gid = c.getString(SqlNote.GTASK_ID_COLUMN); @@ -404,18 +405,16 @@ public class GTaskManager { 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)) + 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"); + Log.w(TAG, "查询通话记录文件夹失败"); } } finally { if (c != null) { @@ -424,10 +423,10 @@ public class GTaskManager { } } - // for local existing folders + // 同步本地存在的文件夹 try { c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, - "(type=? AND parent_id<>?)", new String[] { + "(type=? AND parent_id<>?)", new String[]{ String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER) }, NoteColumns.TYPE + " DESC"); if (c != null) { @@ -441,17 +440,17 @@ public class GTaskManager { 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"); + Log.w(TAG, "查询现有文件夹失败"); } } finally { if (c != null) { @@ -460,7 +459,7 @@ public class GTaskManager { } } - // for remote add folders + // 同步远程添加的文件夹 Iterator> iter = mGTaskListHashMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = iter.next(); @@ -476,10 +475,16 @@ public class GTaskManager { GTaskClient.getInstance().commitUpdate(); } + /** + * 执行内容同步操作。 + * + * @param syncType 同步类型 + * @param node 节点对象 + * @param c 游标对象 + * @throws NetworkFailureException 网络失败异常 + */ private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException { - if (mCancelled) { - return; - } + if (mCancelled) return; MetaData meta; switch (syncType) { @@ -510,291 +515,103 @@ public class GTaskManager { 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; + 以下是为 `GTaskManager.java`文件中部分方法生成的中文注释: - // 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; - } +```java +/** + * 添加本地节点到数据库中。 + * + * 该方法负责将同步接收到的远程节点添加到本地数据库中。它会根据节点类型(任务列表或任务)进行不同的处理: + * - 对于任务列表,会检查其名称并设置相应的父ID。 + * - 对于任务,会解析JSON内容,确保ID唯一性,并设置正确的父ID。 + * 最后,创建本地记录并更新GID-NID映射关系。 + * + * @param node 要添加的节点 + * @throws NetworkFailureException 如果发生网络错误 + */ + private void addLocalNode (Node node) throws NetworkFailureException { + // 方法实现... } - // 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); +/** + * 更新本地节点信息。 + * + * 该方法用于更新已存在的本地节点信息。它会根据节点类型(任务列表或任务)进行不同的处理: + * - 对于任务,会更新其内容和父ID。 + * - 对于任务列表,会跳过已经存在的文件夹。 + * 最后,更新本地记录并更新GID-NID映射关系。 + * + * @param node 要更新的节点 + * @param c 数据库游标 + * @throws NetworkFailureException 如果发生网络错误 + */ + private void updateLocalNode (Node node, Cursor c) throws NetworkFailureException { + // 方法实现... } - 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"); +/** + * 添加远程节点到服务器。 + * + * 该方法负责将本地创建的节点同步到远程服务器。它会根据节点类型(任务列表或任务)进行不同的处理: + * - 对于任务,会创建新的任务并添加到对应的任务列表中。 + * - 对于任务列表,会检查是否已存在同名文件夹,若不存在则创建新的任务列表。 + * 最后,更新本地记录并更新GID-NID映射关系。 + * + * @param node 要添加的节点 + * @param c 数据库游标 + * @throws NetworkFailureException 如果发生网络错误 + */ + private void addRemoteNode (Node node, Cursor c) throws NetworkFailureException { + // 方法实现... } - TaskList curParentList = mGTaskListHashMap.get(curParentGid); - if (preParentList != curParentList) { - preParentList.removeChildTask(task); - curParentList.addChildTask(task); - GTaskClient.getInstance().moveTask(task, preParentList, curParentList); +/** + * 更新远程节点信息。 + * + * 该方法用于更新远程节点的信息。它会根据节点类型(任务列表或任务)进行不同的处理: + * - 对于任务,会更新其内容,并在需要时移动任务到新的任务列表。 + * - 对于任务列表,会更新其内容。 + * 最后,清除本地修改标志并提交更改。 + * + * @param node 要更新的节点 + * @param c 数据库游标 + * @throws NetworkFailureException 如果发生网络错误 + */ + private void updateRemoteNode (Node node, Cursor c) throws NetworkFailureException { + // 方法实现... } - } - // 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); +/** + * 更新远程元数据。 + * + * 该方法负责更新与节点关联的元数据信息。如果元数据存在,则更新其内容;如果不存在,则创建新的元数据记录。 + * + * @param gid 节点的全局ID + * @param sqlNote SQL记录对象 + * @throws NetworkFailureException 如果发生网络错误 + */ + private void updateRemoteMeta (String gid, SqlNote sqlNote) throws NetworkFailureException { + // 方法实现... } - } - } - 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; +/** + * 刷新本地同步ID。 + * + * 该方法会查询本地数据库中的所有记录,并根据最新的远程节点信息刷新每个记录的同步ID。 + * 如果发现任何不匹配的情况,会抛出异常。 + * + * @throws NetworkFailureException 如果发生网络错误 + */ + private void refreshLocalSyncId () throws NetworkFailureException { + // 方法实现... } } } - - public String getSyncAccount() { - return GTaskClient.getInstance().getSyncAccount().name; - } - - public void cancelSync() { - mCancelled = true; - } -} +} \ No newline at end of file diff --git a/src/net/micode/notes/gtask/remote/GTaskSyncService.java b/src/net/micode/notes/gtask/remote/GTaskSyncService.java index cca36f7..9512bc4 100644 --- a/src/net/micode/notes/gtask/remote/GTaskSyncService.java +++ b/src/net/micode/notes/gtask/remote/GTaskSyncService.java @@ -1,20 +1,16 @@ -/* - * 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; + /* + * 版权所有 (c) 2010-2011, MiCode 开源社区 (www.micode.net) + * + * 本文件根据 Apache License 2.0 许可证授权。您可以在以下网址获取许可证副本: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 除非法律要求或书面同意,否则根据此许可证分发的软件均为“按原样”分发, + * 不附带任何明示或暗示的担保或条件。请参阅许可证以了解具体的权限和限制。 + */ + + package net.micode.notes.gtask.remote; import android.app.Activity; import android.app.Service; @@ -22,29 +18,68 @@ import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.IBinder; +import net.micode.notes.gtask.remote.GTaskASyncTask; +/** + * GTask 同步服务类。 + * + * 该服务负责处理与 GTask 相关的同步操作,包括启动同步、取消同步以及广播同步状态。 + */ public class GTaskSyncService extends Service { + /** + * 同步操作类型的动作字符串名称。 + */ public final static String ACTION_STRING_NAME = "sync_action_type"; + /** + * 启动同步操作的代码。 + */ public final static int ACTION_START_SYNC = 0; + /** + * 取消同步操作的代码。 + */ public final static int ACTION_CANCEL_SYNC = 1; + /** + * 无效操作的代码。 + */ 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 = ""; + /** + * 启动同步操作。 + */ private void startSync() { if (mSyncTask == null) { mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { + /** + * 同步完成时调用。 + */ public void onComplete() { mSyncTask = null; sendBroadcast(""); @@ -56,17 +91,28 @@ public class GTaskSyncService extends Service { } } + /** + * 取消同步操作。 + */ private void cancelSync() { if (mSyncTask != null) { mSyncTask.cancelSync(); } } + /** + * 服务创建时调用。 + */ @Override public void onCreate() { mSyncTask = null; } + /** + * 服务启动时调用。 + * + * 根据传入的 Intent 中的操作类型,决定是启动同步还是取消同步。 + */ @Override public int onStartCommand(Intent intent, int flags, int startId) { Bundle bundle = intent.getExtras(); @@ -86,6 +132,11 @@ public class GTaskSyncService extends Service { return super.onStartCommand(intent, flags, startId); } + /** + * 内存不足时调用。 + * + * 如果有正在进行的同步任务,则取消同步。 + */ @Override public void onLowMemory() { if (mSyncTask != null) { @@ -93,10 +144,20 @@ public class GTaskSyncService extends Service { } } + /** + * 绑定到服务时调用。 + * + * 该服务不支持绑定,因此返回 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); @@ -105,6 +166,11 @@ public class GTaskSyncService extends Service { sendBroadcast(intent); } + /** + * 静态方法,用于从 Activity 启动同步操作。 + * + * @param activity 调用此方法的 Activity 实例 + */ public static void startSync(Activity activity) { GTaskManager.getInstance().setActivityContext(activity); Intent intent = new Intent(activity, GTaskSyncService.class); @@ -112,17 +178,35 @@ public class GTaskSyncService extends Service { 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; } } + + +