代码解读更新提交记录

master
majunyi_outlook 3 years ago
parent 56649a882f
commit 31d2b661f8

@ -1,4 +1,4 @@
#Tue Apr 11 20:43:06 CST 2023 #Fri Apr 14 20:15:17 CST 2023
base.1=D\:\\IDEA\\AndroidModeCode\\MiNotes-master\\app\\build\\intermediates\\dex\\debug\\mergeDexDebug\\classes.dex base.1=D\:\\IDEA\\AndroidModeCode\\MiNotes-master\\app\\build\\intermediates\\dex\\debug\\mergeDexDebug\\classes.dex
path.1=classes.dex path.1=classes.dex
base.0=E\:\\MiNotes-master1\\MiNotes-master\\app\\build\\intermediates\\dex\\debug\\mergeDexDebug\\classes.dex base.0=E\:\\MiNotes-master1\\MiNotes-master\\app\\build\\intermediates\\dex\\debug\\mergeDexDebug\\classes.dex

@ -429,167 +429,231 @@ public class GTaskClient {
} }
/******/ /******/
/**
*
* @param task
* @throws NetworkFailureException
*/
public void createTask(Task task) throws NetworkFailureException { public void createTask(Task task) throws NetworkFailureException {
// 提交更新
commitUpdate(); commitUpdate();
try { try {
// 创建JSONObject对象
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
// 创建JSONArray对象
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
// action_list // 将新建任务的操作添加到actionList中
actionList.put(task.getCreateAction(getActionId())); actionList.put(task.getCreateAction(getActionId()));
// 将actionList添加到JSONObject中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version // 将客户端版本号添加到JSONObject中
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post // 发送post请求,并获取响应数据
JSONObject jsResponse = postRequest(jsPost); JSONObject jsResponse = postRequest(jsPost);
// 获取响应结果中的第一个JSONObject对象
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0); GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
// 将新建任务的gid设置为返回结果中的new_id
task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) { } catch (JSONException e) {
// 记录异常日志
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
// 抛出操作失败异常
throw new ActionFailureException("create task: handing jsonobject failed"); throw new ActionFailureException("create task: handing jsonobject failed");
} }
} }
/**
*
* @param tasklist
* @throws NetworkFailureException
*/
public void createTaskList(TaskList tasklist) throws NetworkFailureException { public void createTaskList(TaskList tasklist) throws NetworkFailureException {
// 提交更新
commitUpdate(); commitUpdate();
try { try {
// 创建JSONObject对象
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
// 创建JSONArray对象
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
// action_list // 将新建任务列表的操作添加到actionList中
actionList.put(tasklist.getCreateAction(getActionId())); actionList.put(tasklist.getCreateAction(getActionId()));
// 将actionList添加到JSONObject中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client version // 将客户端版本号添加到JSONObject中
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post // 发送post请求,并获取响应数据
JSONObject jsResponse = postRequest(jsPost); JSONObject jsResponse = postRequest(jsPost);
// 获取响应结果中的第一个JSONObject对象
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0); GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
// 将新建任务列表的gid设置为返回结果中的new_id
tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) { } catch (JSONException e) {
// 记录异常日志
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
// 抛出操作失败异常
throw new ActionFailureException("create tasklist: handing jsonobject failed"); throw new ActionFailureException("create tasklist: handing jsonobject failed");
} }
} }
/**
*
* @throws NetworkFailureException
*/
public void commitUpdate() throws NetworkFailureException { public void commitUpdate() throws NetworkFailureException {
// 如果有更新操作
if (mUpdateArray != null) { if (mUpdateArray != null) {
try { try {
// 创建JSONObject对象
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
// action_list // 将更新操作添加到actionList中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
// client_version // 将客户端版本号添加到JSONObject中
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送post请求
postRequest(jsPost); postRequest(jsPost);
// 更新操作数组置空
mUpdateArray = null; mUpdateArray = null;
} catch (JSONException e) { } catch (JSONException e) {
// 记录异常日志
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
// 抛出操作失败异常
throw new ActionFailureException("commit update: handing jsonobject failed"); throw new ActionFailureException("commit update: handing jsonobject failed");
} }
} }
} }
/**
*
* @param node
* @throws NetworkFailureException
*/
public void addUpdateNode(Node node) throws NetworkFailureException { public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) { if (node != null) {
// too many update items may result in an error // 如果更新数组中的项目太多可能会导致错误
// set max to 10 items // 将最大项设置为10项
if (mUpdateArray != null && mUpdateArray.length() > 10) { if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate(); commitUpdate(); // 提交更新数组
} }
if (mUpdateArray == null) if (mUpdateArray == null)
mUpdateArray = new JSONArray(); mUpdateArray = new JSONArray(); // 创建一个新的JSONArray
mUpdateArray.put(node.getUpdateAction(getActionId())); mUpdateArray.put(node.getUpdateAction(getActionId())); // 将节点的更新操作添加到JSONArray中
} }
} }
/**
*
* @param task
* @param preParent
* @param curParent
* @throws NetworkFailureException
*/
public void moveTask(Task task, TaskList preParent, TaskList curParent) public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException { throws NetworkFailureException {
commitUpdate(); commitUpdate(); // 提交更新数组
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject(); // 创建一个新的JSONObject
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject(); JSONObject action = new JSONObject();
// action_list // action_list
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); // 设置操作类型为移动
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); // 设置操作ID
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); // 设置任务ID
if (preParent == curParent && task.getPriorSibling() != null) { if (preParent == curParent && task.getPriorSibling() != null) {
// put prioring_sibing_id only if moving within the tasklist and // 如果在同一个任务列表中移动且不是第一个则设置prioring_sibing_id
// it is not the first one
action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
} }
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); // 设置移动前的任务列表ID
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); // 设置移动后的父任务列表ID
if (preParent != curParent) { if (preParent != curParent) {
// put the dest_list only if moving between tasklists // 如果在不同的任务列表中移动则设置dest_list
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
} }
actionList.put(action); actionList.put(action); // 将操作添加到操作列表中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version // client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); // 设置客户端版本号
postRequest(jsPost); postRequest(jsPost); // 发送POST请求
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("move task: handing jsonobject failed"); throw new ActionFailureException("move task: handing jsonobject failed"); // 抛出操作失败异常
} }
} }
/**
*
* @param node
* @throws NetworkFailureException
*/
public void deleteNode(Node node) throws NetworkFailureException { public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate(); commitUpdate(); // 提交更新数组
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject(); // 创建一个新的JSONObject
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
// action_list // action_list
node.setDeleted(true); node.setDeleted(true); // 设置节点为已删除
actionList.put(node.getUpdateAction(getActionId())); actionList.put(node.getUpdateAction(getActionId())); // 将节点的更新操作添加到操作列表中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version // client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); // 设置客户端版本号
postRequest(jsPost); // 发送POST请求
mUpdateArray = null; // 将更新数组设置为null
postRequest(jsPost);
mUpdateArray = null;
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("delete node: handing jsonobject failed"); throw new ActionFailureException("delete node: handing jsonobject failed"); // 抛出操作失败异常
} }
} }
/**
*
*
* @return JSONArray
* @throws NetworkFailureException
*/
public JSONArray getTaskLists() throws NetworkFailureException { public JSONArray getTaskLists() throws NetworkFailureException {
// 如果未登录,则抛出异常
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in"); throw new ActionFailureException("not logged in");
} }
try { try {
// 创建HttpGet对象用于向服务器发送GET请求
HttpGet httpGet = new HttpGet(mGetUrl); HttpGet httpGet = new HttpGet(mGetUrl);
HttpResponse response = null; HttpResponse response = null;
response = mHttpClient.execute(httpGet); response = mHttpClient.execute(httpGet);
// get the task list // 获取任务列表
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup("; String jsBegin = "_setup(";
String jsEnd = ")}</script>"; String jsEnd = ")}</script>";
@ -602,23 +666,34 @@ public class GTaskClient {
JSONObject js = new JSONObject(jsString); JSONObject js = new JSONObject(jsString);
return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
} catch (ClientProtocolException e) { } catch (ClientProtocolException e) {
// 如果出现ClientProtocolException则抛出网络连接异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed"); throw new NetworkFailureException("gettasklists: httpget failed");
} catch (IOException e) { } catch (IOException e) {
// 如果出现IOException则抛出网络连接异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed"); throw new NetworkFailureException("gettasklists: httpget failed");
} catch (JSONException e) { } catch (JSONException e) {
// 如果出现JSONException则抛出操作失败异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("get task lists: handing jasonobject failed"); throw new ActionFailureException("get task lists: handing jasonobject failed");
} }
} }
/**
* ID
*
* @param listGid ID
* @return JSONArray
* @throws NetworkFailureException
*/
public JSONArray getTaskList(String listGid) throws NetworkFailureException { public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
// 创建JSONObject对象设置请求参数
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject(); JSONObject action = new JSONObject();
@ -633,19 +708,29 @@ public class GTaskClient {
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送POST请求获取响应JSONObject对象
JSONObject jsResponse = postRequest(jsPost); JSONObject jsResponse = postRequest(jsPost);
return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS);
} catch (JSONException e) { } catch (JSONException e) {
// 如果出现JSONException则抛出操作失败异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("get task list: handing jsonobject failed"); throw new ActionFailureException("get task list: handing jsonobject failed");
} }
} }
/**
*
*
* @return
*/
public Account getSyncAccount() { public Account getSyncAccount() {
return mAccount; return mAccount;
} }
/**
*
*/
public void resetUpdateArray() { public void resetUpdateArray() {
mUpdateArray = null; mUpdateArray = null;
} }

@ -51,111 +51,98 @@ import java.util.Map;
public class GTaskManager { public class GTaskManager {
private static final String TAG = GTaskManager.class.getSimpleName(); private static final String TAG = GTaskManager.class.getSimpleName();
public static final int STATE_SUCCESS = 0; 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_NETWORK_ERROR = 1; private static GTaskManager mInstance = null; // 单例实例
public static final int STATE_INTERNAL_ERROR = 2; private Activity mActivity; // 活动的Activity实例
private Context mContext; // 上下文
private ContentResolver mContentResolver; // ContentResolver实例
public static final int STATE_SYNC_IN_PROGRESS = 3; private boolean mSyncing; // 是否正在同步
private boolean mCancelled; // 是否已取消同步
public static final int STATE_SYNC_CANCELLED = 4; private HashMap<String, TaskList> mGTaskListHashMap; // 任务列表哈希表
private HashMap<String, Node> mGTaskHashMap; // 任务哈希表
private static GTaskManager mInstance = null; private HashMap<String, MetaData> mMetaHashMap; // 元数据哈希表
private TaskList mMetaList; // 元数据列表
private Activity mActivity; private HashSet<Long> mLocalDeleteIdMap; // 本地删除ID哈希表
private HashMap<String, Long> mGidToNid; // GID到NID的映射哈希表
private Context mContext; private HashMap<Long, String> mNidToGid; // NID到GID的映射哈希表
private ContentResolver mContentResolver;
private boolean mSyncing;
private boolean mCancelled;
private HashMap<String, TaskList> mGTaskListHashMap;
private HashMap<String, Node> mGTaskHashMap;
private HashMap<String, MetaData> mMetaHashMap;
private TaskList mMetaList;
private HashSet<Long> mLocalDeleteIdMap;
private HashMap<String, Long> mGidToNid;
private HashMap<Long, String> mNidToGid;
private GTaskManager() { private GTaskManager() {
mSyncing = false; mSyncing = false; // 初始化时不在同步状态
mCancelled = false; mCancelled = false; // 初始化时未取消同步
mGTaskListHashMap = new HashMap<String, TaskList>(); mGTaskListHashMap = new HashMap<String, TaskList>(); // 初始化任务列表哈希表
mGTaskHashMap = new HashMap<String, Node>(); mGTaskHashMap = new HashMap<String, Node>(); // 初始化任务哈希表
mMetaHashMap = new HashMap<String, MetaData>(); mMetaHashMap = new HashMap<String, MetaData>(); // 初始化元数据哈希表
mMetaList = null; mMetaList = null; // 初始化元数据列表为空
mLocalDeleteIdMap = new HashSet<Long>(); mLocalDeleteIdMap = new HashSet<Long>(); // 初始化本地删除ID哈希表为空
mGidToNid = new HashMap<String, Long>(); mGidToNid = new HashMap<String, Long>(); // 初始化GID到NID的映射哈希表为空
mNidToGid = new HashMap<Long, String>(); mNidToGid = new HashMap<Long, String>(); // 初始化NID到GID的映射哈希表为空
} }
public static synchronized GTaskManager getInstance() { public static synchronized GTaskManager getInstance() { // 获取单例实例
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskManager(); mInstance = new GTaskManager();
} }
return mInstance; return mInstance;
} }
public synchronized void setActivityContext(Activity activity) { public synchronized void setActivityContext(Activity activity) { // 设置活动的Activity实例
// used for getting authtoken // 用于获取认证令牌
mActivity = activity; mActivity = activity;
} }
public int sync(Context context, GTaskASyncTask asyncTask) { public int sync(Context context, GTaskASyncTask asyncTask) {
if (mSyncing) { if (mSyncing) { // 如果正在同步中,返回同步进行中状态码
Log.d(TAG, "Sync is in progress"); Log.d(TAG, "Sync is in progress");
return STATE_SYNC_IN_PROGRESS; return STATE_SYNC_IN_PROGRESS;
} }
mContext = context; mContext = context; // 设置上下文
mContentResolver = mContext.getContentResolver(); mContentResolver = mContext.getContentResolver();
mSyncing = true; mSyncing = true; // 设置正在同步
mCancelled = false; mCancelled = false; // 设置未取消同步
mGTaskListHashMap.clear(); mGTaskListHashMap.clear(); // 清除任务列表哈希表
mGTaskHashMap.clear(); mGTaskHashMap.clear(); // 清除任务哈希表
mMetaHashMap.clear(); mMetaHashMap.clear(); // 清除元数据哈希表
mLocalDeleteIdMap.clear(); mLocalDeleteIdMap.clear(); // 清除本地删除ID哈希表
mGidToNid.clear(); mGidToNid.clear(); // 清除GID到NID的映射哈希表
mNidToGid.clear(); mNidToGid.clear(); // 清除NID到GID的映射哈希表
try { try {
GTaskClient client = GTaskClient.getInstance(); GTaskClient client = GTaskClient.getInstance(); // 获取GTaskClient实例
client.resetUpdateArray(); client.resetUpdateArray(); // 重置更新数组
// login google task // 登录Google任务
if (!mCancelled) { if (!mCancelled) {
if (!client.login(mActivity)) { if (!client.login(mActivity)) { // 如果登录失败抛出NetworkFailureException
throw new NetworkFailureException("login google task failed"); throw new NetworkFailureException("login google task failed");
} }
} }
// get the task list from google // 从Google获取任务列表
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); // 发布进度消息
initGTaskList(); initGTaskList();
// do content sync work // 进行内容同步
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); // 发布进度消息
syncContent(); syncContent();
} catch (NetworkFailureException e) { } catch (NetworkFailureException e) { // 如果发生网络错误,返回网络错误状态码
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
return STATE_NETWORK_ERROR; return STATE_NETWORK_ERROR;
} catch (ActionFailureException e) { } catch (ActionFailureException e) { // 如果发生操作失败,返回内部错误状态码
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
return STATE_INTERNAL_ERROR; return STATE_INTERNAL_ERROR;
} catch (Exception e) { } catch (Exception e) { // 如果发生其他异常,返回内部错误状态码
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
return STATE_INTERNAL_ERROR; return STATE_INTERNAL_ERROR;
} finally { } finally { // 在finally中清除哈希表并设置同步完成
mGTaskListHashMap.clear(); mGTaskListHashMap.clear();
mGTaskHashMap.clear(); mGTaskHashMap.clear();
mMetaHashMap.clear(); mMetaHashMap.clear();
@ -165,29 +152,38 @@ public class GTaskManager {
mSyncing = false; mSyncing = false;
} }
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; // 如果已取消同步,返回取消同步状态码,否则返回成功状态码
} }
/**
* GTaskList NetworkFailureException
*/
private void initGTaskList() throws NetworkFailureException { private void initGTaskList() throws NetworkFailureException {
// 如果已经取消则直接返回
if (mCancelled) if (mCancelled)
return; return;
// 获取 GTaskClient 的实例
GTaskClient client = GTaskClient.getInstance(); GTaskClient client = GTaskClient.getInstance();
try { try {
// 获取任务列表
JSONArray jsTaskLists = client.getTaskLists(); JSONArray jsTaskLists = client.getTaskLists();
// init meta list first // 首先初始化 Meta list
mMetaList = null; mMetaList = null;
for (int i = 0; i < jsTaskLists.length(); i++) { for (int i = 0; i < jsTaskLists.length(); i++) {
// 获取任务列表中的元素
JSONObject object = jsTaskLists.getJSONObject(i); JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
if (name // 如果名称为 GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META则初始化 Meta list
.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
mMetaList = new TaskList(); mMetaList = new TaskList();
mMetaList.setContentByRemoteJSON(object); mMetaList.setContentByRemoteJSON(object);
// load meta data // 加载 Meta 数据
JSONArray jsMetas = client.getTaskList(gid); JSONArray jsMetas = client.getTaskList(gid);
for (int j = 0; j < jsMetas.length(); j++) { for (int j = 0; j < jsMetas.length(); j++) {
object = (JSONObject) jsMetas.getJSONObject(j); object = (JSONObject) jsMetas.getJSONObject(j);
@ -203,29 +199,28 @@ public class GTaskManager {
} }
} }
// create meta list if not existed // 如果 Meta list 不存在,则创建一个新的 Meta list
if (mMetaList == null) { if (mMetaList == null) {
mMetaList = new TaskList(); mMetaList = new TaskList();
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META);
+ GTaskStringUtils.FOLDER_META);
GTaskClient.getInstance().createTaskList(mMetaList); GTaskClient.getInstance().createTaskList(mMetaList);
} }
// init task list // 初始化任务列表
for (int i = 0; i < jsTaskLists.length(); i++) { for (int i = 0; i < jsTaskLists.length(); i++) {
// 获取任务列表中的元素
JSONObject object = jsTaskLists.getJSONObject(i); JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) // 如果名称以 GTaskStringUtils.MIUI_FOLDER_PREFFIX 开头且不是 Meta list则初始化任务列表
&& !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
+ GTaskStringUtils.FOLDER_META)) {
TaskList tasklist = new TaskList(); TaskList tasklist = new TaskList();
tasklist.setContentByRemoteJSON(object); tasklist.setContentByRemoteJSON(object);
mGTaskListHashMap.put(gid, tasklist); mGTaskListHashMap.put(gid, tasklist);
mGTaskHashMap.put(gid, tasklist); mGTaskHashMap.put(gid, tasklist);
// load tasks // 加载任务
JSONArray jsTasks = client.getTaskList(gid); JSONArray jsTasks = client.getTaskList(gid);
for (int j = 0; j < jsTasks.length(); j++) { for (int j = 0; j < jsTasks.length(); j++) {
object = (JSONObject) jsTasks.getJSONObject(j); object = (JSONObject) jsTasks.getJSONObject(j);
@ -241,25 +236,27 @@ public class GTaskManager {
} }
} }
} catch (JSONException e) { } catch (JSONException e) {
// 如果处理 JSONObject 失败,则抛出 ActionFailureException 异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("initGTaskList: handing JSONObject failed"); throw new ActionFailureException("initGTaskList: handing JSONObject failed");
} }
} }
private void syncContent() throws NetworkFailureException { private void syncContent() throws NetworkFailureException {
int syncType; int syncType; // 同步类型
Cursor c = null; Cursor c = null; // 游标
String gid; String gid; // GTasks ID
Node node; Node node; // 节点
mLocalDeleteIdMap.clear(); mLocalDeleteIdMap.clear(); // 清空本地删除ID映射表
if (mCancelled) { if (mCancelled) { // 如果已经取消了同步,直接返回
return; return;
} }
// for local deleted note // 处理本地已删除的笔记
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id=?)", new String[] { "(type<>? AND parent_id=?)", new String[] {
@ -271,13 +268,13 @@ public class GTaskManager {
node = mGTaskHashMap.get(gid); node = mGTaskHashMap.get(gid);
if (node != null) { if (node != null) {
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);
doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c); doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c); // 执行删除远程同步操作
} }
mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); // 添加到本地删除ID映射表
} }
} else { } else {
Log.w(TAG, "failed to query trash folder"); Log.w(TAG, "failed to query trash folder"); // 查询回收站失败
} }
} finally { } finally {
if (c != null) { if (c != null) {
@ -286,10 +283,10 @@ public class GTaskManager {
} }
} }
// sync folder first // 同步文件夹
syncFolder(); syncFolder();
// for note existing in database // 处理数据库中已存在的笔记
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] { "(type=? AND parent_id<>?)", new String[] {
@ -303,20 +300,20 @@ public class GTaskManager {
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);
mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
syncType = node.getSyncAction(c); syncType = node.getSyncAction(c); // 获取同步类型
} else { } else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add // 本地新增
syncType = Node.SYNC_ACTION_ADD_REMOTE; syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else { } else {
// remote delete // 远程删除
syncType = Node.SYNC_ACTION_DEL_LOCAL; syncType = Node.SYNC_ACTION_DEL_LOCAL;
} }
} }
doContentSync(syncType, node, c); doContentSync(syncType, node, c); // 执行同步操作
} }
} else { } else {
Log.w(TAG, "failed to query existing note in database"); Log.w(TAG, "failed to query existing note in database"); // 查询已存在的笔记失败
} }
} finally { } finally {
@ -326,42 +323,43 @@ public class GTaskManager {
} }
} }
// go through remaining items // 处理剩余的节点
Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator(); Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
Map.Entry<String, Node> entry = iter.next(); Map.Entry<String, Node> entry = iter.next();
node = entry.getValue(); node = entry.getValue();
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); 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 (!mCancelled) {
if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) { if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) { // 批量删除本地已删除笔记
throw new ActionFailureException("failed to batch-delete local deleted notes"); throw new ActionFailureException("failed to batch-delete local deleted notes");
} }
} }
// refresh local sync id // 刷新本地同步ID
if (!mCancelled) { if (!mCancelled) {
GTaskClient.getInstance().commitUpdate(); GTaskClient.getInstance().commitUpdate(); // 提交更新
refreshLocalSyncId(); refreshLocalSyncId(); // 刷新本地同步ID
} }
} }
/**
*
* @throws NetworkFailureException
*/
private void syncFolder() throws NetworkFailureException { private void syncFolder() throws NetworkFailureException {
Cursor c = null; Cursor c = null; // 游标对象,用于查询数据库
String gid; String gid; // Google Tasks ID
Node node; Node node; // Google Tasks 中的节点
int syncType; int syncType; // 同步类型
if (mCancelled) { if (mCancelled) { // 如果已取消同步,则直接返回
return; return;
} }
// for root folder // 同步根文件夹
try { try {
c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null); Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
@ -369,15 +367,15 @@ public class GTaskManager {
c.moveToNext(); c.moveToNext();
gid = c.getString(SqlNote.GTASK_ID_COLUMN); gid = c.getString(SqlNote.GTASK_ID_COLUMN);
node = mGTaskHashMap.get(gid); node = mGTaskHashMap.get(gid);
if (node != null) { if (node != null) { // Google Tasks 中存在该节点
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER); mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER);
mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid); mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid);
// for system folder, only update remote name if necessary // 如果节点名称不是默认名称,则更新远程名称
if (!node.getName().equals( if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
} else { } else { // Google Tasks 中不存在该节点
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
} }
} else { } else {
@ -390,27 +388,26 @@ public class GTaskManager {
} }
} }
// for call-note folder // 同步通话记录文件夹
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)", c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)",
new String[] { new String[] {
String.valueOf(Notes.ID_CALL_RECORD_FOLDER) String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
}, null); }, null);
if (c != null) { if (c != null) {
if (c.moveToNext()) { if (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN); gid = c.getString(SqlNote.GTASK_ID_COLUMN);
node = mGTaskHashMap.get(gid); node = mGTaskHashMap.get(gid);
if (node != null) { if (node != null) { // Google Tasks 中存在该节点
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER); mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);
mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid); mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid);
// for system folder, only update remote name if // 如果节点名称不是默认名称,则更新远程名称
// necessary
if (!node.getName().equals( if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE)) + GTaskStringUtils.FOLDER_CALL_NOTE))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
} else { } else { // Google Tasks 中不存在该节点
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
} }
} }
@ -424,7 +421,7 @@ public class GTaskManager {
} }
} }
// for local existing folders // 同步本地已存在文件夹
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] { "(type=? AND parent_id<>?)", new String[] {
@ -434,17 +431,17 @@ public class GTaskManager {
while (c.moveToNext()) { while (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN); gid = c.getString(SqlNote.GTASK_ID_COLUMN);
node = mGTaskHashMap.get(gid); node = mGTaskHashMap.get(gid);
if (node != null) { if (node != null) { // Google Tasks 中存在该节点
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);
mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
syncType = node.getSyncAction(c); syncType = node.getSyncAction(c);
} else { } else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add // 本地新增
syncType = Node.SYNC_ACTION_ADD_REMOTE; syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else { } else {
// remote delete // 远程删除
syncType = Node.SYNC_ACTION_DEL_LOCAL; syncType = Node.SYNC_ACTION_DEL_LOCAL;
} }
} }
@ -460,22 +457,30 @@ public class GTaskManager {
} }
} }
// for remote add folders // 为远程添加文件夹
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator(); Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator(); // 迭代 mGTaskListHashMap 中的每一个元素
while (iter.hasNext()) { while (iter.hasNext()) { // 如果还有下一个元素
Map.Entry<String, TaskList> entry = iter.next(); Map.Entry<String, TaskList> entry = iter.next(); // 获取下一个元素
gid = entry.getKey(); gid = entry.getKey(); // 获取元素的键
node = entry.getValue(); node = entry.getValue(); // 获取元素的值
if (mGTaskHashMap.containsKey(gid)) { if (mGTaskHashMap.containsKey(gid)) { // 如果 mGTaskHashMap 中包含该键
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid); // 从 mGTaskHashMap 中删除该键值对
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); // 执行 doContentSync 方法,并传入 SYNC_ACTION_ADD_LOCAL、node 和 null 三个参数
} }
} }
if (!mCancelled) if (!mCancelled) // 如果 mCancelled 为假
GTaskClient.getInstance().commitUpdate(); GTaskClient.getInstance().commitUpdate(); // 执行 GTaskClient.getInstance().commitUpdate() 方法
} }
/**
*
*
* @param syncType
* @param node
* @param c
* @throws NetworkFailureException
*/
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException { private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -484,12 +489,15 @@ public class GTaskManager {
MetaData meta; MetaData meta;
switch (syncType) { switch (syncType) {
case Node.SYNC_ACTION_ADD_LOCAL: case Node.SYNC_ACTION_ADD_LOCAL:
// 添加本地节点
addLocalNode(node); addLocalNode(node);
break; break;
case Node.SYNC_ACTION_ADD_REMOTE: case Node.SYNC_ACTION_ADD_REMOTE:
// 添加远程节点
addRemoteNode(node, c); addRemoteNode(node, c);
break; break;
case Node.SYNC_ACTION_DEL_LOCAL: case Node.SYNC_ACTION_DEL_LOCAL:
// 删除本地节点
meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN)); meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN));
if (meta != null) { if (meta != null) {
GTaskClient.getInstance().deleteNode(meta); GTaskClient.getInstance().deleteNode(meta);
@ -497,6 +505,7 @@ public class GTaskManager {
mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
break; break;
case Node.SYNC_ACTION_DEL_REMOTE: case Node.SYNC_ACTION_DEL_REMOTE:
// 删除远程节点
meta = mMetaHashMap.get(node.getGid()); meta = mMetaHashMap.get(node.getGid());
if (meta != null) { if (meta != null) {
GTaskClient.getInstance().deleteNode(meta); GTaskClient.getInstance().deleteNode(meta);
@ -504,52 +513,69 @@ public class GTaskManager {
GTaskClient.getInstance().deleteNode(node); GTaskClient.getInstance().deleteNode(node);
break; break;
case Node.SYNC_ACTION_UPDATE_LOCAL: case Node.SYNC_ACTION_UPDATE_LOCAL:
// 更新本地节点
updateLocalNode(node, c); updateLocalNode(node, c);
break; break;
case Node.SYNC_ACTION_UPDATE_REMOTE: case Node.SYNC_ACTION_UPDATE_REMOTE:
// 更新远程节点
updateRemoteNode(node, c); updateRemoteNode(node, c);
break; break;
case Node.SYNC_ACTION_UPDATE_CONFLICT: case Node.SYNC_ACTION_UPDATE_CONFLICT:
// merging both modifications maybe a good idea // 合并两个修改可能是个好主意
// right now just use local update simply // 目前只使用本地更新
updateRemoteNode(node, c); updateRemoteNode(node, c);
break; break;
case Node.SYNC_ACTION_NONE: case Node.SYNC_ACTION_NONE:
// 无同步操作
break; break;
case Node.SYNC_ACTION_ERROR: case Node.SYNC_ACTION_ERROR:
default: default:
throw new ActionFailureException("unkown sync action type"); // 未知同步操作类型异常
throw new ActionFailureException("未知的同步操作类型");
} }
} }
/**
*
*
* @param node
* @throws NetworkFailureException
*/
private void addLocalNode(Node node) throws NetworkFailureException { private void addLocalNode(Node node) throws NetworkFailureException {
// 如果已经取消了添加操作,则直接返回
if (mCancelled) { if (mCancelled) {
return; return;
} }
SqlNote sqlNote; SqlNote sqlNote;
// 根据节点类型创建要添加的节点对象
if (node instanceof TaskList) { if (node instanceof TaskList) {
if (node.getName().equals( if (node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) { GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
// 如果是默认文件夹,则将其作为根节点添加
sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER); sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER);
} else if (node.getName().equals( } else if (node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) { GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) {
// 如果是通话记录文件夹,则将其作为通话记录文件夹添加
sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER); sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER);
} else { } else {
// 否则创建一个普通的节点对象,将传入的节点信息添加到其中
sqlNote = new SqlNote(mContext); sqlNote = new SqlNote(mContext);
sqlNote.setContent(node.getLocalJSONFromContent()); sqlNote.setContent(node.getLocalJSONFromContent());
sqlNote.setParentId(Notes.ID_ROOT_FOLDER); sqlNote.setParentId(Notes.ID_ROOT_FOLDER);
} }
} else { } else {
// 创建一个普通的节点对象,将传入的节点信息添加到其中
sqlNote = new SqlNote(mContext); sqlNote = new SqlNote(mContext);
JSONObject js = node.getLocalJSONFromContent(); JSONObject js = node.getLocalJSONFromContent();
try { try {
// 更新节点信息中的元数据信息
if (js.has(GTaskStringUtils.META_HEAD_NOTE)) { if (js.has(GTaskStringUtils.META_HEAD_NOTE)) {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.has(NoteColumns.ID)) { if (note.has(NoteColumns.ID)) {
long id = note.getLong(NoteColumns.ID); long id = note.getLong(NoteColumns.ID);
if (DataUtils.existInNoteDatabase(mContentResolver, id)) { if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
// the id is not available, have to create a new one // 如果该id已存在于本地数据库中则需要创建一个新的id
note.remove(NoteColumns.ID); note.remove(NoteColumns.ID);
} }
} }
@ -562,91 +588,110 @@ public class GTaskManager {
if (data.has(DataColumns.ID)) { if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID); long dataId = data.getLong(DataColumns.ID);
if (DataUtils.existInDataDatabase(mContentResolver, dataId)) { if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
// the data id is not available, have to create // 如果该id已存在于本地数据库中则需要创建一个新的id
// a new one
data.remove(DataColumns.ID); data.remove(DataColumns.ID);
} }
} }
} }
} }
} catch (JSONException e) { } catch (JSONException e) {
Log.w(TAG, e.toString()); Log.w(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
} }
// 将更新后的节点信息添加到要创建的节点对象中
sqlNote.setContent(js); sqlNote.setContent(js);
// 获取要添加的节点的父节点在本地数据库中的id
Long parentId = mGidToNid.get(((Task) node).getParent().getGid()); Long parentId = mGidToNid.get(((Task) node).getParent().getGid());
if (parentId == null) { if (parentId == null) {
// 如果没有找到父节点的id则抛出异常
Log.e(TAG, "cannot find task's parent id locally"); Log.e(TAG, "cannot find task's parent id locally");
throw new ActionFailureException("cannot add local node"); throw new ActionFailureException("cannot add local node");
} }
// 将父节点的id添加到要创建的节点对象中
sqlNote.setParentId(parentId.longValue()); sqlNote.setParentId(parentId.longValue());
} }
// create the local node // 设置要创建的节点对象的gid
sqlNote.setGtaskId(node.getGid()); sqlNote.setGtaskId(node.getGid());
// 将要创建的节点对象添加到本地数据库中
sqlNote.commit(false); sqlNote.commit(false);
// update gid-nid mapping // 更新gid-nid映射表
mGidToNid.put(node.getGid(), sqlNote.getId()); mGidToNid.put(node.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), node.getGid()); mNidToGid.put(sqlNote.getId(), node.getGid());
// update meta // 更新元数据信息
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
} }
/**
*
*
* @param node
* @param c
* @throws NetworkFailureException
*/
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException { private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
// 如果已经取消了更新操作,则直接返回
if (mCancelled) { if (mCancelled) {
return; return;
} }
SqlNote sqlNote; SqlNote sqlNote;
// update the note locally // 根据游标对象获取要更新的节点的信息
sqlNote = new SqlNote(mContext, c); sqlNote = new SqlNote(mContext, c);
// 将传入的节点信息更新到要更新的节点中
sqlNote.setContent(node.getLocalJSONFromContent()); sqlNote.setContent(node.getLocalJSONFromContent());
// 根据节点类型获取要更新节点的父节点的ID
Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid()) Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid())
: new Long(Notes.ID_ROOT_FOLDER); : new Long(Notes.ID_ROOT_FOLDER);
// 如果父节点ID为空则抛出异常
if (parentId == null) { if (parentId == null) {
Log.e(TAG, "cannot find task's parent id locally"); Log.e(TAG, "cannot find task's parent id locally");
throw new ActionFailureException("cannot update local node"); throw new ActionFailureException("cannot update local node");
} }
// 设置要更新节点的父节点ID
sqlNote.setParentId(parentId.longValue()); sqlNote.setParentId(parentId.longValue());
// 提交更新操作
sqlNote.commit(true); sqlNote.commit(true);
// update meta info // 更新远程节点的元数据信息
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
} }
//这段Java代码实现了一个添加远程节点的方法下面我们逐行进行详细的注释说明
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException { private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
//这是一个私有方法,用于添加远程节点。它需要传入一个节点对象和一个光标对象。如果添加过程中出现网络失败,将会抛出
// NetworkFailureException 异常。
if (mCancelled) { if (mCancelled) {
return; return;
} }
//如果任务已被取消,直接返回。
SqlNote sqlNote = new SqlNote(mContext, c); SqlNote sqlNote = new SqlNote(mContext, c);
Node n; Node n;
//创建一个 SqlNote 对象和一个 Node 对象。
// update remotely
if (sqlNote.isNoteType()) { if (sqlNote.isNoteType()) {
Task task = new Task(); Task task = new Task();
task.setContentByLocalJSON(sqlNote.getContent()); task.setContentByLocalJSON(sqlNote.getContent());
//如果 SqlNote 对象表示的是笔记类型,则创建一个 Task 对象,并使用 SqlNote 对象的 getContent() 方法获取本地 JSON 内容,
// 将其设置为 Task 对象的内容。
String parentGid = mNidToGid.get(sqlNote.getParentId()); String parentGid = mNidToGid.get(sqlNote.getParentId());
if (parentGid == null) { if (parentGid == null) {
Log.e(TAG, "cannot find task's parent tasklist"); Log.e(TAG, "cannot find task's parent tasklist");
throw new ActionFailureException("cannot add remote task"); throw new ActionFailureException("cannot add remote task");
} }
mGTaskListHashMap.get(parentGid).addChildTask(task); mGTaskListHashMap.get(parentGid).addChildTask(task);
//获取该笔记的父级任务列表的 GID如果不存在则抛出异常。然后将该任务添加到父级任务列表中。
GTaskClient.getInstance().createTask(task); GTaskClient.getInstance().createTask(task);
n = (Node) task; n = (Node) task;
//使用 GTaskClient 创建该任务,并将其转换为 Node 对象。
// add meta
updateRemoteMeta(task.getGid(), sqlNote); updateRemoteMeta(task.getGid(), sqlNote);
//更新远程元数据。
} else { } else {
TaskList tasklist = null; TaskList tasklist = null;
//如果 SqlNote 对象表示的是文件夹类型,则创建一个 TaskList 对象。
// we need to skip folder if it has already existed // we need to skip folder if it has already existed
String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX; String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;
if (sqlNote.getId() == Notes.ID_ROOT_FOLDER) if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)
@ -655,7 +700,7 @@ public class GTaskManager {
folderName += GTaskStringUtils.FOLDER_CALL_NOTE; folderName += GTaskStringUtils.FOLDER_CALL_NOTE;
else else
folderName += sqlNote.getSnippet(); folderName += sqlNote.getSnippet();
//获取文件夹的名称。如果是根文件夹,则使用默认名称;如果是通话记录文件夹,则使用特定的名称;否则使用 SqlNote 对象的摘录作为名称。
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator(); Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next(); Map.Entry<String, TaskList> entry = iter.next();
@ -670,7 +715,7 @@ public class GTaskManager {
break; break;
} }
} }
//遍历任务列表哈希表,查找是否存在同名任务列表。如果存在,则将其作为 tasklist 对象;否则 tasklist 对象为空。
// no match we can add now // no match we can add now
if (tasklist == null) { if (tasklist == null) {
tasklist = new TaskList(); tasklist = new TaskList();
@ -679,38 +724,60 @@ public class GTaskManager {
mGTaskListHashMap.put(tasklist.getGid(), tasklist); mGTaskListHashMap.put(tasklist.getGid(), tasklist);
} }
n = (Node) tasklist; n = (Node) tasklist;
//如果 tasklist 对象为空,则创建新的任务列表,并使用本地 JSON 内容初始化其内容。
// 然后使用 GTaskClient 创建该任务列表,并将其添加到任务列表哈希表中。然后将 tasklist 转换为 Node 对象。
} }
// update local note // update local note
sqlNote.setGtaskId(n.getGid()); sqlNote.setGtaskId(n.getGid());
sqlNote.commit(false); sqlNote.commit(false);
sqlNote.resetLocalModified(); sqlNote.resetLocalModified();
sqlNote.commit(true); sqlNote.commit(true);
//更新本地笔记的 GID并将其标记为已提交。
// gid-id mapping
mGidToNid.put(n.getGid(), sqlNote.getId()); mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid()); mNidToGid.put(sqlNote.getId(), n.getGid());
//更新 GID 和 ID 之间的映射。
} }
//这段Java代码的主要作用是更新远程云端的节点和元数据。
/**
1. `updateRemoteNode()``node``c``Cursor`
2. `mCancelled``true`
3. `Cursor``SqlNote`
4. `node``setContentByLocalJSON()`
5. `GTaskClient`
6. `updateRemoteMeta()`
7.
8.
9. `updateRemoteMeta()``gid``sqlNote``SqlNote`
10. `sqlNote``null`
11.
12. `GTaskClient`
13.
*/
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException { private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
} }
// 根据Cursor对象创建SqlNote对象
SqlNote sqlNote = new SqlNote(mContext, c); SqlNote sqlNote = new SqlNote(mContext, c);
// update remotely // 更新节点的内容
node.setContentByLocalJSON(sqlNote.getContent()); node.setContentByLocalJSON(sqlNote.getContent());
// 将更新后的节点添加到GTaskClient任务列表中
GTaskClient.getInstance().addUpdateNode(node); GTaskClient.getInstance().addUpdateNode(node);
// update meta // 更新元数据
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
// move task if necessary // 如果需要移动任务,则更新任务的父任务列表
if (sqlNote.isNoteType()) { if (sqlNote.isNoteType()) {
Task task = (Task) node; Task task = (Task) node;
TaskList preParentList = task.getParent(); TaskList preParentList = task.getParent();
// 获取当前任务的父任务列表
String curParentGid = mNidToGid.get(sqlNote.getParentId()); String curParentGid = mNidToGid.get(sqlNote.getParentId());
if (curParentGid == null) { if (curParentGid == null) {
Log.e(TAG, "cannot find task's parent tasklist"); Log.e(TAG, "cannot find task's parent tasklist");
@ -718,6 +785,7 @@ public class GTaskManager {
} }
TaskList curParentList = mGTaskListHashMap.get(curParentGid); TaskList curParentList = mGTaskListHashMap.get(curParentGid);
// 如果当前任务的父任务列表和之前的不同,则移动任务到新的父任务列表中
if (preParentList != curParentList) { if (preParentList != curParentList) {
preParentList.removeChildTask(task); preParentList.removeChildTask(task);
curParentList.addChildTask(task); curParentList.addChildTask(task);
@ -725,18 +793,22 @@ public class GTaskManager {
} }
} }
// clear local modified flag // 清除本地修改标志
sqlNote.resetLocalModified(); sqlNote.resetLocalModified();
sqlNote.commit(true); sqlNote.commit(true);
} }
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException { private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
if (sqlNote != null && sqlNote.isNoteType()) { if (sqlNote != null && sqlNote.isNoteType()) {
// 获取元数据对象
MetaData metaData = mMetaHashMap.get(gid); MetaData metaData = mMetaHashMap.get(gid);
if (metaData != null) { if (metaData != null) {
// 更新元数据
metaData.setMeta(gid, sqlNote.getContent()); metaData.setMeta(gid, sqlNote.getContent());
// 将更新后的元数据添加到GTaskClient任务列表中
GTaskClient.getInstance().addUpdateNode(metaData); GTaskClient.getInstance().addUpdateNode(metaData);
} else { } else {
// 创建新的元数据对象并添加到任务列表中
metaData = new MetaData(); metaData = new MetaData();
metaData.setMeta(gid, sqlNote.getContent()); metaData.setMeta(gid, sqlNote.getContent());
mMetaList.addChildTask(metaData); mMetaList.addChildTask(metaData);
@ -746,12 +818,17 @@ public class GTaskManager {
} }
} }
/**
* ID
* @throws NetworkFailureException
*/
private void refreshLocalSyncId() throws NetworkFailureException { private void refreshLocalSyncId() throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
} }
// get the latest gtask list // 获取最新的gtask列表
mGTaskHashMap.clear(); mGTaskHashMap.clear();
mGTaskListHashMap.clear(); mGTaskListHashMap.clear();
mMetaHashMap.clear(); mMetaHashMap.clear();
@ -759,6 +836,7 @@ public class GTaskManager {
Cursor c = null; Cursor c = null;
try { try {
// 查询本地笔记,排除系统笔记和回收站笔记
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, 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) String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
@ -790,10 +868,17 @@ public class GTaskManager {
} }
} }
/**
*
* @return
*/
public String getSyncAccount() { public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name; return GTaskClient.getInstance().getSyncAccount().name;
} }
/**
*
*/
public void cancelSync() { public void cancelSync() {
mCancelled = true; mCancelled = true;
} }

@ -23,25 +23,36 @@ import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.os.IBinder; import android.os.IBinder;
// GTaskSyncService 类,继承自 Service 类,用于同步任务
public class GTaskSyncService extends Service { public class GTaskSyncService extends Service {
// 定义动作类型字符串常量
public final static String ACTION_STRING_NAME = "sync_action_type"; public final static String ACTION_STRING_NAME = "sync_action_type";
// 定义开始同步动作常量
public final static int ACTION_START_SYNC = 0; public final static int ACTION_START_SYNC = 0;
// 定义取消同步动作常量
public final static int ACTION_CANCEL_SYNC = 1; public final static int ACTION_CANCEL_SYNC = 1;
// 定义无效动作常量
public final static int ACTION_INVALID = 2; 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_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_IS_SYNCING = "isSyncing";
// 定义广播进度消息字符串常量
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg"; public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
// 定义静态的 GTaskASyncTask 对象
private static GTaskASyncTask mSyncTask = null; private static GTaskASyncTask mSyncTask = null;
// 定义静态的同步进度字符串
private static String mSyncProgress = ""; private static String mSyncProgress = "";
// 开始同步的方法
private void startSync() { private void startSync() {
if (mSyncTask == null) { if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
@ -56,17 +67,20 @@ public class GTaskSyncService extends Service {
} }
} }
// 取消同步的方法
private void cancelSync() { private void cancelSync() {
if (mSyncTask != null) { if (mSyncTask != null) {
mSyncTask.cancelSync(); mSyncTask.cancelSync();
} }
} }
// 重写 onCreate 方法
@Override @Override
public void onCreate() { public void onCreate() {
mSyncTask = null; mSyncTask = null;
} }
// 重写 onStartCommand 方法
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras(); Bundle bundle = intent.getExtras();
@ -86,6 +100,7 @@ public class GTaskSyncService extends Service {
return super.onStartCommand(intent, flags, startId); return super.onStartCommand(intent, flags, startId);
} }
// 重写 onLowMemory 方法
@Override @Override
public void onLowMemory() { public void onLowMemory() {
if (mSyncTask != null) { if (mSyncTask != null) {
@ -93,10 +108,12 @@ public class GTaskSyncService extends Service {
} }
} }
// 重写 onBind 方法
public IBinder onBind(Intent intent) { public IBinder onBind(Intent intent) {
return null; return null;
} }
// 发送广播的方法
public void sendBroadcast(String msg) { public void sendBroadcast(String msg) {
mSyncProgress = msg; mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
@ -105,6 +122,7 @@ public class GTaskSyncService extends Service {
sendBroadcast(intent); sendBroadcast(intent);
} }
// 开始同步的静态方法
public static void startSync(Activity activity) { public static void startSync(Activity activity) {
GTaskManager.getInstance().setActivityContext(activity); GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class); Intent intent = new Intent(activity, GTaskSyncService.class);
@ -112,16 +130,19 @@ public class GTaskSyncService extends Service {
activity.startService(intent); activity.startService(intent);
} }
// 取消同步的静态方法
public static void cancelSync(Context context) { public static void cancelSync(Context context) {
Intent intent = new Intent(context, GTaskSyncService.class); Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent); context.startService(intent);
} }
// 判断是否正在同步的静态方法
public static boolean isSyncing() { public static boolean isSyncing() {
return mSyncTask != null; return mSyncTask != null;
} }
// 获取进度字符串的静态方法
public static String getProgressString() { public static String getProgressString() {
return mSyncProgress; return mSyncProgress;
} }

Loading…
Cancel
Save