master
何越 3 years ago
parent 6b12b41243
commit 727d916a6e

@ -19,14 +19,17 @@ package net.micode.notes.gtask.exception;
public class NetworkFailureException extends Exception { public class NetworkFailureException extends Exception {
private static final long serialVersionUID = 2107610287180234136L; private static final long serialVersionUID = 2107610287180234136L;
// 无参构造函数
public NetworkFailureException() { public NetworkFailureException() {
super(); super();
} }
// 构造函数,接受一个字符串消息作为参数
public NetworkFailureException(String paramString) { public NetworkFailureException(String paramString) {
super(paramString); super(paramString);
} }
// 构造函数,接受一个字符串消息和一个可抛出对象作为参数
public NetworkFailureException(String paramString, Throwable paramThrowable) { public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable); super(paramString, paramThrowable);
} }

@ -15,24 +15,11 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.remote;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> { public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
// 定义回调接口 OnCompleteListener
public interface OnCompleteListener { public interface OnCompleteListener {
void onComplete(); void onComplete();
} }
@ -45,6 +32,7 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
private OnCompleteListener mOnCompleteListener; private OnCompleteListener mOnCompleteListener;
// 构造函数,初始化成员变量
public GTaskASyncTask(Context context, OnCompleteListener listener) { public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context; mContext = context;
mOnCompleteListener = listener; mOnCompleteListener = listener;
@ -53,16 +41,19 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
mTaskManager = GTaskManager.getInstance(); mTaskManager = GTaskManager.getInstance();
} }
// 取消同步
public void cancelSync() { public void cancelSync() {
mTaskManager.cancelSync(); mTaskManager.cancelSync();
} }
// 发布进度
public void publishProgess(String message) { public void publishProgess(String message) {
publishProgress(new String[] { publishProgress(new String[] {
message message
}); });
} }
// 显示通知
private void showNotification(int tickerId, String content) { private void showNotification(int tickerId, String content) {
Notification notification = new Notification(R.drawable.notification, mContext Notification notification = new Notification(R.drawable.notification, mContext
.getString(tickerId), System.currentTimeMillis()); .getString(tickerId), System.currentTimeMillis());
@ -77,8 +68,8 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0); NotesListActivity.class), 0);
} }
/*notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, //notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
pendingIntent);*/ // pendingIntent);
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
} }
@ -86,6 +77,7 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
protected Integer doInBackground(Void... unused) { protected Integer doInBackground(Void... unused) {
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext))); .getSyncAccountName(mContext)));
// 执行同步任务,返回状态码
return mTaskManager.sync(mContext, this); return mTaskManager.sync(mContext, this);
} }
@ -99,6 +91,7 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
@Override @Override
protected void onPostExecute(Integer result) { protected void onPostExecute(Integer result) {
// 根据状态码显示通知
if (result == GTaskManager.STATE_SUCCESS) { if (result == GTaskManager.STATE_SUCCESS) {
showNotification(R.string.ticker_success, mContext.getString( showNotification(R.string.ticker_success, mContext.getString(
R.string.success_sync_account, mTaskManager.getSyncAccount())); R.string.success_sync_account, mTaskManager.getSyncAccount()));
@ -111,6 +104,7 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
showNotification(R.string.ticker_cancel, mContext showNotification(R.string.ticker_cancel, mContext
.getString(R.string.error_sync_cancelled)); .getString(R.string.error_sync_cancelled));
} }
if (mOnCompleteListener != null) { if (mOnCompleteListener != null) {
new Thread(new Runnable() { new Thread(new Runnable() {

@ -90,6 +90,10 @@ public class GTaskClient {
private JSONArray mUpdateArray; private JSONArray mUpdateArray;
// 定义一个GTaskClient类用于管理Google任务API
public class GTaskClient {
// 初始化GTaskClient类的私有构造函数
private GTaskClient() { private GTaskClient() {
mHttpClient = null; mHttpClient = null;
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL;
@ -102,6 +106,7 @@ public class GTaskClient {
mUpdateArray = null; mUpdateArray = null;
} }
// 创建一个静态的GTaskClient实例确保线程安全
public static synchronized GTaskClient getInstance() { public static synchronized GTaskClient getInstance() {
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskClient(); mInstance = new GTaskClient();
@ -110,17 +115,14 @@ public class GTaskClient {
} }
public boolean login(Activity activity) { public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes // 假设cookie在5分钟后会过期所以需要重新登录
// then we need to re-login
final long interval = 1000 * 60 * 5; final long interval = 1000 * 60 * 5;
if (mLastLoginTime + interval < System.currentTimeMillis()) { if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false; mLoggedin = false;
} }
// need to re-login after account switch // 如果帐户发生变化,则需要重新登录
if (mLoggedin if (mLoggedin && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity.getSyncAccountName(activity))) {
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) {
mLoggedin = false; mLoggedin = false;
} }
@ -136,9 +138,8 @@ public class GTaskClient {
return false; return false;
} }
// login with custom domain if necessary // 如果需要,使用自定义域名进行登录
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase().endsWith("googlemail.com"))) {
.endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
int index = mAccount.name.indexOf('@') + 1; int index = mAccount.name.indexOf('@') + 1;
String suffix = mAccount.name.substring(index); String suffix = mAccount.name.substring(index);
@ -151,7 +152,7 @@ public class GTaskClient {
} }
} }
// try to login with google official url // 尝试使用Google官方URL进行登录
if (!mLoggedin) { if (!mLoggedin) {
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL; mPostUrl = GTASK_POST_URL;
@ -164,6 +165,7 @@ public class GTaskClient {
return true; return true;
} }
// 登录Google账户获取授权令牌
private String loginGoogleAccount(Activity activity, boolean invalidateToken) { private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken; String authToken;
AccountManager accountManager = AccountManager.get(activity); AccountManager accountManager = AccountManager.get(activity);
@ -189,13 +191,14 @@ public class GTaskClient {
return null; return null;
} }
// get the token now // 获取授权令牌
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account, AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null); "goanna_mobile", null, activity, null, null);
try { try {
Bundle authTokenBundle = accountManagerFuture.getResult(); Bundle authTokenBundle = accountManagerFuture.getResult();
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
if (invalidateToken) { if (invalidateToken) {
// 使令牌无效,并重新获取令牌
accountManager.invalidateAuthToken("com.google", authToken); accountManager.invalidateAuthToken("com.google", authToken);
loginGoogleAccount(activity, false); loginGoogleAccount(activity, false);
} }
@ -207,43 +210,62 @@ public class GTaskClient {
return authToken; return authToken;
} }
// 尝试使用授权令牌进行Gtask登录
/**
* 使 Gtask
*
* @param activity Activity
* @param authToken Gtask
* @return true false
*/
private boolean tryToLoginGtask(Activity activity, String authToken) { private boolean tryToLoginGtask(Activity activity, String authToken) {
// 如果无法成功登录 Gtask 服务,则进行以下处理。
if (!loginGtask(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); authToken = loginGoogleAccount(activity, true);
// 如果登录谷歌帐号失败,则返回 false。
if (authToken == null) { if (authToken == null) {
Log.e(TAG, "login google account failed"); Log.e(TAG, "login google account failed");
return false; return false;
} }
// 如果仍然无法成功登录 Gtask 服务,则返回 false。
if (!loginGtask(authToken)) { if (!loginGtask(authToken)) {
Log.e(TAG, "login gtask failed"); Log.e(TAG, "login gtask failed");
return false; return false;
} }
} }
// 如果登录成功,则返回 true。
return true; return true;
} }
/**
* 使 Gtask
*
* @param authToken Gtask
* @return true false
*/
private boolean loginGtask(String authToken) { private boolean loginGtask(String authToken) {
// 配置 HTTP 连接参数。
int timeoutConnection = 10000; int timeoutConnection = 10000;
int timeoutSocket = 15000; int timeoutSocket = 15000;
HttpParams httpParameters = new BasicHttpParams(); HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// 创建 HTTP 客户端。
mHttpClient = new DefaultHttpClient(httpParameters); mHttpClient = new DefaultHttpClient(httpParameters);
BasicCookieStore localBasicCookieStore = new BasicCookieStore(); BasicCookieStore localBasicCookieStore = new BasicCookieStore();
mHttpClient.setCookieStore(localBasicCookieStore); mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// login gtask // 使用身份验证令牌登录 Gtask 服务。
try { try {
String loginUrl = mGetUrl + "?auth=" + authToken; String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl); HttpGet httpGet = new HttpGet(loginUrl);
HttpResponse response = null; HttpResponse response = mHttpClient.execute(httpGet);
response = mHttpClient.execute(httpGet);
// get the cookie now // 获取 Cookie。
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies(); List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false; boolean hasAuthCookie = false;
for (Cookie cookie : cookies) { for (Cookie cookie : cookies) {
@ -255,7 +277,7 @@ public class GTaskClient {
Log.w(TAG, "it seems that there is no auth cookie"); Log.w(TAG, "it seems that there is no auth cookie");
} }
// get the client version // 获取客户端版本。
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup("; String jsBegin = "_setup(";
String jsEnd = ")}</script>"; String jsEnd = ")}</script>";
@ -272,7 +294,6 @@ public class GTaskClient {
e.printStackTrace(); e.printStackTrace();
return false; return false;
} catch (Exception e) { } catch (Exception e) {
// simply catch all exceptions
Log.e(TAG, "httpget gtask_url failed"); Log.e(TAG, "httpget gtask_url failed");
return false; return false;
} }
@ -280,10 +301,20 @@ public class GTaskClient {
return true; return true;
} }
/**
* ID
*
* @return ID
*/
private int getActionId() { private int getActionId() {
return mActionId++; return mActionId++;
} }
/**
* HTTP POST
*
* @return HTTP POST
*/
private HttpPost createHttpPost() { private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl); HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
@ -291,14 +322,23 @@ public class GTaskClient {
return httpPost; return httpPost;
} }
/**
* HttpEntity
* @param entity HttpEntity
* @return
* @throws IOException
*/
private String getResponseContent(HttpEntity entity) throws IOException { private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null; String contentEncoding = null;
// 获取响应编码方式
if (entity.getContentEncoding() != null) { if (entity.getContentEncoding() != null) {
contentEncoding = entity.getContentEncoding().getValue(); contentEncoding = entity.getContentEncoding().getValue();
Log.d(TAG, "encoding: " + contentEncoding); Log.d(TAG, "encoding: " + contentEncoding);
} }
InputStream input = entity.getContent(); InputStream input = entity.getContent();
// 根据编码方式设置InputStream
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
input = new GZIPInputStream(entity.getContent()); input = new GZIPInputStream(entity.getContent());
} else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) { } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {
@ -307,6 +347,7 @@ public class GTaskClient {
} }
try { try {
// 将InputStream转为字符流并读取响应内容
InputStreamReader isr = new InputStreamReader(input); InputStreamReader isr = new InputStreamReader(input);
BufferedReader br = new BufferedReader(isr); BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@ -319,10 +360,17 @@ public class GTaskClient {
sb = sb.append(buff); sb = sb.append(buff);
} }
} finally { } finally {
// 关闭InputStream
input.close(); input.close();
} }
} }
/**
* HttpPostJSONObject
* @param js JSONObject
* @return JSONObject
* @throws NetworkFailureException
*/
private JSONObject postRequest(JSONObject js) throws NetworkFailureException { private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first");
@ -331,13 +379,15 @@ public class GTaskClient {
HttpPost httpPost = createHttpPost(); HttpPost httpPost = createHttpPost();
try { try {
// 创建请求参数并设置到HttpPost对象中
LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>(); LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
list.add(new BasicNameValuePair("r", js.toString())); list.add(new BasicNameValuePair("r", js.toString()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entity); httpPost.setEntity(entity);
// execute the post // 执行HttpPost请求
HttpResponse response = mHttpClient.execute(httpPost); HttpResponse response = mHttpClient.execute(httpPost);
// 获取响应内容并将其转为JSONObject对象
String jsString = getResponseContent(response.getEntity()); String jsString = getResponseContent(response.getEntity());
return new JSONObject(jsString); return new JSONObject(jsString);
@ -361,124 +411,150 @@ public class GTaskClient {
} }
public void createTask(Task task) throws NetworkFailureException { public void createTask(Task task) throws NetworkFailureException {
commitUpdate(); commitUpdate(); // 提交更新
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject(); // 创建一个JSON对象
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray(); // 创建一个JSON数组
// action_list // action_list
// 将Task对象的创建操作添加到JSON数组中
actionList.put(task.getCreateAction(getActionId())); actionList.put(task.getCreateAction(getActionId()));
// 将JSON数组添加到JSON对象中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version // client_version
// 将客户端版本添加到JSON对象中
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post // post
// 发送post请求并接收响应
JSONObject jsResponse = postRequest(jsPost); JSONObject jsResponse = postRequest(jsPost);
// 获取响应中的结果数组并获取第一个结果对象
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0); GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
// 将新任务的ID设置为响应中的新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"); // 抛出自定义异常
} }
} }
public void createTaskList(TaskList tasklist) throws NetworkFailureException { public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate(); commitUpdate(); // 提交更新
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject(); // 创建一个JSON对象
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray(); // 创建一个JSON数组
// action_list // action_list
// 将TaskList对象的创建操作添加到JSON数组中
actionList.put(tasklist.getCreateAction(getActionId())); actionList.put(tasklist.getCreateAction(getActionId()));
// 将JSON数组添加到JSON对象中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client version // client version
// 将客户端版本添加到JSON对象中
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post // post
// 发送post请求并接收响应
JSONObject jsResponse = postRequest(jsPost); JSONObject jsResponse = postRequest(jsPost);
// 获取响应中的结果数组并获取第一个结果对象
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0); GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
// 将新任务列表的ID设置为响应中的新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"); // 抛出自定义异常
} }
} }
public void commitUpdate() throws NetworkFailureException { public void commitUpdate() throws NetworkFailureException {
// 如果 mUpdateArray 不为空
if (mUpdateArray != null) { if (mUpdateArray != null) {
try { try {
// 新建一个 JSON 对象
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
// action_list // 将 mUpdateArray 放入 JSON 对象中的 action_list 字段
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
// client_version // 将 mClientVersion 放入 JSON 对象中的 client_version 字段
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送 POST 请求
postRequest(jsPost); postRequest(jsPost);
// 清空 mUpdateArray
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");
} }
} }
} }
public void addUpdateNode(Node node) throws NetworkFailureException { public void addUpdateNode(Node node) throws NetworkFailureException {
// 如果 node 不为空
if (node != null) { if (node != null) {
// too many update items may result in an error // 如果 mUpdateArray 不为空且长度超过 10提交更新
// set max to 10 items
if (mUpdateArray != null && mUpdateArray.length() > 10) { if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate(); commitUpdate();
} }
// 如果 mUpdateArray 为空,新建一个 JSON 数组
if (mUpdateArray == null) if (mUpdateArray == null)
mUpdateArray = new JSONArray(); mUpdateArray = new JSONArray();
// 将 node 对象的更新操作添加到 mUpdateArray 中
mUpdateArray.put(node.getUpdateAction(getActionId())); mUpdateArray.put(node.getUpdateAction(getActionId()));
} }
} }
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(); // 创建一个 JSON 对象
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray(); // 创建一个 JSON 数组,用于存放操作列表
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 // 如果任务在同一个任务列表中移动且不是第一个任务,则添加其前一个任务的 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_DEST_PARENT, curParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); // 设置原任务列表的 ID
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 // 如果任务在不同的任务列表中移动,则添加目标任务列表的 ID
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
} }
actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version actionList.put(action); // 将操作添加到操作列表中
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 将操作列表添加到 JSON 对象中
postRequest(jsPost); // client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); // 添加客户端版本信息
postRequest(jsPost); // 发送请求
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
@ -487,21 +563,22 @@ public class GTaskClient {
} }
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(); // 创建一个 JSON 对象
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray(); // 创建一个 JSON 数组,用于存放操作列表
// 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); // 将操作列表添加到 JSON 对象中
// client_version // client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); // 添加客户端版本信息
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();
@ -509,18 +586,21 @@ public class GTaskClient {
} }
} }
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 {
// 发送 HTTP 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 // 从响应中提取 JSON 字符串
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup("; String jsBegin = "_setup(";
String jsEnd = ")}</script>"; String jsEnd = ")}</script>";
@ -530,6 +610,8 @@ public class GTaskClient {
if (begin != -1 && end != -1 && begin < end) { if (begin != -1 && end != -1 && begin < end) {
jsString = resString.substring(begin + jsBegin.length(), end); jsString = resString.substring(begin + jsBegin.length(), end);
} }
// 解析 JSON 字符串,返回任务列表
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) {
@ -548,6 +630,7 @@ public class GTaskClient {
} }
public JSONArray getTaskList(String listGid) throws NetworkFailureException { public JSONArray getTaskList(String listGid) throws NetworkFailureException {
// 提交未提交的更改
commitUpdate(); commitUpdate();
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
@ -566,6 +649,7 @@ public class GTaskClient {
// client_version // client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送 POST 请求,获取指定任务列表的任务
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) {
@ -576,10 +660,12 @@ public class GTaskClient {
} }
public Account getSyncAccount() { public Account getSyncAccount() {
// 获取同步账户
return mAccount; return mAccount;
} }
public void resetUpdateArray() { public void resetUpdateArray() {
// 重置未提交的更改
mUpdateArray = null; mUpdateArray = null;
} }
}

@ -87,35 +87,46 @@ public class GTaskManager {
private HashMap<Long, String> mNidToGid; private HashMap<Long, String> mNidToGid;
// 定义了一个名为 GTaskManager 的私有类
private GTaskManager() { private GTaskManager() {
mSyncing = false; // 初始化一些变量
mCancelled = false; mSyncing = false; // 当前不在同步状态
mGTaskListHashMap = new HashMap<String, TaskList>(); mCancelled = false; // 当前没有取消
mGTaskHashMap = new HashMap<String, Node>(); mGTaskListHashMap = new HashMap<String, TaskList>(); // 存储多个任务列表的 HashMap
mMetaHashMap = new HashMap<String, MetaData>(); mGTaskHashMap = new HashMap<String, Node>(); // 存储任务的 HashMap
mMetaList = null; mMetaHashMap = new HashMap<String, MetaData>(); // 存储元数据的 HashMap
mLocalDeleteIdMap = new HashSet<Long>(); mMetaList = null; // 初始化元数据列表为空
mGidToNid = new HashMap<String, Long>(); mLocalDeleteIdMap = new HashSet<Long>(); // 存储本地删除的任务的 ID 集合
mNidToGid = new HashMap<Long, String>(); mGidToNid = new HashMap<String, Long>(); // 存储 GTask ID 到 Node ID 的映射
mNidToGid = new HashMap<Long, String>(); // 存储 Node ID 到 GTask ID 的映射
} }
// 定义了一个名为 getInstance 的静态方法,返回一个 GTaskManager 对象
public static synchronized GTaskManager getInstance() { public static synchronized GTaskManager getInstance() {
// 如果当前 GTaskManager 对象为空,就创建一个新的 GTaskManager 对象
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskManager(); mInstance = new GTaskManager();
} }
// 返回 GTaskManager 对象
return mInstance; return mInstance;
} }
// 定义了一个名为 setActivityContext 的方法,用于设置 Activity 的上下文
public synchronized void setActivityContext(Activity activity) { public synchronized void setActivityContext(Activity activity) {
// used for getting authtoken // 用于获取授权令牌authtoken的 Activity 上下文
mActivity = activity; mActivity = activity;
} }
// 定义了一个名为 sync 的方法,用于同步 Google 任务列表
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;
@ -128,21 +139,23 @@ public class GTaskManager {
mNidToGid.clear(); mNidToGid.clear();
try { try {
// 获取 GTaskClient 的单例对象
GTaskClient client = GTaskClient.getInstance(); GTaskClient client = GTaskClient.getInstance();
// 重置更新数组
client.resetUpdateArray(); client.resetUpdateArray();
// login google task // 登录 Google 任务列表
if (!mCancelled) { if (!mCancelled) {
if (!client.login(mActivity)) { if (!client.login(mActivity)) {
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) {
@ -156,6 +169,7 @@ public class GTaskManager {
e.printStackTrace(); e.printStackTrace();
return STATE_INTERNAL_ERROR; return STATE_INTERNAL_ERROR;
} finally { } finally {
// 清空相关变量
mGTaskListHashMap.clear(); mGTaskListHashMap.clear();
mGTaskHashMap.clear(); mGTaskHashMap.clear();
mMetaHashMap.clear(); mMetaHashMap.clear();
@ -165,36 +179,45 @@ public class GTaskManager {
mSyncing = false; mSyncing = false;
} }
// 如果已取消,则返回“同步已取消”状态;否则返回“成功”状态
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
} }
// 初始化 GTask 列表
private void initGTaskList() throws NetworkFailureException { private void initGTaskList() throws NetworkFailureException {
// 检查是否已取消
if (mCancelled) if (mCancelled)
return; return;
// 获取 GTask 客户端
GTaskClient client = GTaskClient.getInstance(); GTaskClient client = GTaskClient.getInstance();
try { try {
// 获取任务列表的 JSON 数据
JSONArray jsTaskLists = client.getTaskLists(); JSONArray jsTaskLists = client.getTaskLists();
// init meta list first // 先初始化元列表
mMetaList = null; mMetaList = null;
for (int i = 0; i < jsTaskLists.length(); i++) { for (int i = 0; i < jsTaskLists.length(); i++) {
// 获取 JSON 数据中的任务列表对象
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);
// 如果任务列表名称为“MIUI_FOLDER_PREFFIX + FOLDER_META”则表示为元列表
if (name if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { // 初始化元列表
mMetaList = new TaskList(); mMetaList = new TaskList();
mMetaList.setContentByRemoteJSON(object); mMetaList.setContentByRemoteJSON(object);
// load meta data // 加载元数据
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);
MetaData metaData = new MetaData(); MetaData metaData = new MetaData();
metaData.setContentByRemoteJSON(object); metaData.setContentByRemoteJSON(object);
// 如果元数据值得保存,将其添加到元列表中
if (metaData.isWorthSaving()) { if (metaData.isWorthSaving()) {
mMetaList.addChildTask(metaData); mMetaList.addChildTask(metaData);
// 将元数据关联的 GID 和元数据存储在哈希映射表中
if (metaData.getGid() != null) { if (metaData.getGid() != null) {
mMetaHashMap.put(metaData.getRelatedGid(), metaData); mMetaHashMap.put(metaData.getRelatedGid(), metaData);
} }
@ -203,7 +226,7 @@ public class GTaskManager {
} }
} }
// create meta list if not existed // 如果元列表不存在,则创建元列表
if (mMetaList == null) { if (mMetaList == null) {
mMetaList = new TaskList(); mMetaList = new TaskList();
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
@ -211,31 +234,34 @@ public class GTaskManager {
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++) {
// 获取 JSON 数据中的任务列表对象
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);
// 如果任务列表名称以“MIUI_FOLDER_PREFFIX”开头且不是元列表则为任务列表
if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
&& !name.equals(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);
gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
Task task = new Task(); Task task = new Task();
task.setContentByRemoteJSON(object); task.setContentByRemoteJSON(object);
// 如果任务值得保存,将其添加
if (task.isWorthSaving()) { if (task.isWorthSaving()) {
task.setMetaInfo(mMetaHashMap.get(gid)); task.setMetaInfo(mMetaHashMap.get(gid));// 设置任务元信息
tasklist.addChildTask(task); tasklist.addChildTask(task);// 将任务添加到任务列表的子任务中
mGTaskHashMap.put(gid, task); mGTaskHashMap.put(gid, task); // 在哈希表中添加任务的ID和任务对象
} }
} }
} }
@ -246,7 +272,7 @@ public class GTaskManager {
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;
@ -254,13 +280,13 @@ public class GTaskManager {
Node node; Node node;
mLocalDeleteIdMap.clear(); mLocalDeleteIdMap.clear();
if (mCancelled) {// 如果已取消,直接返回
if (mCancelled) {
return; return;
} }
// for local deleted note // 处理本地已删除笔记
try { try {
// 查询非系统类型且父级 ID 不是回收站的笔记
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)
@ -286,11 +312,12 @@ public class GTaskManager {
} }
} }
// sync folder first // 先同步文件夹
syncFolder(); syncFolder();
// for note existing in database // 处理已存在于数据库中的笔记
try { try {
// 查询类型为笔记且父级 ID 不是回收站的笔记,按类型倒序排序
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_NOTE), String.valueOf(Notes.ID_TRASH_FOLER) String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER)
@ -303,13 +330,13 @@ 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;
} }
} }
@ -326,24 +353,23 @@ 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();// 获取键值对中的value并将其赋值给node
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);// 将node添加到本地同步
} }
// mCancelled can be set by another thread, so we neet to check one by // mCancelled 可能会被另一个线程设置,因此我们需要逐个检查
// 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();
@ -352,60 +378,61 @@ public class GTaskManager {
} }
private void syncFolder() throws NetworkFailureException { private void syncFolder() throws NetworkFailureException {
Cursor c = null; Cursor c = null;// 游标对象,用于访问数据
String gid; String gid;// GTask任务列表的ID
Node node; Node node;// GTask任务列表对应的本地节点
int syncType; int syncType;// 本地与远程数据同步的类型
if (mCancelled) { if (mCancelled) {// 如果同步已被取消,则直接返回
return; return;
} }
// for root folder // 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);
if (c != null) { if (c != null) {
c.moveToNext(); c.moveToNext();// 将游标移动到下一个记录
gid = c.getString(SqlNote.GTASK_ID_COLUMN); gid = c.getString(SqlNote.GTASK_ID_COLUMN);// 获取GTask任务列表ID
node = mGTaskHashMap.get(gid); node = mGTaskHashMap.get(gid);// 从GTask任务列表映射中获取对应本地节点
if (node != null) { if (node != null) {
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);// 从映射中移除该节点
mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER); mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER);// 将GTask ID映射到本地ID
mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid); mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid);// 将本地ID映射到GTask ID
// 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 {
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);// 将本地数据同步到远程
} }
} else { } else {
Log.w(TAG, "failed to query root folder"); Log.w(TAG, "failed to query root folder");// 记录警告信息
} }
} finally { } finally {
if (c != null) { if (c != null) {
c.close(); c.close();// 关闭游标
c = null; c = null;// 将游标对象设置为null
} }
} }
// for call-note folder // 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);// 获取GTask任务列表ID
node = mGTaskHashMap.get(gid); node = mGTaskHashMap.get(gid);// 从GTask任务列表映射中获取对应本地节点
if (node != null) { if (node != null) {
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);// 从映射中移除该节点
mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER); mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);// 将GTask ID映射到本地ID
mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid); mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid);// 将本地ID映射到GTask ID
// 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))
@ -424,7 +451,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[] {
@ -441,10 +468,10 @@ public class GTaskManager {
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,7 +487,7 @@ 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();
while (iter.hasNext()) { while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next(); Map.Entry<String, TaskList> entry = iter.next();
@ -477,193 +504,252 @@ public class GTaskManager {
} }
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;
} }
// 元数据对象
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 删除节点
GTaskClient.getInstance().deleteNode(meta); GTaskClient.getInstance().deleteNode(meta);
} }
// 将节点 ID 添加到本地删除 ID 映射表中
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 删除节点
GTaskClient.getInstance().deleteNode(meta); GTaskClient.getInstance().deleteNode(meta);
} }
// 使用 GTaskClient 删除节点
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("unkown sync action type");
} }
} }
private void addLocalNode(Node node) throws NetworkFailureException { private void addLocalNode(Node node) throws NetworkFailureException {
// 如果取消了操作,直接返回
if (mCancelled) { if (mCancelled) {
return; return;
} }
// 声明一个 SqlNote 对象
SqlNote sqlNote; SqlNote sqlNote;
// 如果是 TaskList判断是哪种文件夹
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 对象
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 对象
sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER); sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER);
} else { }
// 如果是其他类型的文件夹
else {
// 新建一个普通的 SqlNote 对象,并设置其内容和父文件夹 ID
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 { }
// 如果是 Task
else {
// 新建一个普通的 SqlNote 对象
sqlNote = new SqlNote(mContext); sqlNote = new SqlNote(mContext);
// 从 Task 中获取其内容的 JSON 对象
JSONObject js = node.getLocalJSONFromContent(); JSONObject js = node.getLocalJSONFromContent();
try { try {
// 如果 JSON 对象中包含元数据头部信息
if (js.has(GTaskStringUtils.META_HEAD_NOTE)) { if (js.has(GTaskStringUtils.META_HEAD_NOTE)) {
// 获取元数据头部信息中的 Note 对象
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
// 如果 Note 对象中包含 ID
if (note.has(NoteColumns.ID)) { if (note.has(NoteColumns.ID)) {
// 获取 Note 的 ID
long id = note.getLong(NoteColumns.ID); long id = note.getLong(NoteColumns.ID);
// 如果该 ID 在 Note 数据库中已经存在
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);
} }
} }
} }
// 如果 JSON 对象中包含元数据数据部分
if (js.has(GTaskStringUtils.META_HEAD_DATA)) { if (js.has(GTaskStringUtils.META_HEAD_DATA)) {
// 获取元数据数据部分的 JSON 数组
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
// 遍历该 JSON 数组
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {
// 获取数组中的 JSON 对象
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i);
// 如果该 JSON 对象中包含 ID
if (data.has(DataColumns.ID)) { if (data.has(DataColumns.ID)) {
// 获取该数据的 ID
long dataId = data.getLong(DataColumns.ID); long dataId = data.getLong(DataColumns.ID);
// 如果该 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) {// 捕获 JSON 解析异常
Log.w(TAG, e.toString()); Log.w(TAG, e.toString());// 记录警告日志
e.printStackTrace(); e.printStackTrace();// 打印异常堆栈信息
} }
sqlNote.setContent(js); sqlNote.setContent(js);// 设置 SQLNote 的内容为解析出的 js
Long parentId = mGidToNid.get(((Task) node).getParent().getGid()); Long parentId = mGidToNid.get(((Task) node).getParent().getGid());// 获取 Task 节点的父节点的 GID 对应的 NID
// 如果获取到的 NID 为空
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 add local node"); throw new ActionFailureException("cannot add local node");// 抛出 ActionFailureException 异常
} }
sqlNote.setParentId(parentId.longValue()); sqlNote.setParentId(parentId.longValue());// 将 SQLNote 的父节点 ID 设置为获取到的 NID
} }
// create the local node // 创建本地节点
sqlNote.setGtaskId(node.getGid()); sqlNote.setGtaskId(node.getGid());// 设置 SQLNote 的 GTask ID 为节点的 GID
sqlNote.commit(false); sqlNote.commit(false);// 将 SQLNote 提交到本地数据库,不需要立即同步到远程服务器
// update gid-nid mapping // 更新 GID-NID 映射
mGidToNid.put(node.getGid(), sqlNote.getId()); mGidToNid.put(node.getGid(), sqlNote.getId());// 将节点的 GID 映射为 SQLNote 的 ID
mNidToGid.put(sqlNote.getId(), node.getGid()); mNidToGid.put(sqlNote.getId(), node.getGid());// 将 SQLNote 的 ID 映射为节点的 GID
// update meta // 更新元数据
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);// 同步 SQLNote 的元数据到远程服务器
} }
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 对象中
sqlNote = new SqlNote(mContext, c); sqlNote = new SqlNote(mContext, c);
// 将节点内容转换为 JSON 格式并保存到 SqlNote 对象中
sqlNote.setContent(node.getLocalJSONFromContent()); sqlNote.setContent(node.getLocalJSONFromContent());
// 如果节点是任务类型,则将其父节点的 ID 设置为对应的本地 ID
// 否则将其父节点的 ID 设置为根文件夹的 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);
// 如果 parentId 为 null则说明无法在本地找到该任务的父节点 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 对象的 parentId 属性
sqlNote.setParentId(parentId.longValue()); sqlNote.setParentId(parentId.longValue());
// 将 sqlNote 对象的属性保存到数据库中
sqlNote.commit(true); sqlNote.commit(true);
// update meta info // 更新远程节点的元信息
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
} }
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException { private void addRemoteNode(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);
Node n; Node n;
// update remotely // 如果SqlNote是任务类型进行以下操作
if (sqlNote.isNoteType()) { if (sqlNote.isNoteType()) {
// 创建一个Task对象并用SqlNote的内容更新它
Task task = new Task(); Task task = new Task();
task.setContentByLocalJSON(sqlNote.getContent()); task.setContentByLocalJSON(sqlNote.getContent());
// 获取Task对象的父任务列表的gid
String parentGid = mNidToGid.get(sqlNote.getParentId()); String parentGid = mNidToGid.get(sqlNote.getParentId());
// 如果无法找到父任务列表的gid抛出ActionFailureException异常
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);
// 通过GTaskClient实例创建Task任务
GTaskClient.getInstance().createTask(task); GTaskClient.getInstance().createTask(task);
n = (Node) task; n = (Node) task;
// add meta // 添加元数据
updateRemoteMeta(task.getGid(), sqlNote); updateRemoteMeta(task.getGid(), sqlNote);
} else { } else {
TaskList tasklist = null; TaskList tasklist = null;
// 如果SqlNote是文件夹类型进行以下操作
// 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)
folderName += GTaskStringUtils.FOLDER_DEFAULT; folderName += GTaskStringUtils.FOLDER_DEFAULT;
// 如果是通话记录文件夹,设置文件夹名为通话记录文件夹
else if (sqlNote.getId() == Notes.ID_CALL_RECORD_FOLDER) else if (sqlNote.getId() == Notes.ID_CALL_RECORD_FOLDER)
folderName += GTaskStringUtils.FOLDER_CALL_NOTE; folderName += GTaskStringUtils.FOLDER_CALL_NOTE;
// 否则将文件夹名设置为SqlNote对象的片段内容
else else
folderName += sqlNote.getSnippet(); folderName += sqlNote.getSnippet();
// 遍历mGTaskListHashMap查找是否存在与SqlNote对象匹配的TaskList对象
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();
String gid = entry.getKey(); String gid = entry.getKey();
TaskList list = entry.getValue(); TaskList list = entry.getValue();
// 如果存在匹配的TaskList对象则将tasklist设置为该对象
if (list.getName().equals(folderName)) { if (list.getName().equals(folderName)) {
tasklist = list; tasklist = list;
// 如果mGTaskHashMap包含gid将其从中移除
if (mGTaskHashMap.containsKey(gid)) { if (mGTaskHashMap.containsKey(gid)) {
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);
} }
@ -671,7 +757,7 @@ public class GTaskManager {
} }
} }
// no match we can add now // 如果未找到匹配的TaskList对象新建一个TaskList对象
if (tasklist == null) { if (tasklist == null) {
tasklist = new TaskList(); tasklist = new TaskList();
tasklist.setContentByLocalJSON(sqlNote.getContent()); tasklist.setContentByLocalJSON(sqlNote.getContent());
@ -681,108 +767,149 @@ public class GTaskManager {
n = (Node) tasklist; n = (Node) tasklist;
} }
// update local note // 更新SqlNote对象的GTaskId并将其提交到本地数据库
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-id mapping // gid-id 映射表
mGidToNid.put(n.getGid(), sqlNote.getId()); mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid()); mNidToGid.put(sqlNote.getId(), n.getGid());
} }
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException { private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return; // 如果任务已取消,则退出此方法
} }
SqlNote sqlNote = new SqlNote(mContext, c); SqlNote sqlNote = new SqlNote(mContext, c); // 创建 SqlNote 实例
// update remotely // 更新远程服务器的节点内容
node.setContentByLocalJSON(sqlNote.getContent()); node.setContentByLocalJSON(sqlNote.getContent());
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(); // 获取任务当前的父任务列表
// 查找新的父任务列表的 GID
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"); // 找不到新父任务列表,记录错误并抛出异常
throw new ActionFailureException("cannot update remote task"); throw new ActionFailureException("cannot update remote task");
} }
TaskList curParentList = mGTaskListHashMap.get(curParentGid); TaskList curParentList = mGTaskListHashMap.get(curParentGid); // 获取新父任务列表的 TaskList 实例
// 如果新旧父任务列表不同,则移动任务到新的父任务列表
if (preParentList != curParentList) { if (preParentList != curParentList) {
preParentList.removeChildTask(task); preParentList.removeChildTask(task); // 从旧父任务列表中移除该任务
curParentList.addChildTask(task); curParentList.addChildTask(task); // 添加该任务到新的父任务列表中
GTaskClient.getInstance().moveTask(task, preParentList, curParentList); GTaskClient.getInstance().moveTask(task, preParentList, curParentList); // 移动任务到新父任务列表
} }
} }
// clear local modified flag sqlNote.resetLocalModified(); // 重置本地修改标记
sqlNote.resetLocalModified(); sqlNote.commit(true); // 将 SqlNote 中的修改提交到本地 SQLite 数据库中
sqlNote.commit(true);
} }
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException { private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
// 如果 sqlNote 不为空且为笔记类型,则执行以下代码
if (sqlNote != null && sqlNote.isNoteType()) { if (sqlNote != null && sqlNote.isNoteType()) {
// 获取 gid 对应的 metaData
MetaData metaData = mMetaHashMap.get(gid); MetaData metaData = mMetaHashMap.get(gid);
if (metaData != null) { if (metaData != null) {
// 设置 gid 对应的 metaData 的内容为 sqlNote 的内容
metaData.setMeta(gid, sqlNote.getContent()); metaData.setMeta(gid, sqlNote.getContent());
// 将 metaData 添加到更新队列中
GTaskClient.getInstance().addUpdateNode(metaData); GTaskClient.getInstance().addUpdateNode(metaData);
} else { } else {
// 如果 metaData 为空,则创建新的 metaData并设置其内容为 sqlNote 的内容
metaData = new MetaData(); metaData = new MetaData();
metaData.setMeta(gid, sqlNote.getContent()); metaData.setMeta(gid, sqlNote.getContent());
// 将 metaData 添加到 mMetaList 的子任务列表中
mMetaList.addChildTask(metaData); mMetaList.addChildTask(metaData);
// 将 metaData 添加到 mMetaHashMap 中
mMetaHashMap.put(gid, metaData); mMetaHashMap.put(gid, metaData);
// 创建任务并将其添加到 GTaskClient 的任务列表中
GTaskClient.getInstance().createTask(metaData); GTaskClient.getInstance().createTask(metaData);
} }
} }
} }
// 声明一个方法,用于更新本地同步 ID如果网络故障则抛出 NetworkFailureException 异常
private void refreshLocalSyncId() throws NetworkFailureException { private void refreshLocalSyncId() throws NetworkFailureException {
// 如果已取消,则直接返回
if (mCancelled) { if (mCancelled) {
return; return;
} }
// get the latest gtask list // 清空哈希表
mGTaskHashMap.clear(); mGTaskHashMap.clear();
mGTaskListHashMap.clear(); mGTaskListHashMap.clear();
mMetaHashMap.clear(); mMetaHashMap.clear();
// 初始化 GTask 列表
initGTaskList(); initGTaskList();
// 声明一个游标,用于查询本地便签
Cursor c = null; Cursor c = null;
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, // 查询不属于系统类型和垃圾桶类型的所有便签
"(type<>? AND parent_id<>?)", new String[] { c = mContentResolver.query(
String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) Notes.CONTENT_NOTE_URI,
}, NoteColumns.TYPE + " DESC"); 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) { if (c != null) {
// 遍历查询结果
while (c.moveToNext()) { while (c.moveToNext()) {
// 获取当前便签的 GTask ID
String gid = c.getString(SqlNote.GTASK_ID_COLUMN); String gid = c.getString(SqlNote.GTASK_ID_COLUMN);
// 根据 GTask ID 从 GTask 哈希表中获取节点信息
Node node = mGTaskHashMap.get(gid); Node node = mGTaskHashMap.get(gid);
// 如果节点信息不为空
if (node != null) { if (node != null) {
// 从 GTask 哈希表中移除当前 GTask ID 对应的节点
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);
// 创建一个 ContentValues 对象,用于更新本地便签的同步 ID
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.SYNC_ID, node.getLastModified()); values.put(NoteColumns.SYNC_ID, node.getLastModified());
mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, // 更新本地便签的同步 ID
c.getLong(SqlNote.ID_COLUMN)), values, null, null); mContentResolver.update(
ContentUris.withAppendedId(
Notes.CONTENT_NOTE_URI,
c.getLong(SqlNote.ID_COLUMN)
),
values,
null,
null
);
} else { } else {
// 如果节点信息为空,打印日志并抛出 ActionFailureException 异常
Log.e(TAG, "something is missed"); Log.e(TAG, "something is missed");
throw new ActionFailureException( throw new ActionFailureException(
"some local items don't have gid after sync"); "some local items don't have gid after sync"
);
} }
} }
} else { } else {
// 如果查询结果为空,打印警告日志
Log.w(TAG, "failed to query local note to refresh sync id"); Log.w(TAG, "failed to query local note to refresh sync id");
} }
} finally { } finally {
// 关闭游标
if (c != null) { if (c != null) {
c.close(); c.close();
c = null; c = null;
@ -790,6 +917,7 @@ public class GTaskManager {
} }
} }
public String getSyncAccount() { public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name; return GTaskClient.getInstance().getSyncAccount().name;
} }
@ -798,3 +926,4 @@ public class GTaskManager {
mCancelled = true; mCancelled = true;
} }
} }
Loading…
Cancel
Save