main
liuyuxia 7 months ago
parent 6f3dea8052
commit f3aa50205a

@ -16,18 +16,45 @@
package net.micode.notes.gtask.exception; package net.micode.notes.gtask.exception;
/**
* ActionFailureException Google
* RuntimeException
*/
public class ActionFailureException extends RuntimeException { public class ActionFailureException extends RuntimeException {
private static final long serialVersionUID = 4425249765923293627L; private static final long serialVersionUID = 4425249765923293627L;
/**
* ActionFailureException
*/
public ActionFailureException() { public ActionFailureException() {
super(); super();
} }
/**
* ActionFailureException
* @param paramString
*/
public ActionFailureException(String paramString) { public ActionFailureException(String paramString) {
super(paramString); super(paramString);
} }
/**
* ActionFailureException
* @param paramString
* @param paramThrowable
*/
public ActionFailureException(String paramString, Throwable paramThrowable) { public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable); super(paramString, paramThrowable);
} }
} }
/**
*
ActionFailureException Google RuntimeException
serialVersionUID
ActionFailureException() ActionFailureException
ActionFailureException(String paramString) ActionFailureException
ActionFailureException(String paramString, Throwable paramThrowable) ActionFailureException
*/

@ -15,17 +15,46 @@
*/ */
package net.micode.notes.gtask.exception; package net.micode.notes.gtask.exception;
/**
* NetworkFailureException
* Exception
*/
public class NetworkFailureException extends Exception { public class NetworkFailureException extends Exception {
private static final long serialVersionUID = 2107610287180234136L; private static final long serialVersionUID = 2107610287180234136L;
/**
* NetworkFailureException
*/
public NetworkFailureException() { public NetworkFailureException() {
super(); super();
} }
/**
* NetworkFailureException
* @param paramString
*/
public NetworkFailureException(String paramString) { public NetworkFailureException(String paramString) {
super(paramString); super(paramString);
} }
/**
* NetworkFailureException
* @param paramString
* @param paramThrowable
*/
public NetworkFailureException(String paramString, Throwable paramThrowable) { public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable); super(paramString, paramThrowable);
} }
} }
/**
*
NetworkFailureException Exception
serialVersionUID
NetworkFailureException() NetworkFailureException
NetworkFailureException(String paramString) NetworkFailureExceptionparamString
NetworkFailureException(String paramString, Throwable paramThrowable) NetworkFailureExceptionparamString paramThrowable
*/

@ -1,41 +1,27 @@
/* package net.micode.notes.gtask.remote;
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote;
import android.app.Notification; import android.app.Notification;
import android.app.NotificationManager; import android.app.NotificationManager;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.AsyncTask; import android.os.AsyncTask;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity; import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity; import net.micode.notes.ui.NotesPreferenceActivity;
/** /**
* Google * Google
* AsyncTask Google
*/ */
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> { public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; // 同步通知的ID private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; // 同步通知的ID
/** /**
* *
*
*/ */
public interface OnCompleteListener { public interface OnCompleteListener {
void onComplete(); // 当同步完成时调用 void onComplete(); // 当同步完成时调用
@ -43,7 +29,7 @@
private Context mContext; // 应用程序上下文 private Context mContext; // 应用程序上下文
private NotificationManager mNotifiManager; // 通知管理器 private NotificationManager mNotifiManager; // 通知管理器
private GTaskManager mTaskManager; // Google任务管理器 private GTaskManager mTaskManager; // Google 任务管理器
private OnCompleteListener mOnCompleteListener; // 完成监听器 private OnCompleteListener mOnCompleteListener; // 完成监听器
/** /**
@ -60,6 +46,7 @@
/** /**
* *
* Google cancelSync
*/ */
public void cancelSync() { public void cancelSync() {
mTaskManager.cancelSync(); mTaskManager.cancelSync();
@ -84,7 +71,7 @@
notification.flags = Notification.FLAG_AUTO_CANCEL; // 设置通知自动取消 notification.flags = Notification.FLAG_AUTO_CANCEL; // 设置通知自动取消
PendingIntent pendingIntent; // 待决意图 PendingIntent pendingIntent; // 待决意图
// 根据tickerId设置不同的待决意图 // 根据 tickerId 设置不同的待决意图
if (tickerId != R.string.ticker_success) { if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, NotesPreferenceActivity.class), 0); pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, NotesPreferenceActivity.class), 0);
} else { } else {
@ -112,7 +99,7 @@
protected void onProgressUpdate(String... progress) { protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]); // 显示同步中的通知 showNotification(R.string.ticker_syncing, progress[0]); // 显示同步中的通知
if (mContext instanceof GTaskSyncService) { if (mContext instanceof GTaskSyncService) {
((GTaskSyncService) mContext).sendBroadcast(progress[0]); // 如果上下文是GTaskSyncService发送广播 ((GTaskSyncService) mContext).sendBroadcast(progress[0]); // 如果上下文是 GTaskSyncService发送广播
} }
} }
@ -133,7 +120,7 @@
} else if (result == GTaskManager.STATE_SYNC_CANCELLED) { } else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
showNotification(R.string.ticker_cancel, mContext.getString(R.string.error_sync_cancelled)); showNotification(R.string.ticker_cancel, mContext.getString(R.string.error_sync_cancelled));
} }
// 如果设置了完成监听器,则在新线程中调用onComplete方法 // 如果设置了完成监听器,则在新线程中调用 onComplete 方法
if (mOnCompleteListener != null) { if (mOnCompleteListener != null) {
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
@ -142,4 +129,27 @@
}).start(); }).start();
} }
} }
} }
/**
*
GTaskASyncTask Google AsyncTask Google
GTASK_SYNC_NOTIFICATION_ID ID
OnCompleteListener
mContext
mNotifiManager
mTaskManagerGoogle
mOnCompleteListener
GTaskASyncTask(Context context, OnCompleteListener listener) Google
cancelSync() Google cancelSync
publishProgess(String message) publishProgress
showNotification(int tickerId, String content) tickerId
doInBackground(Void... unused) Google sync
onProgressUpdate(String... progress) GTaskSyncService广
onPostExecute(Integer result)线 onComplete
*/

@ -1,19 +1,3 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote; package net.micode.notes.gtask.remote;
import android.accounts.Account; import android.accounts.Account;
@ -60,45 +44,32 @@ import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater; import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream; import java.util.zip.InflaterInputStream;
/**
* GTaskClient Google
*
*/
public class GTaskClient { public class GTaskClient {
// 类名的简写,用于日志输出 private static final String TAG = GTaskClient.class.getSimpleName(); // 类名的简写,用于日志输出
private static final String TAG = GTaskClient.class.getSimpleName();
private static final String GTASK_URL = "https://mail.google.com/tasks/"; // Google任务的URL地址
// Google任务的URL地址 private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; // 获取任务的URL
private static final String GTASK_URL = "https://mail.google.com/tasks/"; private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; // 发布任务的URL
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; private static GTaskClient mInstance = null; // 单例对象
// 单例对象 private DefaultHttpClient mHttpClient; // HTTP客户端
private static GTaskClient mInstance = null; private String mGetUrl; // 获取任务的URL
private String mPostUrl; // 发布任务的URL
// HTTP客户端 private long mClientVersion; // 客户端版本号
private DefaultHttpClient mHttpClient; private boolean mLoggedin; // 登录状态
private long mLastLoginTime; // 上次登录时间
// 获取和发布任务的URL private int mActionId; // 动作ID
private String mGetUrl; private Account mAccount; // 账户信息
private String mPostUrl; private JSONArray mUpdateArray; // 更新数组
// 客户端版本号 /**
private long mClientVersion; *
*/
// 登录状态
private boolean mLoggedin;
// 上次登录时间
private long mLastLoginTime;
// 动作ID
private int mActionId;
// 账户信息
private Account mAccount;
// 更新数组
private JSONArray mUpdateArray;
// 私有构造函数,防止外部直接创建对象
private GTaskClient() { private GTaskClient() {
mHttpClient = null; mHttpClient = null;
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL;
@ -111,7 +82,10 @@ public class GTaskClient {
mUpdateArray = null; mUpdateArray = null;
} }
// 获取单例对象 /**
*
* @return GTaskClient
*/
public static synchronized GTaskClient getInstance() { public static synchronized GTaskClient getInstance() {
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskClient(); mInstance = new GTaskClient();
@ -119,18 +93,19 @@ public class GTaskClient {
return mInstance; return mInstance;
} }
// 登录方法 /**
*
* @param activity Activity
* @return truefalse
*/
public boolean login(Activity activity) { public boolean login(Activity activity) {
// 假设cookie会在5分钟后过期需要重新登录 final long interval = 1000 * 60 * 5; // 假设cookie会在5分钟后过期需要重新登录
final long interval = 1000 * 60 * 5;
if (mLastLoginTime + interval < System.currentTimeMillis()) { if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false; mLoggedin = false;
} }
// 切换账户后需要重新登录 // 切换账户后需要重新登录
if (mLoggedin if (mLoggedin && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity.getSyncAccountName(activity))) {
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) {
mLoggedin = false; mLoggedin = false;
} }
@ -150,8 +125,7 @@ public class GTaskClient {
} }
// 如果账户不是Gmail或Googlemail则尝试使用自定义域名登录 // 如果账户不是Gmail或Googlemail则尝试使用自定义域名登录
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);
@ -179,13 +153,16 @@ public class GTaskClient {
return true; return true;
} }
// 获取Google账户的认证令牌 /**
* Google
* @param activity Activity
* @param invalidateToken 使
* @return
*/
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); Account[] accounts = accountManager.getAccountsByType("com.google"); // 获取所有Google账户
// 获取所有Google账户
Account[] accounts = accountManager.getAccountsByType("com.google");
// 如果没有Google账户则返回null // 如果没有Google账户则返回null
if (accounts.length == 0) { if (accounts.length == 0) {
@ -213,13 +190,10 @@ public class GTaskClient {
} }
// 获取认证令牌 // 获取认证令牌
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对象 Bundle authTokenBundle = accountManagerFuture.getResult(); // 获取认证令牌的Bundle对象
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);
@ -233,10 +207,14 @@ public class GTaskClient {
return authToken; return authToken;
} }
}
// 尝试使用给定的认证令牌登录Google任务 /**
private boolean tryToLoginGtask(Activity activity, String authToken) { * 使Google
* @param activity Activity
* @param authToken
* @return truefalse
*/
private boolean tryToLoginGtask(Activity activity, String authToken) {
// 如果使用给定的认证令牌登录失败 // 如果使用给定的认证令牌登录失败
if (!loginGtask(authToken)) { if (!loginGtask(authToken)) {
// 可能认证令牌已过期,现在使令牌无效并再次尝试登录 // 可能认证令牌已过期,现在使令牌无效并再次尝试登录
@ -254,33 +232,29 @@ private boolean tryToLoginGtask(Activity activity, String authToken) {
} }
} }
return true; return true;
} }
// 使用给定的认证令牌登录Google任务 /**
private boolean loginGtask(String authToken) { * 使Google
// 设置连接超时和套接字超时的时间 * @param authToken
int timeoutConnection = 10000; * @return truefalse
int timeoutSocket = 15000; */
private boolean loginGtask(String authToken) {
int timeoutConnection = 10000; // 设置连接超时时间
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); // 创建HTTP客户端
mHttpClient = new DefaultHttpClient(httpParameters);
// 创建本地Cookie存储
BasicCookieStore localBasicCookieStore = new BasicCookieStore(); BasicCookieStore localBasicCookieStore = new BasicCookieStore();
mHttpClient.setCookieStore(localBasicCookieStore); mHttpClient.setCookieStore(localBasicCookieStore);
// 设置HTTP协议参数 HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); // 设置HTTP协议参数
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// 登录Google任务
try { try {
// 构建登录URL String loginUrl = mGetUrl + "?auth=" + authToken; // 构建登录URL
String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl); HttpGet httpGet = new HttpGet(loginUrl);
// 执行HTTP GET请求 HttpResponse response = mHttpClient.execute(httpGet); // 执行HTTP GET请求
HttpResponse response = mHttpClient.execute(httpGet);
// 获取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) {
@ -293,7 +267,6 @@ private boolean loginGtask(String authToken) {
Log.w(TAG, "it seems that there is no auth cookie"); Log.w(TAG, "it seems that there is no auth cookie");
} }
// 获取客户端版本
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup("; String jsBegin = "_setup(";
String jsEnd = ")}</script>"; String jsEnd = ")}</script>";
@ -316,34 +289,41 @@ private boolean loginGtask(String authToken) {
} }
return true; return true;
} }
// 获取动作ID /**
private int getActionId() { * ID
// 返回并递增动作ID * @return ID
return mActionId++; */
} private int getActionId() {
return mActionId++; // 返回并递增动作ID
}
// 创建HTTP POST请求 /**
private HttpPost createHttpPost() { * HTTP POST
* @return HttpPost
*/
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");
httpPost.setHeader("AT", "1"); httpPost.setHeader("AT", "1");
return httpPost; return httpPost;
} }
// 获取HTTP响应的内容 /**
private String getResponseContent(HttpEntity entity) throws IOException { * HTTP
* @param entity HttpEntity
* @return
* @throws IOException IO
*/
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();
// 根据内容编码解压缩响应内容
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")) {
@ -352,7 +332,6 @@ private String getResponseContent(HttpEntity entity) throws IOException {
} }
try { try {
// 读取响应内容
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();
@ -365,36 +344,32 @@ private String getResponseContent(HttpEntity entity) throws IOException {
sb = sb.append(buff); sb = sb.append(buff);
} }
} finally { } finally {
// 关闭输入流
input.close(); input.close();
} }
} }
// 发送POST请求 /**
private JSONObject postRequest(JSONObject js) throws NetworkFailureException { * POST
// 如果未登录,则抛出异常 * @param js JSON
* @return JSON
* @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");
throw new ActionFailureException("not logged in"); throw new ActionFailureException("not logged in");
} }
// 创建HTTP POST请求
HttpPost httpPost = createHttpPost(); HttpPost httpPost = createHttpPost();
try { try {
// 创建参数列表
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()));
// 创建URL编码的表单实体
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entity); httpPost.setEntity(entity);
// 执行POST请求
HttpResponse response = mHttpClient.execute(httpPost); HttpResponse response = mHttpClient.execute(httpPost);
// 获取响应内容
String jsString = getResponseContent(response.getEntity()); String jsString = getResponseContent(response.getEntity());
// 将响应内容转换为JSON对象
return new JSONObject(jsString); return new JSONObject(jsString);
} catch (ClientProtocolException e) { } catch (ClientProtocolException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
@ -412,87 +387,69 @@ private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("error occurs when posting request"); throw new ActionFailureException("error occurs when posting request");
} }
} }
// 创建任务 /**
public void createTask(Task task) throws NetworkFailureException { *
// 提交更新 * @param task Task
* @throws NetworkFailureException
*/
public void createTask(Task task) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
// 创建JSON对象
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
// 添加创建任务的动作
actionList.put(task.getCreateAction(getActionId())); actionList.put(task.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// 设置客户端版本
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);
// 获取响应结果 JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
// 设置任务的GID
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 { *
// 提交更新 * @param tasklist TaskList
* @throws NetworkFailureException
*/
public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
// 创建JSON对象
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
// 添加创建任务列表的动作
actionList.put(tasklist.getCreateAction(getActionId())); actionList.put(tasklist.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// 设置客户端版本
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);
// 获取响应结果 JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
// 设置任务列表的GID
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 { *
// 如果存在更新数组 * @throws NetworkFailureException
*/
public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) { if (mUpdateArray != null) {
try { try {
// 创建JSON对象
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
// 添加更新动作列表
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
// 设置客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送POST请求
postRequest(jsPost); postRequest(jsPost);
// 清空更新数组
mUpdateArray = null; mUpdateArray = null;
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
@ -500,110 +457,103 @@ public void commitUpdate() throws NetworkFailureException {
throw new ActionFailureException("commit update: handing jsonobject failed"); throw new ActionFailureException("commit update: handing jsonobject failed");
} }
} }
} }
// 添加更新节点 /**
public void addUpdateNode(Node node) throws NetworkFailureException { *
// 如果节点不为空 * @param node Node
* @throws NetworkFailureException
*/
public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) { if (node != null) {
// 如果更新项过多,则提交更新
if (mUpdateArray != null && mUpdateArray.length() > 10) { if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate(); commitUpdate();
} }
// 如果更新数组为空,则创建新的数组 if (mUpdateArray == null) {
if (mUpdateArray == null)
mUpdateArray = new JSONArray(); mUpdateArray = new JSONArray();
// 添加更新动作 }
mUpdateArray.put(node.getUpdateAction(getActionId())); mUpdateArray.put(node.getUpdateAction(getActionId()));
} }
} }
// 移动任务 /**
public void moveTask(Task task, TaskList preParent, TaskList curParent) *
throws NetworkFailureException { * @param task Task
// 提交更新 * @param preParent
* @param curParent
* @throws NetworkFailureException
*/
public void moveTask(Task task, TaskList preParent, TaskList curParent) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
// 创建JSON对象
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject(); JSONObject action = new JSONObject();
// 添加移动任务的动作 action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid());
if (preParent == curParent && task.getPriorSibling() != null) { if (preParent == curParent && task.getPriorSibling() != null) {
// 如果在同一个任务列表中移动且不是第一个则添加前一个兄弟节点的ID
action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
} }
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid());
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid());
if (preParent != curParent) { if (preParent != curParent) {
// 如果在不同任务列表之间移动则添加目标列表的ID
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
} }
actionList.put(action); actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// 设置客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送POST请求
postRequest(jsPost); postRequest(jsPost);
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("move task: handing jsonobject failed"); throw new ActionFailureException("move task: handing jsonobject failed");
} }
} }
// 删除节点 /**
public void deleteNode(Node node) throws NetworkFailureException { *
// 提交所有挂起的更新 * @param node Node
* @throws NetworkFailureException
*/
public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
// 创建JSON对象来构建请求体
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
// 设置节点为已删除,并添加更新动作到动作列表中
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);
// 设置客户端版本号
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();
throw new ActionFailureException("delete node: handing jsonobject failed"); throw new ActionFailureException("delete node: handing jsonobject failed");
} }
} }
// 获取任务列表 /**
public JSONArray getTaskLists() throws NetworkFailureException { *
// 如果未登录,则抛出异常 * @return JSON
* @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 = mHttpClient.execute(httpGet);
response = mHttpClient.execute(httpGet);
// 获取任务列表
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup("; String jsBegin = "_setup(";
String jsEnd = ")}</script>"; String jsEnd = ")}</script>";
@ -614,7 +564,6 @@ public JSONArray getTaskLists() throws NetworkFailureException {
jsString = resString.substring(begin + jsBegin.length(), end); jsString = resString.substring(begin + jsBegin.length(), end);
} }
JSONObject js = new JSONObject(jsString); JSONObject js = new JSONObject(jsString);
// 返回任务列表的JSON数组
return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
} catch (ClientProtocolException e) { } catch (ClientProtocolException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
@ -629,47 +578,90 @@ public JSONArray getTaskLists() throws NetworkFailureException {
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("get task lists: handing jasonobject failed"); throw new ActionFailureException("get task lists: handing jasonobject failed");
} }
} }
// 获取特定任务列表中的任务 /**
public JSONArray getTaskList(String listGid) throws NetworkFailureException { *
// 提交所有挂起的更新 * @param listGid GID
* @return JSON
* @throws NetworkFailureException
*/
public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
// 创建JSON对象来构建请求体
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject(); JSONObject action = new JSONObject();
// 构建获取任务的动作 action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid);
action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false);
actionList.put(action); actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// 设置客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送请求并获取响应
JSONObject jsResponse = postRequest(jsPost); JSONObject jsResponse = postRequest(jsPost);
// 返回任务的JSON数组
return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS);
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("get task list: handing jsonobject failed"); throw new ActionFailureException("get task list: handing jsonobject failed");
} }
} }
// 获取用于同步的账户 /**
public Account getSyncAccount() { *
* @return
*/
public Account getSyncAccount() {
return mAccount; return mAccount;
} }
// 重置更新数组 /**
public void resetUpdateArray() { *
*/
public void resetUpdateArray() {
mUpdateArray = null; mUpdateArray = null;
}
} }
/**
*
GTaskClient Google
TAG
GTASK_URLGTASK_GET_URLGTASK_POST_URLGoogle URL
mInstance
mHttpClientHTTP
mGetUrlmPostUrl URL
mClientVersion
mLoggedin
mLastLoginTime
mActionId ID
mAccount
mUpdateArray
GTaskClient
getInstance
login
loginGoogleAccount Google
tryToLoginGtask使 Google
loginGtask使 Google
getActionId ID
createHttpPost HTTP POST
getResponseContent HTTP
postRequest POST
createTask
createTaskList
commitUpdate
addUpdateNode
moveTask
deleteNode
getTaskLists
getTaskList
getSyncAccount
resetUpdateArray
*/
Loading…
Cancel
Save