Compare commits

..

1 Commits
master ... main

@ -16,23 +16,18 @@
package net.micode.notes.gtask.exception;
// ActionFailureException类用于表示任务操作失败的异常情况
public class ActionFailureException extends RuntimeException {
// 序列化ID用于标识类的版本
private static final long serialVersionUID = 4425249765923293627L;
// 构造方法,无参数
public ActionFailureException() {
super();
}
// 构造方法,带错误消息参数
public ActionFailureException(String paramString) {
super(paramString);
}
// 构造方法,带错误消息和异常原因参数
public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}
}
}

@ -16,23 +16,18 @@
package net.micode.notes.gtask.exception;
// NetworkFailureException类用于表示网络操作失败的异常情况
public class NetworkFailureException extends Exception {
// 序列化ID用于标识类的版本
private static final long serialVersionUID = 2107610287180234136L;
// 构造方法,无参数
public NetworkFailureException() {
super();
}
// 构造方法,带错误消息参数
public NetworkFailureException(String paramString) {
super(paramString);
}
// 构造方法,带错误消息和异常原因参数
public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}
}
}

@ -1,3 +1,4 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
@ -27,29 +28,23 @@ 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> {
// 通知ID用于同步任务的通知
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
// 定义任务完成后的回调接口
public interface OnCompleteListener {
void onComplete();
}
// 上下文环境,用于访问应用程序资源
private Context mContext;
// 通知管理器,用于显示同步通知
private NotificationManager mNotifiManager;
// GTask管理器用于处理任务同步
private GTaskManager mTaskManager;
// 任务完成后的回调监听器
private OnCompleteListener mOnCompleteListener;
// 构造方法,初始化任务所需的资源
public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context;
mOnCompleteListener = listener;
@ -58,19 +53,35 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
mTaskManager = GTaskManager.getInstance();
}
// 取消同步操作
public void cancelSync() {
mTaskManager.cancelSync();
}
// 发布进度信息
public void publishProgess(String message) {
publishProgress(new String[] {
message
message
});
}
// 显示通知
// private void showNotification(int tickerId, String content) {
// Notification notification = new Notification(R.drawable.notification, mContext
// .getString(tickerId), System.currentTimeMillis());
// notification.defaults = Notification.DEFAULT_LIGHTS;
// notification.flags = Notification.FLAG_AUTO_CANCEL;
// PendingIntent pendingIntent;
// if (tickerId != R.string.ticker_success) {
// pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
// NotesPreferenceActivity.class), 0);
//
// } else {
// pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
// NotesListActivity.class), 0);
// }
// notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
// pendingIntent);
// mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
// }
private void showNotification(int tickerId, String content) {
PendingIntent pendingIntent;
if (tickerId != R.string.ticker_success) {
@ -87,11 +98,10 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
.setContentIntent(pendingIntent)
.setWhen(System.currentTimeMillis())
.setOngoing(true);
Notification notification = builder.getNotification();
Notification notification=builder.getNotification();
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
}
// 后台执行任务
@Override
protected Integer doInBackground(Void... unused) {
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
@ -99,7 +109,6 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
return mTaskManager.sync(mContext, this);
}
// 更新进度
@Override
protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]);
@ -108,7 +117,6 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
}
}
// 任务完成后执行的操作
@Override
protected void onPostExecute(Integer result) {
if (result == GTaskManager.STATE_SUCCESS) {
@ -132,4 +140,4 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
}).start();
}
}
}
}

@ -44,6 +44,7 @@ import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.json.JSONArray;
import org.json.JSONException;
@ -59,50 +60,36 @@ import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
public class GTaskClient {
// 日志标签,用于调试和日志记录
private static final String TAG = GTaskClient.class.getSimpleName();
// Google Tasks 的基础URL
private static final String GTASK_URL = "https://mail.google.com/tasks/";
// Google Tasks 获取数据的URL
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
// Google Tasks 提交数据的URL
private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
// 单例实例
private static GTaskClient mInstance = null;
// HTTP客户端用于网络请求
private DefaultHttpClient mHttpClient;
// 获取数据的URL
private String mGetUrl;
// 提交数据的URL
private String mPostUrl;
// 客户端版本号
private long mClientVersion;
// 登录状态
private boolean mLoggedin;
// 最后登录时间
private long mLastLoginTime;
// 操作ID
private int mActionId;
// 当前账户
private Account mAccount;
// 更新数组
private JSONArray mUpdateArray;
// 私有构造方法,用于单例模式
private GTaskClient() {
mHttpClient = null;
mGetUrl = GTASK_GET_URL;
@ -115,7 +102,6 @@ public class GTaskClient {
mUpdateArray = null;
}
// 获取单例实例
public static synchronized GTaskClient getInstance() {
if (mInstance == null) {
mInstance = new GTaskClient();
@ -123,18 +109,18 @@ public class GTaskClient {
return mInstance;
}
// 登录Google账户
public boolean login(Activity activity) {
// 检查是否需要重新登录
// we suppose that the cookie would expire after 5 minutes
// then we need to re-login
final long interval = 1000 * 60 * 5;
if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false;
}
// 检查账户是否切换
// need to re-login after account switch
if (mLoggedin
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) {
.getSyncAccountName(activity))) {
mLoggedin = false;
}
@ -150,7 +136,7 @@ public class GTaskClient {
return false;
}
// 登录自定义域名
// login with custom domain if necessary
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
.endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
@ -165,7 +151,7 @@ public class GTaskClient {
}
}
// 登录官方URL
// try to login with google official url
if (!mLoggedin) {
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
@ -178,7 +164,6 @@ public class GTaskClient {
return true;
}
// 登录Google账户并获取认证令牌
private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken;
AccountManager accountManager = AccountManager.get(activity);
@ -204,6 +189,7 @@ public class GTaskClient {
return null;
}
// get the token now
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null);
try {
@ -221,10 +207,10 @@ public class GTaskClient {
return authToken;
}
// 尝试登录Google Tasks
private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) {
// 如果认证令牌过期,重新获取并再次尝试登录
// maybe the auth token is out of date, now let's invalidate the
// token and try again
authToken = loginGoogleAccount(activity, true);
if (authToken == null) {
Log.e(TAG, "login google account failed");
@ -239,7 +225,6 @@ public class GTaskClient {
return true;
}
// 登录Google Tasks
private boolean loginGtask(String authToken) {
int timeoutConnection = 10000;
int timeoutSocket = 15000;
@ -251,13 +236,14 @@ public class GTaskClient {
mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// login gtask
try {
String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl);
HttpResponse response = null;
response = mHttpClient.execute(httpGet);
// 获取登录后的Cookie
// get the cookie now
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false;
for (Cookie cookie : cookies) {
@ -269,7 +255,7 @@ public class GTaskClient {
Log.w(TAG, "it seems that there is no auth cookie");
}
// 获取客户端版本号
// get the client version
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
@ -286,6 +272,7 @@ public class GTaskClient {
e.printStackTrace();
return false;
} catch (Exception e) {
// simply catch all exceptions
Log.e(TAG, "httpget gtask_url failed");
return false;
}
@ -293,12 +280,10 @@ public class GTaskClient {
return true;
}
// 获取操作ID
private int getActionId() {
return mActionId++;
}
// 创建HTTP POST请求
private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
@ -306,7 +291,6 @@ public class GTaskClient {
return httpPost;
}
// 获取HTTP响应内容
private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null;
if (entity.getContentEncoding() != null) {
@ -339,7 +323,6 @@ public class GTaskClient {
}
}
// 发送POST请求
private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
@ -353,6 +336,7 @@ public class GTaskClient {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entity);
// execute the post
HttpResponse response = mHttpClient.execute(httpPost);
String jsString = getResponseContent(response.getEntity());
return new JSONObject(jsString);
@ -376,18 +360,20 @@ public class GTaskClient {
}
}
// 创建任务
public void createTask(Task task) throws NetworkFailureException {
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// action_list
actionList.put(task.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post
JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
@ -400,18 +386,20 @@ public class GTaskClient {
}
}
// 创建任务列表
public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// action_list
actionList.put(tasklist.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post
JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
@ -424,14 +412,15 @@ public class GTaskClient {
}
}
// 提交更新
public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) {
try {
JSONObject jsPost = new JSONObject();
// action_list
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost);
@ -444,9 +433,10 @@ public class GTaskClient {
}
}
// 添加更新节点
public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) {
// too many update items may result in an error
// set max to 10 items
if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate();
}
@ -457,7 +447,6 @@ public class GTaskClient {
}
}
// 移动任务
public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException {
commitUpdate();
@ -466,21 +455,26 @@ public class GTaskClient {
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
// action_list
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid());
if (preParent == curParent && task.getPriorSibling() != null) {
// put prioring_sibing_id only if moving within the tasklist and
// it is not the first one
action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
}
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid());
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid());
if (preParent != curParent) {
// put the dest_list only if moving between tasklists
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
}
actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost);
@ -492,17 +486,18 @@ public class GTaskClient {
}
}
// 删除节点
public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// action_list
node.setDeleted(true);
actionList.put(node.getUpdateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost);
@ -514,7 +509,6 @@ public class GTaskClient {
}
}
// 获取任务列表
public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
@ -526,6 +520,7 @@ public class GTaskClient {
HttpResponse response = null;
response = mHttpClient.execute(httpGet);
// get the task list
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
@ -552,7 +547,6 @@ public class GTaskClient {
}
}
// 获取任务列表中的任务
public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate();
try {
@ -560,6 +554,7 @@ public class GTaskClient {
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
// action_list
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
@ -568,6 +563,7 @@ public class GTaskClient {
actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
JSONObject jsResponse = postRequest(jsPost);
@ -579,13 +575,11 @@ public class GTaskClient {
}
}
// 获取同步账户
public Account getSyncAccount() {
return mAccount;
}
// 重置更新数组
public void resetUpdateArray() {
mUpdateArray = null;
}
}
}

@ -47,57 +47,46 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
public class GTaskManager {
// 日志标签,用于调试和日志记录
private static final String TAG = GTaskManager.class.getSimpleName();
// 同步状态常量
public static final int STATE_SUCCESS = 0;
public static final int STATE_NETWORK_ERROR = 1;
public static final int STATE_INTERNAL_ERROR = 2;
public static final int STATE_SYNC_IN_PROGRESS = 3;
public static final int STATE_SYNC_CANCELLED = 4;
// 单例实例
private static GTaskManager mInstance = null;
// 当前活动的Activity
private Activity mActivity;
// 上下文环境
private Context mContext;
// 内容解析器
private ContentResolver mContentResolver;
// 同步状态
private boolean mSyncing;
// 是否取消同步
private boolean mCancelled;
// GTask列表映射
private HashMap<String, TaskList> mGTaskListHashMap;
// GTask映射
private HashMap<String, Node> mGTaskHashMap;
// 元数据映射
private HashMap<String, MetaData> mMetaHashMap;
// 元数据列表
private TaskList mMetaList;
// 本地删除ID集合
private HashSet<Long> mLocalDeleteIdMap;
// GID到NID的映射
private HashMap<String, Long> mGidToNid;
// NID到GID的映射
private HashMap<Long, String> mNidToGid;
// 私有构造方法,用于单例模式
private GTaskManager() {
mSyncing = false;
mCancelled = false;
@ -110,7 +99,6 @@ public class GTaskManager {
mNidToGid = new HashMap<Long, String>();
}
// 获取单例实例
public static synchronized GTaskManager getInstance() {
if (mInstance == null) {
mInstance = new GTaskManager();
@ -118,12 +106,11 @@ public class GTaskManager {
return mInstance;
}
// 设置活动的Activity
public synchronized void setActivityContext(Activity activity) {
// used for getting authtoken
mActivity = activity;
}
// 执行同步操作
public int sync(Context context, GTaskASyncTask asyncTask) {
if (mSyncing) {
Log.d(TAG, "Sync is in progress");
@ -144,18 +131,18 @@ public class GTaskManager {
GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray();
// 登录Google Tasks
// login google task
if (!mCancelled) {
if (!client.login(mActivity)) {
throw new NetworkFailureException("login google task failed");
}
}
// 初始化GTask列表
// get the task list from google
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
initGTaskList();
// 执行内容同步
// do content sync work
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
syncContent();
} catch (NetworkFailureException e) {
@ -181,7 +168,6 @@ public class GTaskManager {
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
}
// 初始化GTask列表
private void initGTaskList() throws NetworkFailureException {
if (mCancelled)
return;
@ -189,7 +175,7 @@ public class GTaskManager {
try {
JSONArray jsTaskLists = client.getTaskLists();
// 初始化元数据列表
// init meta list first
mMetaList = null;
for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i);
@ -201,7 +187,7 @@ public class GTaskManager {
mMetaList = new TaskList();
mMetaList.setContentByRemoteJSON(object);
// 加载元数据
// load meta data
JSONArray jsMetas = client.getTaskList(gid);
for (int j = 0; j < jsMetas.length(); j++) {
object = (JSONObject) jsMetas.getJSONObject(j);
@ -217,7 +203,7 @@ public class GTaskManager {
}
}
// 创建元数据列表(如果不存在)
// create meta list if not existed
if (mMetaList == null) {
mMetaList = new TaskList();
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
@ -225,7 +211,7 @@ public class GTaskManager {
GTaskClient.getInstance().createTaskList(mMetaList);
}
// 初始化任务列表
// init task list
for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
@ -233,13 +219,13 @@ public class GTaskManager {
if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
&& !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDERMETA)) {
+ GTaskStringUtils.FOLDER_META)) {
TaskList tasklist = new TaskList();
tasklist.setContentByRemoteJSON(object);
mGTaskListHashMap.put(gid, tasklist);
mGTaskHashMap.put(gid, tasklist);
// 加载任务
// load tasks
JSONArray jsTasks = client.getTaskList(gid);
for (int j = 0; j < jsTasks.length(); j++) {
object = (JSONObject) jsTasks.getJSONObject(j);
@ -261,7 +247,6 @@ public class GTaskManager {
}
}
// 执行内容同步
private void syncContent() throws NetworkFailureException {
int syncType;
Cursor c = null;
@ -274,7 +259,7 @@ public class GTaskManager {
return;
}
// 同步本地删除的便签
// for local deleted note
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id=?)", new String[] {
@ -301,10 +286,10 @@ public class GTaskManager {
}
}
// 同步文件夹
// sync folder first
syncFolder();
// 同步便签
// for note existing in database
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] {
@ -321,8 +306,10 @@ public class GTaskManager {
syncType = node.getSyncAction(c);
} else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
// remote delete
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
@ -339,7 +326,7 @@ public class GTaskManager {
}
}
// 同步剩余项目
// go through remaining items
Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Node> entry = iter.next();
@ -347,21 +334,23 @@ public class GTaskManager {
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
}
// 清除本地删除表
// mCancelled can be set by another thread, so we neet to check one by
// one
// clear local delete table
if (!mCancelled) {
if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {
throw new ActionFailureException("failed to batch-delete local deleted notes");
}
}
// 刷新本地同步ID
// refresh local sync id
if (!mCancelled) {
GTaskClient.getInstance().commitUpdate();
refreshLocalSyncId();
}
}
// 同步文件夹
private void syncFolder() throws NetworkFailureException {
Cursor c = null;
String gid;
@ -372,7 +361,7 @@ public class GTaskManager {
return;
}
// 同步根文件夹
// for root folder
try {
c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
@ -384,6 +373,7 @@ public class GTaskManager {
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER);
mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid);
// for system folder, only update remote name if necessary
if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
@ -400,11 +390,11 @@ public class GTaskManager {
}
}
// 同步通话记录文件夹
// for call-note folder
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)",
new String[] {
String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
}, null);
if (c != null) {
if (c.moveToNext()) {
@ -414,6 +404,8 @@ public class GTaskManager {
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);
mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid);
// for system folder, only update remote name if
// necessary
if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE))
@ -432,7 +424,7 @@ public class GTaskManager {
}
}
// 同步本地现有文件夹
// for local existing folders
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] {
@ -449,8 +441,10 @@ public class GTaskManager {
syncType = node.getSyncAction(c);
} else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
// remote delete
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
@ -466,7 +460,7 @@ public class GTaskManager {
}
}
// 同步远程添加的文件夹
// for remote add folders
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next();
@ -482,7 +476,6 @@ public class GTaskManager {
GTaskClient.getInstance().commitUpdate();
}
// 执行内容同步操作
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -517,17 +510,18 @@ public class GTaskManager {
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_UPDATE_CONFLICT:
// merging both modifications maybe a good idea
// right now just use local update simply
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_NONE:
break;
case Node.SYNC_ACTION_ERROR:
default:
throw new ActionFailureException("unknown sync action type");
throw new ActionFailureException("unkown sync action type");
}
}
// 添加本地节点
private void addLocalNode(Node node) throws NetworkFailureException {
if (mCancelled) {
return;
@ -555,6 +549,7 @@ public class GTaskManager {
if (note.has(NoteColumns.ID)) {
long id = note.getLong(NoteColumns.ID);
if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
// the id is not available, have to create a new one
note.remove(NoteColumns.ID);
}
}
@ -567,6 +562,8 @@ public class GTaskManager {
if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID);
if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
// the data id is not available, have to create
// a new one
data.remove(DataColumns.ID);
}
}
@ -587,22 +584,26 @@ public class GTaskManager {
sqlNote.setParentId(parentId.longValue());
}
// create the local node
sqlNote.setGtaskId(node.getGid());
sqlNote.commit(false);
// update gid-nid mapping
mGidToNid.put(node.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), node.getGid());
// update meta
updateRemoteMeta(node.getGid(), sqlNote);
}
// 更新本地节点
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
}
SqlNote sqlNote = new SqlNote(mContext, c);
SqlNote sqlNote;
// update the note locally
sqlNote = new SqlNote(mContext, c);
sqlNote.setContent(node.getLocalJSONFromContent());
Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid())
@ -614,10 +615,10 @@ public class GTaskManager {
sqlNote.setParentId(parentId.longValue());
sqlNote.commit(true);
// update meta info
updateRemoteMeta(node.getGid(), sqlNote);
}
// 添加远程节点
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -626,6 +627,7 @@ public class GTaskManager {
SqlNote sqlNote = new SqlNote(mContext, c);
Node n;
// update remotely
if (sqlNote.isNoteType()) {
Task task = new Task();
task.setContentByLocalJSON(sqlNote.getContent());
@ -640,10 +642,12 @@ public class GTaskManager {
GTaskClient.getInstance().createTask(task);
n = (Node) task;
// add meta
updateRemoteMeta(task.getGid(), sqlNote);
} else {
TaskList tasklist = null;
// we need to skip folder if it has already existed
String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;
if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)
folderName += GTaskStringUtils.FOLDER_DEFAULT;
@ -667,6 +671,7 @@ public class GTaskManager {
}
}
// no match we can add now
if (tasklist == null) {
tasklist = new TaskList();
tasklist.setContentByLocalJSON(sqlNote.getContent());
@ -676,16 +681,17 @@ public class GTaskManager {
n = (Node) tasklist;
}
// update local note
sqlNote.setGtaskId(n.getGid());
sqlNote.commit(false);
sqlNote.resetLocalModified();
sqlNote.commit(true);
// gid-id mapping
mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid());
}
// 更新远程节点
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -693,11 +699,14 @@ public class GTaskManager {
SqlNote sqlNote = new SqlNote(mContext, c);
// update remotely
node.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(node);
// update meta
updateRemoteMeta(node.getGid(), sqlNote);
// move task if necessary
if (sqlNote.isNoteType()) {
Task task = (Task) node;
TaskList preParentList = task.getParent();
@ -716,11 +725,11 @@ public class GTaskManager {
}
}
// clear local modified flag
sqlNote.resetLocalModified();
sqlNote.commit(true);
}
// 更新远程元数据
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
if (sqlNote != null && sqlNote.isNoteType()) {
MetaData metaData = mMetaHashMap.get(gid);
@ -737,12 +746,12 @@ public class GTaskManager {
}
}
// 刷新本地同步ID
private void refreshLocalSyncId() throws NetworkFailureException {
if (mCancelled) {
return;
}
// get the latest gtask list
mGTaskHashMap.clear();
mGTaskListHashMap.clear();
mMetaHashMap.clear();
@ -781,13 +790,11 @@ public class GTaskManager {
}
}
// 获取同步账户名称
public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name;
}
// 取消同步
public void cancelSync() {
mCancelled = true;
}
}
}

@ -24,28 +24,24 @@ import android.os.Bundle;
import android.os.IBinder;
public class GTaskSyncService extends Service {
// 广播操作类型
public final static String ACTION_STRING_NAME = "sync_action_type";
// 同步操作类型常量
public final static int ACTION_START_SYNC = 0;
public final static int ACTION_CANCEL_SYNC = 1;
public final static int ACTION_INVALID = 2;
// 广播名称
public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
// 广播数据键
public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
// 同步任务实例
private static GTaskASyncTask mSyncTask = null;
// 同步进度信息
private static String mSyncProgress = "";
// 开始同步
private void startSync() {
if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
@ -60,20 +56,17 @@ public class GTaskSyncService extends Service {
}
}
// 取消同步
private void cancelSync() {
if (mSyncTask != null) {
mSyncTask.cancelSync();
}
}
// 服务创建时调用
@Override
public void onCreate() {
mSyncTask = null;
}
// 处理启动命令
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras();
@ -93,7 +86,6 @@ public class GTaskSyncService extends Service {
return super.onStartCommand(intent, flags, startId);
}
// 低内存时调用
@Override
public void onLowMemory() {
if (mSyncTask != null) {
@ -101,12 +93,10 @@ public class GTaskSyncService extends Service {
}
}
// 返回绑定的IBinder对象
public IBinder onBind(Intent intent) {
return null;
}
// 发送广播
public void sendBroadcast(String msg) {
mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
@ -115,7 +105,6 @@ public class GTaskSyncService extends Service {
sendBroadcast(intent);
}
// 静态方法,用于启动同步
public static void startSync(Activity activity) {
GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class);
@ -123,20 +112,17 @@ public class GTaskSyncService extends Service {
activity.startService(intent);
}
// 静态方法,用于取消同步
public static void cancelSync(Context context) {
Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent);
}
// 静态方法,用于检查是否正在同步
public static boolean isSyncing() {
return mSyncTask != null;
}
// 静态方法,用于获取同步进度信息
public static String getProgressString() {
return mSyncProgress;
}
}
}

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 186 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 606 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 194 KiB

@ -18,8 +18,8 @@
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- android:background="@drawable/list_background">-->
android:layout_height="fill_parent"
android:background="@drawable/list_background">
<LinearLayout
android:layout_width="fill_parent"

@ -36,16 +36,4 @@
<item
android:id="@+id/menu_search"
android:title="@string/menu_search"/>
<item
android:id="@+id/menu_graygoo"
android:title="@string/menu_graygoo"/>
<item
android:id="@+id/menu_miku"
android:title="@string/menu_miku"/>
<item
android:id="@+id/menu_hutao"
android:title="@string/menu_hutao"/>
</menu>

@ -39,10 +39,6 @@
<string name="file_path">/MIUI/notes/</string>
<string name="file_name_txt_format">notes_%s.txt</string>
<!-- notes list string -->
<string name="menu_graygoo">Background: graygoo</string>
<string name="menu_miku">Background: miku</string>
<string name="menu_hutao">Background: hutao</string>
<string name="format_folder_files_count">(%d)</string>
<string name="menu_create_folder">New Folder</string>
<string name="menu_export_text">Export text</string>

Loading…
Cancel
Save