From be4eadda91bd3cec2f99b884172f54f0d6268fce Mon Sep 17 00:00:00 2001 From: hu <1515867307@qq.com> Date: Thu, 29 May 2025 14:48:41 +0800 Subject: [PATCH 1/3] data --- Contact.java | 91 ++++++++++ Notes.java | 279 ++++++++++++++++++++++++++++++ NotesDatabaseHelper.java | 362 +++++++++++++++++++++++++++++++++++++++ NotesProvider.java | 305 +++++++++++++++++++++++++++++++++ 4 files changed, 1037 insertions(+) create mode 100644 Contact.java create mode 100644 Notes.java create mode 100644 NotesDatabaseHelper.java create mode 100644 NotesProvider.java diff --git a/Contact.java b/Contact.java new file mode 100644 index 0000000..c6a5642 --- /dev/null +++ b/Contact.java @@ -0,0 +1,91 @@ +/* + * 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.data; + +import android.content.Context; +import android.database.Cursor; +import android.provider.ContactsContract.CommonDataKinds.Phone; +import android.provider.ContactsContract.Data; +import android.telephony.PhoneNumberUtils; +import android.util.Log; + +import java.util.HashMap; + +public class Contact { + // 用于缓存电话号码与联系人姓名的映射关系,提高查询效率 + private static HashMap sContactCache; + // 日志标签 + private static final String TAG = "Contact"; + + // 查询联系人数据库的SQL选择语句 + // 这个复杂查询: + // 1. 检查电话号码是否匹配(考虑不同格式) + // 2. 验证数据类型是电话号码 + // 3. 确保原始联系人存在于phone_lookup表中 + private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER + + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + + " AND " + Data.RAW_CONTACT_ID + " IN " + + "(SELECT raw_contact_id " + + " FROM phone_lookup" + + " WHERE min_match = '+')"; + /** + * 根据电话号码获取联系人姓名 + * + * @param context 应用上下文 + * @param phoneNumber 要查询的电话号码 + * @return 如果找到则返回联系人姓名,否则返回null + */ + public static String getContact(Context context, String phoneNumber) { + // 如果缓存不存在,则初始化 + if(sContactCache == null) { + sContactCache = new HashMap(); + } + // 如果缓存中已有结果,直接返回 + if(sContactCache.containsKey(phoneNumber)) { + return sContactCache.get(phoneNumber); + } + // 准备查询语句,将'+'替换为电话号码的最小匹配模式(处理不同格式) + String selection = CALLER_ID_SELECTION.replace("+", + PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); + // 查询联系人数据库 + Cursor cursor = context.getContentResolver().query( + Data.CONTENT_URI, // 联系人数据的内容URI + new String [] { Phone.DISPLAY_NAME }, // 只获取显示名称 + selection, // 准备好的查询条件 + new String[] { phoneNumber }, // 查询参数 + null); // 无排序要求 + // 处理查询结果 + if (cursor != null && cursor.moveToFirst()) { + try { + // 从第一条结果获取联系人姓名 + String name = cursor.getString(0); + // 将结果缓存以备后用 + sContactCache.put(phoneNumber, name); + return name; + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, " Cursor get string error " + e.toString()); + return null; + } finally { + // 始终关闭游标,避免内存泄漏 + cursor.close(); + } + } else { + Log.d(TAG, "No contact matched with number:" + phoneNumber); + return null; + } + } +} diff --git a/Notes.java b/Notes.java new file mode 100644 index 0000000..f240604 --- /dev/null +++ b/Notes.java @@ -0,0 +1,279 @@ +/* + * 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.data; + +import android.net.Uri; +public class Notes { + public static final String AUTHORITY = "micode_notes"; + public static final String TAG = "Notes"; + public static final int TYPE_NOTE = 0; + public static final int TYPE_FOLDER = 1; + public static final int TYPE_SYSTEM = 2; + + /** + * Following IDs are system folders' identifiers + * {@link Notes#ID_ROOT_FOLDER } is default folder + * {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder + * {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records + */ + public static final int ID_ROOT_FOLDER = 0; + public static final int ID_TEMPARAY_FOLDER = -1; + public static final int ID_CALL_RECORD_FOLDER = -2; + public static final int ID_TRASH_FOLER = -3; + + public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; + public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; + public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; + public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; + public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; + public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; + + public static final int TYPE_WIDGET_INVALIDE = -1; + public static final int TYPE_WIDGET_2X = 0; + public static final int TYPE_WIDGET_4X = 1; + + public static class DataConstants { + public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; + public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; + } + + /** + * Uri to query all notes and folders + */ + public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note"); + + /** + * Uri to query data + */ + public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); + + public interface NoteColumns { + /** + * The unique ID for a row + *

Type: INTEGER (long)

+ */ + public static final String ID = "_id"; + + /** + * The parent's id for note or folder + *

Type: INTEGER (long)

+ */ + public static final String PARENT_ID = "parent_id"; + + /** + * Created data for note or folder + *

Type: INTEGER (long)

+ */ + public static final String CREATED_DATE = "created_date"; + + /** + * Latest modified date + *

Type: INTEGER (long)

+ */ + public static final String MODIFIED_DATE = "modified_date"; + + + /** + * Alert date + *

Type: INTEGER (long)

+ */ + public static final String ALERTED_DATE = "alert_date"; + + /** + * Folder's name or text content of note + *

Type: TEXT

+ */ + public static final String SNIPPET = "snippet"; + + /** + * Note's widget id + *

Type: INTEGER (long)

+ */ + public static final String WIDGET_ID = "widget_id"; + + /** + * Note's widget type + *

Type: INTEGER (long)

+ */ + public static final String WIDGET_TYPE = "widget_type"; + + /** + * Note's background color's id + *

Type: INTEGER (long)

+ */ + public static final String BG_COLOR_ID = "bg_color_id"; + + /** + * For text note, it doesn't has attachment, for multi-media + * note, it has at least one attachment + *

Type: INTEGER

+ */ + public static final String HAS_ATTACHMENT = "has_attachment"; + + /** + * Folder's count of notes + *

Type: INTEGER (long)

+ */ + public static final String NOTES_COUNT = "notes_count"; + + /** + * The file type: folder or note + *

Type: INTEGER

+ */ + public static final String TYPE = "type"; + + /** + * The last sync id + *

Type: INTEGER (long)

+ */ + public static final String SYNC_ID = "sync_id"; + + /** + * Sign to indicate local modified or not + *

Type: INTEGER

+ */ + public static final String LOCAL_MODIFIED = "local_modified"; + + /** + * Original parent id before moving into temporary folder + *

Type : INTEGER

+ */ + public static final String ORIGIN_PARENT_ID = "origin_parent_id"; + + /** + * The gtask id + *

Type : TEXT

+ */ + public static final String GTASK_ID = "gtask_id"; + + /** + * The version code + *

Type : INTEGER (long)

+ */ + public static final String VERSION = "version"; + } + + public interface DataColumns { + /** + * The unique ID for a row + *

Type: INTEGER (long)

+ */ + public static final String ID = "_id"; + + /** + * The MIME type of the item represented by this row. + *

Type: Text

+ */ + public static final String MIME_TYPE = "mime_type"; + + /** + * The reference id to note that this data belongs to + *

Type: INTEGER (long)

+ */ + public static final String NOTE_ID = "note_id"; + + /** + * Created data for note or folder + *

Type: INTEGER (long)

+ */ + public static final String CREATED_DATE = "created_date"; + + /** + * Latest modified date + *

Type: INTEGER (long)

+ */ + public static final String MODIFIED_DATE = "modified_date"; + + /** + * Data's content + *

Type: TEXT

+ */ + public static final String CONTENT = "content"; + + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * integer data type + *

Type: INTEGER

+ */ + public static final String DATA1 = "data1"; + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * integer data type + *

Type: INTEGER

+ */ + public static final String DATA2 = "data2"; + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * TEXT data type + *

Type: TEXT

+ */ + public static final String DATA3 = "data3"; + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * TEXT data type + *

Type: TEXT

+ */ + public static final String DATA4 = "data4"; + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * TEXT data type + *

Type: TEXT

+ */ + public static final String DATA5 = "data5"; + } + + public static final class TextNote implements DataColumns { + /** + * Mode to indicate the text in check list mode or not + *

Type: Integer 1:check list mode 0: normal mode

+ */ + public static final String MODE = DATA1; + + public static final int MODE_CHECK_LIST = 1; + + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; + + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; + + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); + } + + public static final class CallNote implements DataColumns { + /** + * Call date for this record + *

Type: INTEGER (long)

+ */ + public static final String CALL_DATE = DATA1; + + /** + * Phone number for this record + *

Type: TEXT

+ */ + public static final String PHONE_NUMBER = DATA3; + + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; + + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; + + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); + } +} diff --git a/NotesDatabaseHelper.java b/NotesDatabaseHelper.java new file mode 100644 index 0000000..ffe5d57 --- /dev/null +++ b/NotesDatabaseHelper.java @@ -0,0 +1,362 @@ +/* + * 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.data; + +import android.content.ContentValues; +import android.content.Context; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.util.Log; + +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; + + +public class NotesDatabaseHelper extends SQLiteOpenHelper { + private static final String DB_NAME = "note.db"; + + private static final int DB_VERSION = 4; + + public interface TABLE { + public static final String NOTE = "note"; + + public static final String DATA = "data"; + } + + private static final String TAG = "NotesDatabaseHelper"; + + private static NotesDatabaseHelper mInstance; + + private static final String CREATE_NOTE_TABLE_SQL = + "CREATE TABLE " + TABLE.NOTE + "(" + + NoteColumns.ID + " INTEGER PRIMARY KEY," + + NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + + NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + + NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + + ")"; + + private static final String CREATE_DATA_TABLE_SQL = + "CREATE TABLE " + TABLE.DATA + "(" + + DataColumns.ID + " INTEGER PRIMARY KEY," + + DataColumns.MIME_TYPE + " TEXT NOT NULL," + + DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + + DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA1 + " INTEGER," + + DataColumns.DATA2 + " INTEGER," + + DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + + ")"; + + private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = + "CREATE INDEX IF NOT EXISTS note_id_index ON " + + TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; + + /** + * Increase folder's note count when move note to the folder + */ + private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = + "CREATE TRIGGER increase_folder_count_on_update "+ + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + + " END"; + + /** + * Decrease folder's note count when move note from folder + */ + private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = + "CREATE TRIGGER decrease_folder_count_on_update " + + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + + " AND " + NoteColumns.NOTES_COUNT + ">0" + ";" + + " END"; + + /** + * Increase folder's note count when insert new note to the folder + */ + private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER = + "CREATE TRIGGER increase_folder_count_on_insert " + + " AFTER INSERT ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + + " END"; + + /** + * Decrease folder's note count when delete note from the folder + */ + private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER = + "CREATE TRIGGER decrease_folder_count_on_delete " + + " AFTER DELETE ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + + " AND " + NoteColumns.NOTES_COUNT + ">0;" + + " END"; + + /** + * Update note's content when insert data with type {@link DataConstants#NOTE} + */ + private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = + "CREATE TRIGGER update_note_content_on_insert " + + " AFTER INSERT ON " + TABLE.DATA + + " WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + + " END"; + + /** + * Update note's content when data with {@link DataConstants#NOTE} type has changed + */ + private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER = + "CREATE TRIGGER update_note_content_on_update " + + " AFTER UPDATE ON " + TABLE.DATA + + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + + " END"; + + /** + * Update note's content when data with {@link DataConstants#NOTE} type has deleted + */ + private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER = + "CREATE TRIGGER update_note_content_on_delete " + + " AFTER delete ON " + TABLE.DATA + + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.SNIPPET + "=''" + + " WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" + + " END"; + + /** + * Delete datas belong to note which has been deleted + */ + private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = + "CREATE TRIGGER delete_data_on_delete " + + " AFTER DELETE ON " + TABLE.NOTE + + " BEGIN" + + " DELETE FROM " + TABLE.DATA + + " WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" + + " END"; + + /** + * Delete notes belong to folder which has been deleted + */ + private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER = + "CREATE TRIGGER folder_delete_notes_on_delete " + + " AFTER DELETE ON " + TABLE.NOTE + + " BEGIN" + + " DELETE FROM " + TABLE.NOTE + + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + + " END"; + + /** + * Move notes belong to folder which has been moved to trash folder + */ + private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER = + "CREATE TRIGGER folder_move_notes_on_trash " + + " AFTER UPDATE ON " + TABLE.NOTE + + " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + + " END"; + + public NotesDatabaseHelper(Context context) { + super(context, DB_NAME, null, DB_VERSION); + } + + public void createNoteTable(SQLiteDatabase db) { + db.execSQL(CREATE_NOTE_TABLE_SQL); + reCreateNoteTableTriggers(db); + createSystemFolder(db); + Log.d(TAG, "note table has been created"); + } + + private void reCreateNoteTableTriggers(SQLiteDatabase db) { + db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update"); + db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update"); + db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS delete_data_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert"); + db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash"); + + db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); + db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); + db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER); + db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER); + db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER); + db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER); + db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER); + } + + private void createSystemFolder(SQLiteDatabase db) { + ContentValues values = new ContentValues(); + + /** + * call record foler for call notes + */ + values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + /** + * root folder which is default folder + */ + values.clear(); + values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + /** + * temporary folder which is used for moving note + */ + values.clear(); + values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + /** + * create trash folder + */ + values.clear(); + values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + } + + public void createDataTable(SQLiteDatabase db) { + db.execSQL(CREATE_DATA_TABLE_SQL); + reCreateDataTableTriggers(db); + db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); + Log.d(TAG, "data table has been created"); + } + + private void reCreateDataTableTriggers(SQLiteDatabase db) { + db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete"); + + db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER); + db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER); + db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER); + } + + static synchronized NotesDatabaseHelper getInstance(Context context) { + if (mInstance == null) { + mInstance = new NotesDatabaseHelper(context); + } + return mInstance; + } + + @Override + public void onCreate(SQLiteDatabase db) { + createNoteTable(db); + createDataTable(db); + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + boolean reCreateTriggers = false; + boolean skipV2 = false; + + if (oldVersion == 1) { + upgradeToV2(db); + skipV2 = true; // this upgrade including the upgrade from v2 to v3 + oldVersion++; + } + + if (oldVersion == 2 && !skipV2) { + upgradeToV3(db); + reCreateTriggers = true; + oldVersion++; + } + + if (oldVersion == 3) { + upgradeToV4(db); + oldVersion++; + } + + if (reCreateTriggers) { + reCreateNoteTableTriggers(db); + reCreateDataTableTriggers(db); + } + + if (oldVersion != newVersion) { + throw new IllegalStateException("Upgrade notes database to version " + newVersion + + "fails"); + } + } + + private void upgradeToV2(SQLiteDatabase db) { + db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); + db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); + createNoteTable(db); + createDataTable(db); + } + + private void upgradeToV3(SQLiteDatabase db) { + // drop unused triggers + db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update"); + // add a column for gtask id + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID + + " TEXT NOT NULL DEFAULT ''"); + // add a trash system folder + ContentValues values = new ContentValues(); + values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + } + + private void upgradeToV4(SQLiteDatabase db) { + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION + + " INTEGER NOT NULL DEFAULT 0"); + } +} diff --git a/NotesProvider.java b/NotesProvider.java new file mode 100644 index 0000000..edb0a60 --- /dev/null +++ b/NotesProvider.java @@ -0,0 +1,305 @@ +/* + * 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.data; + + +import android.app.SearchManager; +import android.content.ContentProvider; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Intent; +import android.content.UriMatcher; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.net.Uri; +import android.text.TextUtils; +import android.util.Log; + +import net.micode.notes.R; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.NotesDatabaseHelper.TABLE; + + +public class NotesProvider extends ContentProvider { + private static final UriMatcher mMatcher; + + private NotesDatabaseHelper mHelper; + + private static final String TAG = "NotesProvider"; + + private static final int URI_NOTE = 1; + private static final int URI_NOTE_ITEM = 2; + private static final int URI_DATA = 3; + private static final int URI_DATA_ITEM = 4; + + private static final int URI_SEARCH = 5; + private static final int URI_SEARCH_SUGGEST = 6; + + static { + mMatcher = new UriMatcher(UriMatcher.NO_MATCH); + mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); + mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); + mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); + mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); + mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); + mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST); + mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST); + } + + /** + * x'0A' represents the '\n' character in sqlite. For title and content in the search result, + * we will trim '\n' and white space in order to show more information. + */ + private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + "," + + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + "," + + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + "," + + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + "," + + R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + "," + + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," + + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; + + private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION + + " FROM " + TABLE.NOTE + + " WHERE " + NoteColumns.SNIPPET + " LIKE ?" + + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; + + @Override + public boolean onCreate() { + mHelper = NotesDatabaseHelper.getInstance(getContext()); + return true; + } + + @Override + public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, + String sortOrder) { + Cursor c = null; + SQLiteDatabase db = mHelper.getReadableDatabase(); + String id = null; + switch (mMatcher.match(uri)) { + case URI_NOTE: + c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, + sortOrder); + break; + case URI_NOTE_ITEM: + id = uri.getPathSegments().get(1); + c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id + + parseSelection(selection), selectionArgs, null, null, sortOrder); + break; + case URI_DATA: + c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, + sortOrder); + break; + case URI_DATA_ITEM: + id = uri.getPathSegments().get(1); + c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id + + parseSelection(selection), selectionArgs, null, null, sortOrder); + break; + case URI_SEARCH: + case URI_SEARCH_SUGGEST: + if (sortOrder != null || projection != null) { + throw new IllegalArgumentException( + "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query"); + } + + String searchString = null; + if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { + if (uri.getPathSegments().size() > 1) { + searchString = uri.getPathSegments().get(1); + } + } else { + searchString = uri.getQueryParameter("pattern"); + } + + if (TextUtils.isEmpty(searchString)) { + return null; + } + + try { + searchString = String.format("%%%s%%", searchString); + c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, + new String[] { searchString }); + } catch (IllegalStateException ex) { + Log.e(TAG, "got exception: " + ex.toString()); + } + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } + if (c != null) { + c.setNotificationUri(getContext().getContentResolver(), uri); + } + return c; + } + + @Override + public Uri insert(Uri uri, ContentValues values) { + SQLiteDatabase db = mHelper.getWritableDatabase(); + long dataId = 0, noteId = 0, insertedId = 0; + switch (mMatcher.match(uri)) { + case URI_NOTE: + insertedId = noteId = db.insert(TABLE.NOTE, null, values); + break; + case URI_DATA: + if (values.containsKey(DataColumns.NOTE_ID)) { + noteId = values.getAsLong(DataColumns.NOTE_ID); + } else { + Log.d(TAG, "Wrong data format without note id:" + values.toString()); + } + insertedId = dataId = db.insert(TABLE.DATA, null, values); + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } + // Notify the note uri + if (noteId > 0) { + getContext().getContentResolver().notifyChange( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); + } + + // Notify the data uri + if (dataId > 0) { + getContext().getContentResolver().notifyChange( + ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); + } + + return ContentUris.withAppendedId(uri, insertedId); + } + + @Override + public int delete(Uri uri, String selection, String[] selectionArgs) { + int count = 0; + String id = null; + SQLiteDatabase db = mHelper.getWritableDatabase(); + boolean deleteData = false; + switch (mMatcher.match(uri)) { + case URI_NOTE: + selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; + count = db.delete(TABLE.NOTE, selection, selectionArgs); + break; + case URI_NOTE_ITEM: + id = uri.getPathSegments().get(1); + /** + * ID that smaller than 0 is system folder which is not allowed to + * trash + */ + long noteId = Long.valueOf(id); + if (noteId <= 0) { + break; + } + count = db.delete(TABLE.NOTE, + NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs); + break; + case URI_DATA: + count = db.delete(TABLE.DATA, selection, selectionArgs); + deleteData = true; + break; + case URI_DATA_ITEM: + id = uri.getPathSegments().get(1); + count = db.delete(TABLE.DATA, + DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); + deleteData = true; + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } + if (count > 0) { + if (deleteData) { + getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); + } + getContext().getContentResolver().notifyChange(uri, null); + } + return count; + } + + @Override + public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { + int count = 0; + String id = null; + SQLiteDatabase db = mHelper.getWritableDatabase(); + boolean updateData = false; + switch (mMatcher.match(uri)) { + case URI_NOTE: + increaseNoteVersion(-1, selection, selectionArgs); + count = db.update(TABLE.NOTE, values, selection, selectionArgs); + break; + case URI_NOTE_ITEM: + id = uri.getPathSegments().get(1); + increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); + count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id + + parseSelection(selection), selectionArgs); + break; + case URI_DATA: + count = db.update(TABLE.DATA, values, selection, selectionArgs); + updateData = true; + break; + case URI_DATA_ITEM: + id = uri.getPathSegments().get(1); + count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id + + parseSelection(selection), selectionArgs); + updateData = true; + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } + + if (count > 0) { + if (updateData) { + getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); + } + getContext().getContentResolver().notifyChange(uri, null); + } + return count; + } + + private String parseSelection(String selection) { + return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); + } + + private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { + StringBuilder sql = new StringBuilder(120); + sql.append("UPDATE "); + sql.append(TABLE.NOTE); + sql.append(" SET "); + sql.append(NoteColumns.VERSION); + sql.append("=" + NoteColumns.VERSION + "+1 "); + + if (id > 0 || !TextUtils.isEmpty(selection)) { + sql.append(" WHERE "); + } + if (id > 0) { + sql.append(NoteColumns.ID + "=" + String.valueOf(id)); + } + if (!TextUtils.isEmpty(selection)) { + String selectString = id > 0 ? parseSelection(selection) : selection; + for (String args : selectionArgs) { + selectString = selectString.replaceFirst("\\?", args); + } + sql.append(selectString); + } + + mHelper.getWritableDatabase().execSQL(sql.toString()); + } + + @Override + public String getType(Uri uri) { + // TODO Auto-generated method stub + return null; + } + +} From 30ca9845e3821a0fcb68918716829c61c8bc520d Mon Sep 17 00:00:00 2001 From: hu <1515867307@qq.com> Date: Thu, 29 May 2025 15:07:27 +0800 Subject: [PATCH 2/3] data --- data/Contact.java | 91 ++++++++ data/Notes.java | 279 +++++++++++++++++++++++++ data/NotesDatabaseHelper.java | 378 ++++++++++++++++++++++++++++++++++ data/NotesProvider.java | 372 +++++++++++++++++++++++++++++++++ 4 files changed, 1120 insertions(+) create mode 100644 data/Contact.java create mode 100644 data/Notes.java create mode 100644 data/NotesDatabaseHelper.java create mode 100644 data/NotesProvider.java diff --git a/data/Contact.java b/data/Contact.java new file mode 100644 index 0000000..c6a5642 --- /dev/null +++ b/data/Contact.java @@ -0,0 +1,91 @@ +/* + * 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.data; + +import android.content.Context; +import android.database.Cursor; +import android.provider.ContactsContract.CommonDataKinds.Phone; +import android.provider.ContactsContract.Data; +import android.telephony.PhoneNumberUtils; +import android.util.Log; + +import java.util.HashMap; + +public class Contact { + // 用于缓存电话号码与联系人姓名的映射关系,提高查询效率 + private static HashMap sContactCache; + // 日志标签 + private static final String TAG = "Contact"; + + // 查询联系人数据库的SQL选择语句 + // 这个复杂查询: + // 1. 检查电话号码是否匹配(考虑不同格式) + // 2. 验证数据类型是电话号码 + // 3. 确保原始联系人存在于phone_lookup表中 + private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER + + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + + " AND " + Data.RAW_CONTACT_ID + " IN " + + "(SELECT raw_contact_id " + + " FROM phone_lookup" + + " WHERE min_match = '+')"; + /** + * 根据电话号码获取联系人姓名 + * + * @param context 应用上下文 + * @param phoneNumber 要查询的电话号码 + * @return 如果找到则返回联系人姓名,否则返回null + */ + public static String getContact(Context context, String phoneNumber) { + // 如果缓存不存在,则初始化 + if(sContactCache == null) { + sContactCache = new HashMap(); + } + // 如果缓存中已有结果,直接返回 + if(sContactCache.containsKey(phoneNumber)) { + return sContactCache.get(phoneNumber); + } + // 准备查询语句,将'+'替换为电话号码的最小匹配模式(处理不同格式) + String selection = CALLER_ID_SELECTION.replace("+", + PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); + // 查询联系人数据库 + Cursor cursor = context.getContentResolver().query( + Data.CONTENT_URI, // 联系人数据的内容URI + new String [] { Phone.DISPLAY_NAME }, // 只获取显示名称 + selection, // 准备好的查询条件 + new String[] { phoneNumber }, // 查询参数 + null); // 无排序要求 + // 处理查询结果 + if (cursor != null && cursor.moveToFirst()) { + try { + // 从第一条结果获取联系人姓名 + String name = cursor.getString(0); + // 将结果缓存以备后用 + sContactCache.put(phoneNumber, name); + return name; + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, " Cursor get string error " + e.toString()); + return null; + } finally { + // 始终关闭游标,避免内存泄漏 + cursor.close(); + } + } else { + Log.d(TAG, "No contact matched with number:" + phoneNumber); + return null; + } + } +} diff --git a/data/Notes.java b/data/Notes.java new file mode 100644 index 0000000..f240604 --- /dev/null +++ b/data/Notes.java @@ -0,0 +1,279 @@ +/* + * 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.data; + +import android.net.Uri; +public class Notes { + public static final String AUTHORITY = "micode_notes"; + public static final String TAG = "Notes"; + public static final int TYPE_NOTE = 0; + public static final int TYPE_FOLDER = 1; + public static final int TYPE_SYSTEM = 2; + + /** + * Following IDs are system folders' identifiers + * {@link Notes#ID_ROOT_FOLDER } is default folder + * {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder + * {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records + */ + public static final int ID_ROOT_FOLDER = 0; + public static final int ID_TEMPARAY_FOLDER = -1; + public static final int ID_CALL_RECORD_FOLDER = -2; + public static final int ID_TRASH_FOLER = -3; + + public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; + public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; + public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; + public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; + public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; + public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; + + public static final int TYPE_WIDGET_INVALIDE = -1; + public static final int TYPE_WIDGET_2X = 0; + public static final int TYPE_WIDGET_4X = 1; + + public static class DataConstants { + public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; + public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; + } + + /** + * Uri to query all notes and folders + */ + public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note"); + + /** + * Uri to query data + */ + public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); + + public interface NoteColumns { + /** + * The unique ID for a row + *

Type: INTEGER (long)

+ */ + public static final String ID = "_id"; + + /** + * The parent's id for note or folder + *

Type: INTEGER (long)

+ */ + public static final String PARENT_ID = "parent_id"; + + /** + * Created data for note or folder + *

Type: INTEGER (long)

+ */ + public static final String CREATED_DATE = "created_date"; + + /** + * Latest modified date + *

Type: INTEGER (long)

+ */ + public static final String MODIFIED_DATE = "modified_date"; + + + /** + * Alert date + *

Type: INTEGER (long)

+ */ + public static final String ALERTED_DATE = "alert_date"; + + /** + * Folder's name or text content of note + *

Type: TEXT

+ */ + public static final String SNIPPET = "snippet"; + + /** + * Note's widget id + *

Type: INTEGER (long)

+ */ + public static final String WIDGET_ID = "widget_id"; + + /** + * Note's widget type + *

Type: INTEGER (long)

+ */ + public static final String WIDGET_TYPE = "widget_type"; + + /** + * Note's background color's id + *

Type: INTEGER (long)

+ */ + public static final String BG_COLOR_ID = "bg_color_id"; + + /** + * For text note, it doesn't has attachment, for multi-media + * note, it has at least one attachment + *

Type: INTEGER

+ */ + public static final String HAS_ATTACHMENT = "has_attachment"; + + /** + * Folder's count of notes + *

Type: INTEGER (long)

+ */ + public static final String NOTES_COUNT = "notes_count"; + + /** + * The file type: folder or note + *

Type: INTEGER

+ */ + public static final String TYPE = "type"; + + /** + * The last sync id + *

Type: INTEGER (long)

+ */ + public static final String SYNC_ID = "sync_id"; + + /** + * Sign to indicate local modified or not + *

Type: INTEGER

+ */ + public static final String LOCAL_MODIFIED = "local_modified"; + + /** + * Original parent id before moving into temporary folder + *

Type : INTEGER

+ */ + public static final String ORIGIN_PARENT_ID = "origin_parent_id"; + + /** + * The gtask id + *

Type : TEXT

+ */ + public static final String GTASK_ID = "gtask_id"; + + /** + * The version code + *

Type : INTEGER (long)

+ */ + public static final String VERSION = "version"; + } + + public interface DataColumns { + /** + * The unique ID for a row + *

Type: INTEGER (long)

+ */ + public static final String ID = "_id"; + + /** + * The MIME type of the item represented by this row. + *

Type: Text

+ */ + public static final String MIME_TYPE = "mime_type"; + + /** + * The reference id to note that this data belongs to + *

Type: INTEGER (long)

+ */ + public static final String NOTE_ID = "note_id"; + + /** + * Created data for note or folder + *

Type: INTEGER (long)

+ */ + public static final String CREATED_DATE = "created_date"; + + /** + * Latest modified date + *

Type: INTEGER (long)

+ */ + public static final String MODIFIED_DATE = "modified_date"; + + /** + * Data's content + *

Type: TEXT

+ */ + public static final String CONTENT = "content"; + + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * integer data type + *

Type: INTEGER

+ */ + public static final String DATA1 = "data1"; + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * integer data type + *

Type: INTEGER

+ */ + public static final String DATA2 = "data2"; + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * TEXT data type + *

Type: TEXT

+ */ + public static final String DATA3 = "data3"; + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * TEXT data type + *

Type: TEXT

+ */ + public static final String DATA4 = "data4"; + + /** + * Generic data column, the meaning is {@link #MIMETYPE} specific, used for + * TEXT data type + *

Type: TEXT

+ */ + public static final String DATA5 = "data5"; + } + + public static final class TextNote implements DataColumns { + /** + * Mode to indicate the text in check list mode or not + *

Type: Integer 1:check list mode 0: normal mode

+ */ + public static final String MODE = DATA1; + + public static final int MODE_CHECK_LIST = 1; + + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; + + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; + + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); + } + + public static final class CallNote implements DataColumns { + /** + * Call date for this record + *

Type: INTEGER (long)

+ */ + public static final String CALL_DATE = DATA1; + + /** + * Phone number for this record + *

Type: TEXT

+ */ + public static final String PHONE_NUMBER = DATA3; + + public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; + + public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; + + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); + } +} diff --git a/data/NotesDatabaseHelper.java b/data/NotesDatabaseHelper.java new file mode 100644 index 0000000..f771a3d --- /dev/null +++ b/data/NotesDatabaseHelper.java @@ -0,0 +1,378 @@ +/* + * 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.data; + +import android.content.ContentValues; +import android.content.Context; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.util.Log; + +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; + +/** + * 小米便签数据库帮助类,负责数据库的创建和版本管理 + */ +public class NotesDatabaseHelper extends SQLiteOpenHelper { + // 数据库名称 + private static final String DB_NAME = "note.db"; + // 当前数据库版本 + private static final int DB_VERSION = 4; + // 数据库表名定义接口 + public interface TABLE { + public static final String NOTE = "note"; // 笔记表 + + public static final String DATA = "data"; // 数据表 + } + + private static final String TAG = "NotesDatabaseHelper"; // 日志标签 + + private static NotesDatabaseHelper mInstance; // 单例实例 + // 创建笔记表的SQL语句 + private static final String CREATE_NOTE_TABLE_SQL = + "CREATE TABLE " + TABLE.NOTE + "(" + + NoteColumns.ID + " INTEGER PRIMARY KEY," + // 主键ID + NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + // 父ID + NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + // 提醒日期 + NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," +// 背景颜色ID + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 创建时间 + NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + // 是否有附件 + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 修改时间 + NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + // 笔记数量(针对文件夹) + NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + // 内容摘要 + NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + // 类型(笔记/文件夹) + NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + // 小部件ID + NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + // 小部件类型 + NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + // 同步ID + NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + // 本地修改标记 + NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + // 原始父ID + NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + // Google任务ID + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + // 版本号 + ")"; + // 创建数据表的SQL语句 + private static final String CREATE_DATA_TABLE_SQL = + "CREATE TABLE " + TABLE.DATA + "(" + + DataColumns.ID + " INTEGER PRIMARY KEY," + // 主键ID + DataColumns.MIME_TYPE + " TEXT NOT NULL," + // MIME类型 + DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + // 关联的笔记ID + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 创建时间 + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 修改时间 + DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + + DataColumns.DATA1 + " INTEGER," + // 通用数据列1 + DataColumns.DATA2 + " INTEGER," + // 通用数据列2 + DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + // 通用数据列3 + DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + // 通用数据列4 + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + // 通用数据列5 + ")"; + // 创建数据表笔记ID索引的SQL语句 + private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = + "CREATE INDEX IF NOT EXISTS note_id_index ON " + + TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; + + /** + * Increase folder's note count when move note to the folder + */ + private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = + "CREATE TRIGGER increase_folder_count_on_update "+ + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + + " END"; + + /** + * Decrease folder's note count when move note from folder + */ + private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = + "CREATE TRIGGER decrease_folder_count_on_update " + + " AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + + " AND " + NoteColumns.NOTES_COUNT + ">0" + ";" + + " END"; + + /** + * Increase folder's note count when insert new note to the folder + */ + private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER = + "CREATE TRIGGER increase_folder_count_on_insert " + + " AFTER INSERT ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" + + " WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" + + " END"; + + /** + * Decrease folder's note count when delete note from the folder + */ + private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER = + "CREATE TRIGGER decrease_folder_count_on_delete " + + " AFTER DELETE ON " + TABLE.NOTE + + " BEGIN " + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" + + " WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID + + " AND " + NoteColumns.NOTES_COUNT + ">0;" + + " END"; + + /** + * Update note's content when insert data with type {@link DataConstants#NOTE} + */ + private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = + "CREATE TRIGGER update_note_content_on_insert " + + " AFTER INSERT ON " + TABLE.DATA + + " WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + + " END"; + + /** + * Update note's content when data with {@link DataConstants#NOTE} type has changed + */ + private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER = + "CREATE TRIGGER update_note_content_on_update " + + " AFTER UPDATE ON " + TABLE.DATA + + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT + + " WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" + + " END"; + + /** + * Update note's content when data with {@link DataConstants#NOTE} type has deleted + */ + private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER = + "CREATE TRIGGER update_note_content_on_delete " + + " AFTER delete ON " + TABLE.DATA + + " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.SNIPPET + "=''" + + " WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" + + " END"; + + /** + * Delete datas belong to note which has been deleted + */ + private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = + "CREATE TRIGGER delete_data_on_delete " + + " AFTER DELETE ON " + TABLE.NOTE + + " BEGIN" + + " DELETE FROM " + TABLE.DATA + + " WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" + + " END"; + + /** + * Delete notes belong to folder which has been deleted + */ + private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER = + "CREATE TRIGGER folder_delete_notes_on_delete " + + " AFTER DELETE ON " + TABLE.NOTE + + " BEGIN" + + " DELETE FROM " + TABLE.NOTE + + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + + " END"; + + /** + * Move notes belong to folder which has been moved to trash folder + */ + private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER = + "CREATE TRIGGER folder_move_notes_on_trash " + + " AFTER UPDATE ON " + TABLE.NOTE + + " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + + " BEGIN" + + " UPDATE " + TABLE.NOTE + + " SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER + + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + + " END"; + + /** + * 构造函数 + */ + public NotesDatabaseHelper(Context context) { + super(context, DB_NAME, null, DB_VERSION); + } + /** + * 创建笔记表 + */ + public void createNoteTable(SQLiteDatabase db) { + db.execSQL(CREATE_NOTE_TABLE_SQL); + reCreateNoteTableTriggers(db); + createSystemFolder(db); + Log.d(TAG, "note table has been created"); + } + /** + * 重新创建笔记表相关的触发器 + */ + private void reCreateNoteTableTriggers(SQLiteDatabase db) { + db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update"); + db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update"); + db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS delete_data_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert"); + db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash"); + + db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); + db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); + db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER); + db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER); + db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER); + db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER); + db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER); + } + /** + * 创建系统文件夹 + */ + private void createSystemFolder(SQLiteDatabase db) { + ContentValues values = new ContentValues(); + + /** + * call record foler for call notes + */ + values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + /** + * root folder which is default folder + */ + values.clear(); + values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + /** + * temporary folder which is used for moving note + */ + values.clear(); + values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + + /** + * create trash folder + */ + values.clear(); + values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + } + + public void createDataTable(SQLiteDatabase db) { + db.execSQL(CREATE_DATA_TABLE_SQL); + reCreateDataTableTriggers(db); + db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); + Log.d(TAG, "data table has been created"); + } + /** + * 重新创建数据表相关的触发器 + */ + private void reCreateDataTableTriggers(SQLiteDatabase db) { + // 删除现有触发器 + db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete"); + // 重新创建触发器 + db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER); + db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER); + db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER); + } + + static synchronized NotesDatabaseHelper getInstance(Context context) { + if (mInstance == null) { + mInstance = new NotesDatabaseHelper(context); + } + return mInstance; + } + + @Override + public void onCreate(SQLiteDatabase db) { + // 创建数据库时调用,创建表和触发器 + createNoteTable(db); + createDataTable(db); + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + boolean reCreateTriggers = false; + boolean skipV2 = false; + // 从版本1升级到版本2 + if (oldVersion == 1) { + upgradeToV2(db); + skipV2 = true; // this upgrade including the upgrade from v2 to v3 + oldVersion++; + } + // 从版本2升级到版本3 + if (oldVersion == 2 && !skipV2) { + upgradeToV3(db); + reCreateTriggers = true; + oldVersion++; + } + // 从版本3升级到版本4 + if (oldVersion == 3) { + upgradeToV4(db); + oldVersion++; + } + // 如果需要,重新创建触发器 + if (reCreateTriggers) { + reCreateNoteTableTriggers(db); + reCreateDataTableTriggers(db); + } + // 检查版本升级是否成功 + if (oldVersion != newVersion) { + throw new IllegalStateException("Upgrade notes database to version " + newVersion + + "fails"); + } + } + + private void upgradeToV2(SQLiteDatabase db) { + db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); + db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); + createNoteTable(db); + createDataTable(db); + } + + private void upgradeToV3(SQLiteDatabase db) { + // drop unused triggers + db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete"); + db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update"); + // add a column for gtask id + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID + + " TEXT NOT NULL DEFAULT ''"); + // add a trash system folder + ContentValues values = new ContentValues(); + values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); + values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + db.insert(TABLE.NOTE, null, values); + } + + private void upgradeToV4(SQLiteDatabase db) { + db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION + + " INTEGER NOT NULL DEFAULT 0"); + } +} diff --git a/data/NotesProvider.java b/data/NotesProvider.java new file mode 100644 index 0000000..b814416 --- /dev/null +++ b/data/NotesProvider.java @@ -0,0 +1,372 @@ +/* + * 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.data; + + +import android.app.SearchManager; +import android.content.ContentProvider; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Intent; +import android.content.UriMatcher; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.net.Uri; +import android.text.TextUtils; +import android.util.Log; + +import net.micode.notes.R; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.NotesDatabaseHelper.TABLE; + +/** + * NotesProvider 是小米便签应用的内容提供者,负责管理便签数据的访问。 + * 它实现了对便签和便签数据的CRUD操作,并支持搜索功能。 + */ +public class NotesProvider extends ContentProvider { + private static final UriMatcher mMatcher; + + private NotesDatabaseHelper mHelper; + + private static final String TAG = "NotesProvider"; + + private static final int URI_NOTE = 1; // 匹配所有便签 + private static final int URI_NOTE_ITEM = 2; // 匹配单个便签 + private static final int URI_DATA = 3; // 匹配所有便签数据 + private static final int URI_DATA_ITEM = 4; // 匹配单个便签数据 + + private static final int URI_SEARCH = 5; // 匹配搜索请求 + private static final int URI_SEARCH_SUGGEST = 6; // 匹配搜索建议请求 + + static { + // 初始化URI匹配器,用于识别不同的URI请求 + mMatcher = new UriMatcher(UriMatcher.NO_MATCH); + mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); + mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); + mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); + mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); + mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); + mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST); + mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST); + } + + /** + * x'0A' represents the '\n' character in sqlite. For title and content in the search result, + * we will trim '\n' and white space in order to show more information. + */ + private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + "," + + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + "," + + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + "," + + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + "," + + R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + "," + + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," + + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; + // 便签搜索查询语句,用于搜索便签摘要中包含特定关键词的便签 + private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION + + " FROM " + TABLE.NOTE + + " WHERE " + NoteColumns.SNIPPET + " LIKE ?" + + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; + /** + * 初始化ContentProvider,创建数据库帮助类实例 + * @return 初始化成功返回true,否则返回false + */ + @Override + public boolean onCreate() { + mHelper = NotesDatabaseHelper.getInstance(getContext()); + return true; + } + + /** + * 查询便签数据 + * @param uri 查询的URI + * @param projection 返回的列 + * @param selection 选择条件 + * @param selectionArgs 选择条件参数 + * @param sortOrder 排序方式 + * @return 返回符合条件的Cursor + */ + @Override + public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, + String sortOrder) { + Cursor c = null; + SQLiteDatabase db = mHelper.getReadableDatabase(); + String id = null; + switch (mMatcher.match(uri)) { + case URI_NOTE: + // 查询所有便签 + c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, + sortOrder); + break; + case URI_NOTE_ITEM: + // 查询单个便签 + id = uri.getPathSegments().get(1); + c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id + + parseSelection(selection), selectionArgs, null, null, sortOrder); + break; + case URI_DATA: + // 查询所有便签数据 + c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, + sortOrder); + break; + case URI_DATA_ITEM: + // 查询单个便签数据 + id = uri.getPathSegments().get(1); + c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id + + parseSelection(selection), selectionArgs, null, null, sortOrder); + break; + case URI_SEARCH: + case URI_SEARCH_SUGGEST: + // 处理搜索请求 + if (sortOrder != null || projection != null) { + throw new IllegalArgumentException( + "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query"); + } + + String searchString = null; + if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { + if (uri.getPathSegments().size() > 1) { + searchString = uri.getPathSegments().get(1); + } + } else { + searchString = uri.getQueryParameter("pattern"); + } + + if (TextUtils.isEmpty(searchString)) { + return null; + } + + try { + // 执行搜索查询 + searchString = String.format("%%%s%%", searchString); + c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, + new String[] { searchString }); + } catch (IllegalStateException ex) { + Log.e(TAG, "got exception: " + ex.toString()); + } + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } +// 设置通知URI,当数据变化时通知观察者 + if (c != null) { + c.setNotificationUri(getContext().getContentResolver(), uri); + } + return c; + } + /** + * 插入新的便签或便签数据 + * @param uri 插入的URI + * @param values 要插入的数据 + * @return 返回插入后的URI + */ + @Override + public Uri insert(Uri uri, ContentValues values) { + SQLiteDatabase db = mHelper.getWritableDatabase(); + long dataId = 0, noteId = 0, insertedId = 0; + switch (mMatcher.match(uri)) { + case URI_NOTE: + // 插入新便签 + insertedId = noteId = db.insert(TABLE.NOTE, null, values); + break; + case URI_DATA: + // 插入新便签数据 + if (values.containsKey(DataColumns.NOTE_ID)) { + noteId = values.getAsLong(DataColumns.NOTE_ID); + } else { + Log.d(TAG, "Wrong data format without note id:" + values.toString()); + } + insertedId = dataId = db.insert(TABLE.DATA, null, values); + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } + // Notify the note uri + if (noteId > 0) { + getContext().getContentResolver().notifyChange( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); + } + + // Notify the data uri + if (dataId > 0) { + getContext().getContentResolver().notifyChange( + ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); + } + + return ContentUris.withAppendedId(uri, insertedId); + } + + /** + * 删除便签或便签数据 + * @param uri 删除的URI + * @param selection 选择条件 + * @param selectionArgs 选择条件参数 + * @return 返回删除的行数 + */ + @Override + public int delete(Uri uri, String selection, String[] selectionArgs) { + int count = 0; + String id = null; + SQLiteDatabase db = mHelper.getWritableDatabase(); + boolean deleteData = false; + switch (mMatcher.match(uri)) { + case URI_NOTE: + // 删除便签 + selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; + count = db.delete(TABLE.NOTE, selection, selectionArgs); + break; + case URI_NOTE_ITEM: + // 删除单个便签 + id = uri.getPathSegments().get(1); + /** + * ID that smaller than 0 is system folder which is not allowed to + * trash + */ + long noteId = Long.valueOf(id); + if (noteId <= 0) { + break; + } + count = db.delete(TABLE.NOTE, + NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs); + break; + case URI_DATA: + // 删除便签数据 + count = db.delete(TABLE.DATA, selection, selectionArgs); + deleteData = true; + break; + case URI_DATA_ITEM: + // 删除单个便签数据 + id = uri.getPathSegments().get(1); + count = db.delete(TABLE.DATA, + DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); + deleteData = true; + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } + // 通知数据变化 + if (count > 0) { + if (deleteData) { + getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); + } + getContext().getContentResolver().notifyChange(uri, null); + } + return count; + } + /** + * 更新便签或便签数据 + * @param uri 更新的URI + * @param values 要更新的数据 + * @param selection 选择条件 + * @param selectionArgs 选择条件参数 + * @return 返回更新的行数 + */ + @Override + public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { + int count = 0; + String id = null; + SQLiteDatabase db = mHelper.getWritableDatabase(); + boolean updateData = false; + switch (mMatcher.match(uri)) { + case URI_NOTE: + // 更新便签 + increaseNoteVersion(-1, selection, selectionArgs); + count = db.update(TABLE.NOTE, values, selection, selectionArgs); + break; + case URI_NOTE_ITEM: + // 更新单个便签 + id = uri.getPathSegments().get(1); + increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); + count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id + + parseSelection(selection), selectionArgs); + break; + case URI_DATA: + // 更新便签数据 + count = db.update(TABLE.DATA, values, selection, selectionArgs); + updateData = true; + break; + case URI_DATA_ITEM: + // 更新单个便签数据 + id = uri.getPathSegments().get(1); + count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id + + parseSelection(selection), selectionArgs); + updateData = true; + break; + default: + throw new IllegalArgumentException("Unknown URI " + uri); + } + // 通知数据变化 + if (count > 0) { + if (updateData) { + getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); + } + getContext().getContentResolver().notifyChange(uri, null); + } + return count; + } + /** + * 解析选择条件,添加额外的条件 + * @param selection 原始选择条件 + * @return 解析后的选择条件 + */ + private String parseSelection(String selection) { + return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); + } + /** + * 增加便签版本号,用于数据同步 + * @param id 便签ID,如果为-1则更新所有符合条件的便签 + * @param selection 选择条件 + * @param selectionArgs 选择条件参数 + */ + private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { + StringBuilder sql = new StringBuilder(120); + sql.append("UPDATE "); + sql.append(TABLE.NOTE); + sql.append(" SET "); + sql.append(NoteColumns.VERSION); + sql.append("=" + NoteColumns.VERSION + "+1 "); + + if (id > 0 || !TextUtils.isEmpty(selection)) { + sql.append(" WHERE "); + } + if (id > 0) { + sql.append(NoteColumns.ID + "=" + String.valueOf(id)); + } + if (!TextUtils.isEmpty(selection)) { + String selectString = id > 0 ? parseSelection(selection) : selection; + for (String args : selectionArgs) { + selectString = selectString.replaceFirst("\\?", args); + } + sql.append(selectString); + } + + mHelper.getWritableDatabase().execSQL(sql.toString()); + } + + /** + * 获取URI对应的MIME类型 + * @param uri 请求的URI + * @return 返回对应的MIME类型 + */ + @Override + public String getType(Uri uri) { + // TODO Auto-generated method stub + return null; + } + +} From 83876355523df230e02a300696b273ba2702009b Mon Sep 17 00:00:00 2001 From: hu <1515867307@qq.com> Date: Thu, 29 May 2025 15:36:18 +0800 Subject: [PATCH 3/3] explain --- gtask/data/MetaData.java | 113 +++++ gtask/data/Node.java | 133 ++++++ gtask/data/SqlData.java | 227 ++++++++++ gtask/data/SqlNote.java | 354 +++++++++++++++ gtask/data/Task.java | 395 ++++++++++++++++ gtask/data/TaskList.java | 445 +++++++++++++++++++ gtask/exception/ActionFailureException.java | 48 ++ gtask/exception/NetworkFailureException.java | 46 ++ gtask/remote/GTaskASyncTask.java | 169 +++++++ gtask/remote/GTaskClient.java | 430 ++++++++++++++++++ 10 files changed, 2360 insertions(+) create mode 100644 gtask/data/MetaData.java create mode 100644 gtask/data/Node.java create mode 100644 gtask/data/SqlData.java create mode 100644 gtask/data/SqlNote.java create mode 100644 gtask/data/Task.java create mode 100644 gtask/data/TaskList.java create mode 100644 gtask/exception/ActionFailureException.java create mode 100644 gtask/exception/NetworkFailureException.java create mode 100644 gtask/remote/GTaskASyncTask.java create mode 100644 gtask/remote/GTaskClient.java diff --git a/gtask/data/MetaData.java b/gtask/data/MetaData.java new file mode 100644 index 0000000..c2359e5 --- /dev/null +++ b/gtask/data/MetaData.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import android.database.Cursor; +import android.util.Log; + +import net.micode.notes.tool.GTaskStringUtils; + +import org.json.JSONException; +import org.json.JSONObject; + +/** + * 元数据实体类,继承自Task,用于存储与Google Tasks相关的元数据信息 + * 主要处理元数据的JSON解析、关联GID管理等逻辑 + */ +public class MetaData extends Task { + private final static String TAG = MetaData.class.getSimpleName(); + // 关联的Google Tasks的GID(全局唯一标识符) + private String mRelatedGid = null; + /** + * 设置元数据信息 + * @param gid 关联的Google Tasks的GID + * @param metaInfo 包含元数据的JSON对象 + */ + public void setMeta(String gid, JSONObject metaInfo) { + try { + // 在元数据JSON中添加GID头部信息 + metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); + } catch (JSONException e) { + Log.e(TAG, "failed to put related gid"); + } + // 将元数据JSON转为字符串存储到便签内容中 + setNotes(metaInfo.toString()); + // 设置元数据对应的便签名称(固定为预定义常量) + setName(GTaskStringUtils.META_NOTE_NAME); + } + /** + * 获取关联的Google Tasks的GID + * @return 关联的GID,若无则返回null + */ + public String getRelatedGid() { + return mRelatedGid; + } + /** + * 判断元数据是否值得保存(当前逻辑:只要便签内容不为空则值得保存) + * @return 便签内容不为null时返回true,否则false + */ + @Override + public boolean isWorthSaving() { + return getNotes() != null; + } + /** + * 从远程JSON数据中解析并设置元数据内容(供同步模块调用) + * @param js 包含远程数据的JSON对象 + */ + @Override + public void setContentByRemoteJSON(JSONObject js) { + super.setContentByRemoteJSON(js); // 先调用父类解析逻辑 + if (getNotes() != null) { + try { + // 解析便签内容中的元数据JSON + JSONObject metaInfo = new JSONObject(getNotes().trim()); + // 提取关联的GID + mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); + } catch (JSONException e) { + Log.w(TAG, "failed to get related gid"); + mRelatedGid = null; // 解析失败时清空GID + } + } + } + /** + * 本地JSON内容设置方法(禁止调用) + * @throws IllegalAccessError 始终抛出异常,表明该方法不允许使用 + */ + @Override + public void setContentByLocalJSON(JSONObject js) { + // this function should not be called + throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); + } + /** + * 获取本地JSON内容方法(禁止调用) + * @throws IllegalAccessError 始终抛出异常,表明该方法不允许使用 + */ + @Override + public JSONObject getLocalJSONFromContent() { + throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); + } + /** + * 获取同步操作类型(禁止调用) + * @param c 数据库游标(未使用) + * @throws IllegalAccessError 始终抛出异常,表明该方法不允许使用 + */ + @Override + public int getSyncAction(Cursor c) { + throw new IllegalAccessError("MetaData:getSyncAction should not be called"); + } + +} diff --git a/gtask/data/Node.java b/gtask/data/Node.java new file mode 100644 index 0000000..3aedcf5 --- /dev/null +++ b/gtask/data/Node.java @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import android.database.Cursor; + +import org.json.JSONObject; +/** + * 同步节点抽象类,定义同步操作的基础模型和行为 + * 用于表示Google Tasks中的任务、列表等实体的同步状态和数据 + */ +public abstract class Node { + // 同步操作类型常量定义 + public static final int SYNC_ACTION_NONE = 0;// 无操作 + + public static final int SYNC_ACTION_ADD_REMOTE = 1;// 远程添加 + + public static final int SYNC_ACTION_ADD_LOCAL = 2;// 本地添加 + + public static final int SYNC_ACTION_DEL_REMOTE = 3;// 远程删除 + + public static final int SYNC_ACTION_DEL_LOCAL = 4;// 本地删除 + + public static final int SYNC_ACTION_UPDATE_REMOTE = 5;// 远程更新 + + public static final int SYNC_ACTION_UPDATE_LOCAL = 6;// 本地更新 + + public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;// 更新冲突 + + public static final int SYNC_ACTION_ERROR = 8;// 操作错误 + // 节点核心属性 + private String mGid;// Google Tasks全局唯一标识符(GID + + private String mName;// 节点名称(如任务标题、列表名称) + + private long mLastModified;// 最后修改时间戳 + + private boolean mDeleted;// 是否已删除标记 + /** + * 构造方法,初始化节点默认状态 + */ + public Node() { + mGid = null; + mName = ""; + mLastModified = 0; + mDeleted = false; + } + + // ====================== 抽象方法(子类必须实现) ====================== + + /** + * 获取创建操作的JSON数据 + * @param actionId 操作ID,用于标识不同的创建场景 + * @return 包含创建操作的JSON对象 + */ + public abstract JSONObject getCreateAction(int actionId); + /** + * 获取更新操作的JSON数据 + * @param actionId 操作ID,用于标识不同的更新场景 + * @return 包含更新操作的JSON对象 + */ + public abstract JSONObject getUpdateAction(int actionId); + /** + * 从远程JSON数据中解析并设置节点内容(供同步模块调用) + * @param js 包含远程数据的JSON对象 + */ + public abstract void setContentByRemoteJSON(JSONObject js); + /** + * 从本地JSON数据中解析并设置节点内容(供本地存储模块调用) + * @param js 包含本地数据的JSON对象 + */ + public abstract void setContentByLocalJSON(JSONObject js); + /** + * 将节点内容转换为本地存储的JSON格式 + * @return 表示节点内容的JSON对象 + */ + public abstract JSONObject getLocalJSONFromContent(); + /** + * 获取节点的同步操作类型(根据数据库游标数据判断) + * @param c 包含节点数据的数据库游标 + * @return 同步操作类型常量(如SYNC_ACTION_ADD_LOCAL) + */ + public abstract int getSyncAction(Cursor c); + + // ====================== 基础属性访问方法 ====================== + + public void setGid(String gid) { + this.mGid = gid; + } + + public void setName(String name) { + this.mName = name; + } + + public void setLastModified(long lastModified) { + this.mLastModified = lastModified; + } + + public void setDeleted(boolean deleted) { + this.mDeleted = deleted; + } + + public String getGid() { + return this.mGid; + } + + public String getName() { + return this.mName; + } + + public long getLastModified() { + return this.mLastModified; + } + + public boolean getDeleted() { + return this.mDeleted; + } + +} diff --git a/gtask/data/SqlData.java b/gtask/data/SqlData.java new file mode 100644 index 0000000..99502fc --- /dev/null +++ b/gtask/data/SqlData.java @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import android.content.ContentResolver; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.NotesDatabaseHelper.TABLE; +import net.micode.notes.gtask.exception.ActionFailureException; + +import org.json.JSONException; +import org.json.JSONObject; + +/** + * 数据库数据操作类,用于处理便签数据在SQLite数据库中的CRUD操作 + * 提供与JSON数据格式的相互转换功能 + */ +public class SqlData { + private static final String TAG = SqlData.class.getSimpleName(); + + // 无效ID常量 + private static final int INVALID_ID = -99999; + + // 数据库查询字段投影 + public static final String[] PROJECTION_DATA = new String[] { + DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1, + DataColumns.DATA3 + }; + + // 字段索引常量 + public static final int DATA_ID_COLUMN = 0; // ID字段索引 + public static final int DATA_MIME_TYPE_COLUMN = 1; // MIME类型字段索引 + public static final int DATA_CONTENT_COLUMN = 2; // 内容字段索引 + public static final int DATA_CONTENT_DATA_1_COLUMN = 3; // DATA1字段索引 + public static final int DATA_CONTENT_DATA_3_COLUMN = 4; // DATA3字段索引 + + private ContentResolver mContentResolver; // 内容解析器,用于数据库操作 + private boolean mIsCreate; // 标记是否是新建数据 + private long mDataId; // 数据ID + private String mDataMimeType; // 数据类型(MIME类型) + private String mDataContent; // 数据内容 + private long mDataContentData1; // 数据扩展字段1 + private String mDataContentData3; // 数据扩展字段3 + private ContentValues mDiffDataValues; // 存储有变动的字段值 + + /** + * 构造函数 - 用于创建新数据 + * @param context 上下文对象 + */ + public SqlData(Context context) { + mContentResolver = context.getContentResolver(); + mIsCreate = true; // 标记为新数据 + mDataId = INVALID_ID; // 初始化为无效ID + mDataMimeType = DataConstants.NOTE; // 默认MIME类型为便签 + mDataContent = ""; // 内容初始化为空 + mDataContentData1 = 0; // 扩展字段1初始化为0 + mDataContentData3 = ""; // 扩展字段3初始化为空 + mDiffDataValues = new ContentValues(); // 初始化变动字段集合 + } + + /** + * 构造函数 - 从数据库游标加载已有数据 + * @param context 上下文对象 + * @param c 数据库游标 + */ + public SqlData(Context context, Cursor c) { + mContentResolver = context.getContentResolver(); + mIsCreate = false; // 标记为已有数据 + loadFromCursor(c); // 从游标加载数据 + mDiffDataValues = new ContentValues(); // 初始化变动字段集合 + } + + /** + * 从数据库游标加载数据 + * @param c 数据库游标 + */ + private void loadFromCursor(Cursor c) { + mDataId = c.getLong(DATA_ID_COLUMN); + mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); + mDataContent = c.getString(DATA_CONTENT_COLUMN); + mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN); + mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); + } + + /** + * 从JSON对象设置数据内容 + * @param js JSON对象 + * @throws JSONException JSON解析异常 + */ + public void setContent(JSONObject js) throws JSONException { + // 处理ID字段 + long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; + if (mIsCreate || mDataId != dataId) { + mDiffDataValues.put(DataColumns.ID, dataId); + } + mDataId = dataId; + + // 处理MIME类型字段 + String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE) + : DataConstants.NOTE; + if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { + mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); + } + mDataMimeType = dataMimeType; + + // 处理内容字段 + String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; + if (mIsCreate || !mDataContent.equals(dataContent)) { + mDiffDataValues.put(DataColumns.CONTENT, dataContent); + } + mDataContent = dataContent; + + // 处理DATA1字段 + long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; + if (mIsCreate || mDataContentData1 != dataContentData1) { + mDiffDataValues.put(DataColumns.DATA1, dataContentData1); + } + mDataContentData1 = dataContentData1; + + // 处理DATA3字段 + String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; + if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { + mDiffDataValues.put(DataColumns.DATA3, dataContentData3); + } + mDataContentData3 = dataContentData3; + } + + /** + * 将数据内容转换为JSON对象 + * @return JSON对象 + * @throws JSONException JSON转换异常 + */ + public JSONObject getContent() throws JSONException { + if (mIsCreate) { + Log.e(TAG, "数据尚未创建到数据库中"); + return null; + } + JSONObject js = new JSONObject(); + js.put(DataColumns.ID, mDataId); + js.put(DataColumns.MIME_TYPE, mDataMimeType); + js.put(DataColumns.CONTENT, mDataContent); + js.put(DataColumns.DATA1, mDataContentData1); + js.put(DataColumns.DATA3, mDataContentData3); + return js; + } + + /** + * 提交数据到数据库 + * @param noteId 关联的便签ID + * @param validateVersion 是否验证版本号 + * @param version 版本号 + */ + public void commit(long noteId, boolean validateVersion, long version) { + if (mIsCreate) { + // 处理新建数据的情况 + if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) { + mDiffDataValues.remove(DataColumns.ID); + } + + mDiffDataValues.put(DataColumns.NOTE_ID, noteId); + Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); + try { + // 从返回的URI中获取新创建的ID + mDataId = Long.valueOf(uri.getPathSegments().get(1)); + } catch (NumberFormatException e) { + Log.e(TAG, "获取便签ID错误:" + e.toString()); + throw new ActionFailureException("创建便签失败"); + } + } else { + // 处理更新已有数据的情况 + if (mDiffDataValues.size() > 0) { + int result = 0; + if (!validateVersion) { + // 不验证版本号的更新 + result = mContentResolver.update(ContentUris.withAppendedId( + Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); + } else { + // 需要验证版本号的更新 + result = mContentResolver.update(ContentUris.withAppendedId( + Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, + " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE + + " WHERE " + NoteColumns.VERSION + "=?)", new String[] { + String.valueOf(noteId), String.valueOf(version) + }); + } + if (result == 0) { + Log.w(TAG, "没有更新记录,可能在同步时用户已更新便签"); + } + } + } + + // 重置状态 + mDiffDataValues.clear(); + mIsCreate = false; + } + + /** + * 获取数据ID + * @return 数据ID + */ + public long getId() { + return mDataId; + } +} \ No newline at end of file diff --git a/gtask/data/SqlNote.java b/gtask/data/SqlNote.java new file mode 100644 index 0000000..05e94be --- /dev/null +++ b/gtask/data/SqlNote.java @@ -0,0 +1,354 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * 遵循 Apache 许可证 2.0 版("许可证"); + * 除非遵守许可证,否则不得使用此文件。 + * 您可以在以下网址获取许可证副本: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 除非适用法律要求或书面同意,否则根据许可证分发的软件是按"原样"提供的, + * 不附带任何明示或暗示的保证或条件。请参阅许可证,了解管理权限和限制的具体语言。 + */ + +package net.micode.notes.gtask.data; + +import android.appwidget.AppWidgetManager; +import android.content.ContentResolver; +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.tool.GTaskStringUtils; +import net.micode.notes.tool.ResourceParser; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; + + +/** + * 便签数据库操作类 + * 负责便签(Note)的数据库增删改查及 JSON 数据转换 + */ +public class SqlNote { + private static final String TAG = SqlNote.class.getSimpleName(); // 日志标签 + + private static final int INVALID_ID = -99999; // 无效 ID 标识 + + // 便签查询投影(指定查询的数据库字段) + public static final String[] PROJECTION_NOTE = new String[] { + NoteColumns.ID, // 便签 ID + NoteColumns.ALERTED_DATE, // 提醒时间 + NoteColumns.BG_COLOR_ID, // 背景颜色 ID + NoteColumns.CREATED_DATE, // 创建时间 + NoteColumns.HAS_ATTACHMENT, // 是否有附件(0/1) + NoteColumns.MODIFIED_DATE, // 修改时间 + NoteColumns.NOTES_COUNT, // 子便签数量(用于文件夹) + NoteColumns.PARENT_ID, // 父级 ID(用于层级结构) + NoteColumns.SNIPPET, // 便签摘要 + NoteColumns.TYPE, // 类型(普通便签、文件夹、系统文件夹等) + NoteColumns.WIDGET_ID, // 桌面小部件 ID + NoteColumns.WIDGET_TYPE, // 小部件类型 + NoteColumns.SYNC_ID, // 同步 ID(用于云同步) + NoteColumns.LOCAL_MODIFIED, // 本地修改标记(用于同步冲突检测) + NoteColumns.ORIGIN_PARENT_ID, // 原始父级 ID(可能用于同步历史记录) + NoteColumns.GTASK_ID, // Google Tasks ID(任务同步) + NoteColumns.VERSION // 版本号(用于乐观锁) + }; + + // 投影字段索引(方便通过索引访问字段值) + public static final int ID_COLUMN = 0; + public static final int ALERTED_DATE_COLUMN = 1; + public static final int BG_COLOR_ID_COLUMN = 2; + public static final int CREATED_DATE_COLUMN = 3; + public static final int HAS_ATTACHMENT_COLUMN = 4; + public static final int MODIFIED_DATE_COLUMN = 5; + public static final int NOTES_COUNT_COLUMN = 6; + public static final int PARENT_ID_COLUMN = 7; + public static final int SNIPPET_COLUMN = 8; + public static final int TYPE_COLUMN = 9; + public static final int WIDGET_ID_COLUMN = 10; + public static final int WIDGET_TYPE_COLUMN = 11; + public static final int SYNC_ID_COLUMN = 12; + public static final int LOCAL_MODIFIED_COLUMN = 13; + public static final int ORIGIN_PARENT_ID_COLUMN = 14; + public static final int GTASK_ID_COLUMN = 15; + public static final int VERSION_COLUMN = 16; + + private Context mContext; // 上下文(用于获取 ContentResolver) + private ContentResolver mContentResolver; // 内容解析器(操作数据库) + private boolean mIsCreate; // 是否为新建便签(未插入数据库) + private long mId; // 便签 ID + private long mAlertDate; // 提醒时间 + private int mBgColorId; // 背景颜色 ID(默认取系统默认值) + private long mCreatedDate; // 创建时间(默认当前时间) + private int mHasAttachment; // 是否有附件(默认无) + private long mModifiedDate; // 修改时间(默认当前时间) + private long mParentId; // 父级 ID(默认根目录) + private String mSnippet; // 便签摘要(默认空字符串) + private int mType; // 便签类型(默认普通便签) + private int mWidgetId; // 小部件 ID(默认无效 ID) + private int mWidgetType; // 小部件类型(默认无效类型) + private long mOriginParent; // 原始父级 ID(默认 0) + private long mVersion; // 版本号(用于数据版本控制) + private ContentValues mDiffNoteValues; // 待更新的字段值(增量更新) + private ArrayList mDataList; // 便签内容列表(普通便签包含文本、图片等子数据) + + /** + * 构造函数(新建便签) + * 初始化默认值,标记为新建状态 + */ + public SqlNote(Context context) { + mContext = context; + mContentResolver = context.getContentResolver(); + mIsCreate = true; // 标记为新建 + mId = INVALID_ID; // 初始 ID 无效 + mAlertDate = 0; // 无提醒时间 + // 获取默认背景颜色 ID(来自 ResourceParser 工具类) + mBgColorId = ResourceParser.getDefaultBgId(context); + mCreatedDate = System.currentTimeMillis(); // 创建时间为当前时间 + mHasAttachment = 0; // 初始无附件 + mModifiedDate = System.currentTimeMillis(); // 修改时间为当前时间 + mParentId = 0; // 父级默认为根目录 + mSnippet = ""; // 摘要为空 + mType = Notes.TYPE_NOTE; // 类型为普通便签 + // 小部件 ID 设为无效值(AppWidgetManager 定义) + mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; + mWidgetType = Notes.TYPE_WIDGET_INVALIDE; // 无效小部件类型 + mOriginParent = 0; // 原始父级默认 0 + mVersion = 0; // 版本号初始为 0 + mDiffNoteValues = new ContentValues(); // 初始化待更新字段集合 + mDataList = new ArrayList(); // 初始化内容列表 + } + + /** + * 构造函数(从 Cursor 加载已有便签) + * @param c 数据库查询结果 Cursor + */ + public SqlNote(Context context, Cursor c) { + mContext = context; + mContentResolver = context.getContentResolver(); + mIsCreate = false; // 标记为已存在 + loadFromCursor(c); // 从 Cursor 加载数据 + mDataList = new ArrayList(); // 初始化内容列表 + // 如果是普通便签,加载其子内容(文本、图片等) + if (mType == Notes.TYPE_NOTE) + loadDataContent(); + mDiffNoteValues = new ContentValues(); // 初始化待更新字段集合 + } + + /** + * 构造函数(通过 ID 加载便签) + * @param id 便签 ID + */ + public SqlNote(Context context, long id) { + mContext = context; + mContentResolver = context.getContentResolver(); + mIsCreate = false; // 标记为已存在 + loadFromCursor(id); // 通过 ID 从数据库加载数据 + mDataList = new ArrayList(); // 初始化内容列表 + // 如果是普通便签,加载其子内容 + if (mType == Notes.TYPE_NOTE) + loadDataContent(); + mDiffNoteValues = new ContentValues(); // 初始化待更新字段集合 + } + + /** + * 通过 ID 从数据库加载便签数据 + * @param id 便签 ID + */ + private void loadFromCursor(long id) { + Cursor c = null; + try { + // 查询便签表,条件为 ID 匹配 + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)", + new String[] { String.valueOf(id) }, null); + if (c != null) { + c.moveToNext(); // 移动到查询结果第一条(假设唯一) + loadFromCursor(c); // 从 Cursor 解析数据 + } else { + Log.w(TAG, "loadFromCursor: cursor = null"); // 日志:Cursor 为空 + } + } finally { + if (c != null) + c.close(); // 关闭 Cursor 释放资源 + } + } + + /** + * 从 Cursor 解析便签数据到对象属性 + * @param c 数据库查询结果 Cursor + */ + private void loadFromCursor(Cursor c) { + // 从 Cursor 中按投影索引获取字段值 + mId = c.getLong(ID_COLUMN); + mAlertDate = c.getLong(ALERTED_DATE_COLUMN); + mBgColorId = c.getInt(BG_COLOR_ID_COLUMN); + mCreatedDate = c.getLong(CREATED_DATE_COLUMN); + mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN); + mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN); + mParentId = c.getLong(PARENT_ID_COLUMN); + mSnippet = c.getString(SNIPPET_COLUMN); + mType = c.getInt(TYPE_COLUMN); + mWidgetId = c.getInt(WIDGET_ID_COLUMN); + mWidgetType = c.getInt(WIDGET_TYPE_COLUMN); + mVersion = c.getLong(VERSION_COLUMN); // 加载版本号用于乐观锁 + } + + /** + * 加载普通便签的子内容(如文本段落、图片等) + * 数据存储在独立的表中,通过 note_id 关联 + */ + private void loadDataContent() { + Cursor c = null; + mDataList.clear(); // 清空现有内容列表 + try { + // 查询便签内容表,条件为当前便签 ID + c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA, + "(note_id=?)", new String[] { String.valueOf(mId) }, null); + if (c != null) { + if (c.getCount() == 0) { + Log.w(TAG, "it seems that the note has not data"); // 日志:便签无内容 + return; + } + // 遍历 Cursor,创建 SqlData 对象并添加到列表 + while (c.moveToNext()) { + SqlData data = new SqlData(mContext, c); + mDataList.add(data); + } + } else { + Log.w(TAG, "loadDataContent: cursor = null"); // 日志:Cursor 为空 + } + } finally { + if (c != null) + c.close(); // 关闭 Cursor 释放资源 + } + } + + /** + * 从 JSON 对象设置便签内容(用于同步数据解析) + * @param js 包含便签数据的 JSON 对象 + * @return 是否解析成功 + */ + public boolean setContent(JSONObject js) { + try { + // 获取便签头部数据(note 节点) + JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + int type = note.getInt(NoteColumns.TYPE); + + // 系统文件夹不可修改 + if (type == Notes.TYPE_SYSTEM) { + Log.w(TAG, "cannot set system folder"); + return false; + } else if (type == Notes.TYPE_FOLDER) { // 文件夹类型 + // 文件夹仅支持更新摘要和类型 + String snippet = note.optString(NoteColumns.SNIPPET, ""); // 安全获取摘要 + if (mIsCreate || !mSnippet.equals(snippet)) { + // 记录待更新的摘要字段 + mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); + } + mSnippet = snippet; // 更新本地摘要 + + // 更新类型(如果有变化) + type = note.optInt(NoteColumns.TYPE, Notes.TYPE_NOTE); + if (mIsCreate || mType != type) { + mDiffNoteValues.put(NoteColumns.TYPE, type); + } + mType = type; // 更新本地类型 + } else if (type == Notes.TYPE_NOTE) { // 普通便签类型 + // 获取内容数组(data 节点) + JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); + + // 解析便签基础属性 + long id = note.optLong(NoteColumns.ID, INVALID_ID); // 安全获取 ID + if (mIsCreate || mId != id) { + mDiffNoteValues.put(NoteColumns.ID, id); // 新建时设置 ID + } + mId = id; // 更新本地 ID + + // 解析提醒时间 + long alertDate = note.optLong(NoteColumns.ALERTED_DATE, 0); + if (mIsCreate || mAlertDate != alertDate) { + mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate); + } + mAlertDate = alertDate; + + // 解析背景颜色 ID(默认系统默认值) + int bgColorId = note.optInt(NoteColumns.BG_COLOR_ID, + ResourceParser.getDefaultBgId(mContext)); + if (mIsCreate || mBgColorId != bgColorId) { + mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId); + } + mBgColorId = bgColorId; + + // 解析创建时间(默认当前时间) + long createDate = note.optLong(NoteColumns.CREATED_DATE, + System.currentTimeMillis()); + if (mIsCreate || mCreatedDate != createDate) { + mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate); + } + mCreatedDate = createDate; + + // 解析附件标记(默认无附件) + int hasAttachment = note.optInt(NoteColumns.HAS_ATTACHMENT, 0); + if (mIsCreate || mHasAttachment != hasAttachment) { + mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment); + } + mHasAttachment = hasAttachment; + + // 解析修改时间(默认当前时间) + long modifiedDate = note.optLong(NoteColumns.MODIFIED_DATE, + System.currentTimeMillis()); + if (mIsCreate || mModifiedDate != modifiedDate) { + mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate); + } + mModifiedDate = modifiedDate; + + // 解析父级 ID(默认根目录) + long parentId = note.optLong(NoteColumns.PARENT_ID, 0); + if (mIsCreate || mParentId != parentId) { + mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId); + } + mParentId = parentId; + + // 解析摘要(默认空字符串) + String snippet = note.optString(NoteColumns.SNIPPET, ""); + if (mIsCreate || !mSnippet.equals(snippet)) { + mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); + } + mSnippet = snippet; + + // 解析类型(默认普通便签) + type = note.optInt(NoteColumns.TYPE, Notes.TYPE_NOTE); + if (mIsCreate || mType != type) { + mDiffNoteValues.put(NoteColumns.TYPE, type); + } + mType = type; + + // 解析小部件 ID(默认无效 ID) + int widgetId = note.optInt(NoteColumns.WIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID); + if (mIsCreate || mWidgetId != widgetId) { + mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId); + } + mWidgetId = widgetId; + + // 解析小部件类型(默认无效类型) + int widgetType = note.optInt(NoteColumns.WIDGET_TYPE, + Notes.TYPE_WIDGET_INVALIDE); + if (mIsCreate || mWidgetType != widgetType) { + mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType); + } + mWidgetType = widgetType; + + // 解析原始父级 ID(默认 0) + long originParent = note.optLong(NoteColumns.ORIGIN_PARENT_ID, \ No newline at end of file diff --git a/gtask/data/Task.java b/gtask/data/Task.java new file mode 100644 index 0000000..ca68514 --- /dev/null +++ b/gtask/data/Task.java @@ -0,0 +1,395 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.data; + +import android.database.Cursor; +import android.text.TextUtils; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.tool.GTaskStringUtils; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * 任务类,继承自Node基类,表示Google任务中的一个具体任务 + * 处理任务的创建、更新、同步以及与本地数据库的交互 + */ +public class Task extends Node { + private static final String TAG = Task.class.getSimpleName(); + + private boolean mCompleted; // 任务是否已完成 + private String mNotes; // 任务备注内容 + private JSONObject mMetaInfo; // 元数据信息(存储本地笔记相关信息) + private Task mPriorSibling; // 前一个兄弟任务(用于排序) + private TaskList mParent; // 父任务列表 + + /** + * 构造函数,初始化任务对象 + */ + public Task() { + super(); + mCompleted = false; + mNotes = null; + mPriorSibling = null; + mParent = null; + mMetaInfo = null; + } + + /** + * 生成创建任务的JSON对象 + * @param actionId 动作ID + * @return 包含创建任务所需数据的JSON对象 + */ + public JSONObject getCreateAction(int actionId) { + JSONObject js = new JSONObject(); + + try { + // 设置动作类型为创建 + js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); + + // 设置动作ID + js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); + + // 设置任务在父列表中的索引位置 + js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this)); + + // 构建任务实体数据 + JSONObject entity = new JSONObject(); + entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 任务名称 + entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); + entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, + GTaskStringUtils.GTASK_JSON_TYPE_TASK); // 实体类型为任务 + if (getNotes() != null) { + entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); // 任务备注 + } + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + + // 设置父任务列表ID + js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); + + // 设置父类型为组 + js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE, + GTaskStringUtils.GTASK_JSON_TYPE_GROUP); + + // 设置列表ID + js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); + + // 设置前一个兄弟任务ID(用于排序) + if (mPriorSibling != null) { + js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid()); + } + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("生成任务创建JSON对象失败"); + } + + return js; + } + + /** + * 生成更新任务的JSON对象 + * @param actionId 动作ID + * @return 包含更新任务所需数据的JSON对象 + */ + public JSONObject getUpdateAction(int actionId) { + JSONObject js = new JSONObject(); + + try { + // 设置动作类型为更新 + js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); + + // 设置动作ID + js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); + + // 设置任务ID + js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); + + // 构建任务更新数据 + JSONObject entity = new JSONObject(); + entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 更新任务名称 + if (getNotes() != null) { + entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); // 更新任务备注 + } + entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); // 更新删除状态 + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("生成任务更新JSON对象失败"); + } + + return js; + } + + /** + * 从远程JSON数据设置任务内容 + * @param js 包含远程任务数据的JSON对象 + */ + public void setContentByRemoteJSON(JSONObject js) { + if (js != null) { + try { + // 设置任务ID + if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { + setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); + } + + // 设置最后修改时间 + if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { + setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); + } + + // 设置任务名称 + if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { + setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); + } + + // 设置任务备注 + if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) { + setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES)); + } + + // 设置删除状态 + if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) { + setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED)); + } + + // 设置完成状态 + if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) { + setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED)); + } + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("从JSON对象获取任务内容失败"); + } + } + } + + /** + * 从本地JSON数据设置任务内容 + * @param js 包含本地任务数据的JSON对象 + */ + public void setContentByLocalJSON(JSONObject js) { + if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) + || !js.has(GTaskStringUtils.META_HEAD_DATA)) { + Log.w(TAG, "setContentByLocalJSON: 无可用数据"); + } + + try { + JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); + + // 验证笔记类型 + if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { + Log.e(TAG, "无效的类型"); + return; + } + + // 从数据数组中获取笔记内容 + for (int i = 0; i < dataArray.length(); i++) { + JSONObject data = dataArray.getJSONObject(i); + if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { + setName(data.getString(DataColumns.CONTENT)); // 设置任务名称 + break; + } + } + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + } + + /** + * 从任务内容生成本地JSON数据 + * @return 包含本地任务数据的JSON对象 + */ + public JSONObject getLocalJSONFromContent() { + String name = getName(); + try { + if (mMetaInfo == null) { + // 从网页创建的新任务 + if (name == null) { + Log.w(TAG, "笔记内容为空"); + return null; + } + + // 构建新的JSON结构 + JSONObject js = new JSONObject(); + JSONObject note = new JSONObject(); + JSONArray dataArray = new JSONArray(); + JSONObject data = new JSONObject(); + data.put(DataColumns.CONTENT, name); // 设置笔记内容 + dataArray.put(data); + js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); // 数据部分 + note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); // 设置笔记类型 + js.put(GTaskStringUtils.META_HEAD_NOTE, note); // 笔记元信息 + return js; + } else { + // 已同步的任务 + JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); + + // 更新笔记内容 + for (int i = 0; i < dataArray.length(); i++) { + JSONObject data = dataArray.getJSONObject(i); + if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { + data.put(DataColumns.CONTENT, getName()); + break; + } + } + + note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); + return mMetaInfo; + } + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return null; + } + } + + /** + * 设置元数据信息 + * @param metaData 元数据对象 + */ + public void setMetaInfo(MetaData metaData) { + if (metaData != null && metaData.getNotes() != null) { + try { + mMetaInfo = new JSONObject(metaData.getNotes()); // 从备注解析元数据 + } catch (JSONException e) { + Log.w(TAG, e.toString()); + mMetaInfo = null; + } + } + } + + /** + * 获取同步动作类型 + * @param c 数据库游标 + * @return 同步动作类型常量 + */ + public int getSyncAction(Cursor c) { + try { + JSONObject noteInfo = null; + if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { + noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + } + + if (noteInfo == null) { + Log.w(TAG, "笔记元数据似乎已被删除"); + return SYNC_ACTION_UPDATE_REMOTE; // 需要更新远程 + } + + if (!noteInfo.has(NoteColumns.ID)) { + Log.w(TAG, "远程笔记ID似乎已被删除"); + return SYNC_ACTION_UPDATE_LOCAL; // 需要更新本地 + } + + // 验证笔记ID是否匹配 + if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { + Log.w(TAG, "笔记ID不匹配"); + return SYNC_ACTION_UPDATE_LOCAL; + } + + // 检查本地修改状态 + if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { + // 本地无更新 + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { + // 两边都无更新 + return SYNC_ACTION_NONE; + } else { + // 将远程更新应用到本地 + return SYNC_ACTION_UPDATE_LOCAL; + } + } else { + // 验证任务ID + if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { + Log.e(TAG, "任务ID不匹配"); + return SYNC_ACTION_ERROR; + } + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { + // 只有本地修改 + return SYNC_ACTION_UPDATE_REMOTE; + } else { + // 冲突情况 + return SYNC_ACTION_UPDATE_CONFLICT; + } + } + } catch (Exception e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + + return SYNC_ACTION_ERROR; + } + + /** + * 检查任务是否值得保存 + * @return 如果有有效内容则返回true,否则返回false + */ + public boolean isWorthSaving() { + return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) + || (getNotes() != null && getNotes().trim().length() > 0); + } + + // 以下是getter和setter方法 + + public void setCompleted(boolean completed) { + this.mCompleted = completed; + } + + public void setNotes(String notes) { + this.mNotes = notes; + } + + public void setPriorSibling(Task priorSibling) { + this.mPriorSibling = priorSibling; + } + + public void setParent(TaskList parent) { + this.mParent = parent; + } + + public boolean getCompleted() { + return this.mCompleted; + } + + public String getNotes() { + return this.mNotes; + } + + public Task getPriorSibling() { + return this.mPriorSibling; + } + + public TaskList getParent() { + return this.mParent; + } +} \ No newline at end of file diff --git a/gtask/data/TaskList.java b/gtask/data/TaskList.java new file mode 100644 index 0000000..1d452f3 --- /dev/null +++ b/gtask/data/TaskList.java @@ -0,0 +1,445 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * 遵循 Apache 许可证 2.0 版("许可证"); + * 除非遵守许可证,否则不得使用此文件。 + * 您可以在以下网址获取许可证副本: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 除非适用法律要求或书面同意,否则根据许可证分发的软件是按"原样"提供的, + * 不附带任何明示或暗示的保证或条件。请参阅许可证,了解管理权限和限制的具体语言。 + */ + +package net.micode.notes.gtask.data; + +import android.database.Cursor; +import android.util.Log; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.tool.GTaskStringUtils; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; + + +/** + * 任务列表类(对应 Google Tasks 中的任务列表概念) + * 负责管理一组相关的任务,并与云端同步 + */ +public class TaskList extends Node { + private static final String TAG = TaskList.class.getSimpleName(); + + private int mIndex; // 任务列表在同步队列中的索引位置 + private ArrayList mChildren; // 子任务列表 + + /** + * 构造函数 + */ + public TaskList() { + super(); // 调用父类构造函数 + mChildren = new ArrayList(); // 初始化子任务列表 + mIndex = 1; // 默认索引为 1 + } + + /** + * 生成创建任务列表的 JSON 操作对象 + * @param actionId 操作 ID(用于标识同步操作) + * @return JSON 格式的创建操作 + */ + public JSONObject getCreateAction(int actionId) { + JSONObject js = new JSONObject(); + + try { + // 设置操作类型为创建任务列表 + js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); + + // 设置操作 ID + js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); + + // 设置任务列表索引 + js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex); + + // 设置实体变更内容 + JSONObject entity = new JSONObject(); + entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 任务列表名称 + entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); // 创建者 ID + entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, + GTaskStringUtils.GTASK_JSON_TYPE_GROUP); // 实体类型为组 + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to generate tasklist-create jsonobject"); + } + + return js; + } + + /** + * 生成更新任务列表的 JSON 操作对象 + * @param actionId 操作 ID + * @return JSON 格式的更新操作 + */ + public JSONObject getUpdateAction(int actionId) { + JSONObject js = new JSONObject(); + + try { + // 设置操作类型为更新任务列表 + js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); + + // 设置操作 ID + js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); + + // 设置任务列表 ID + js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); + + // 设置实体变更内容 + JSONObject entity = new JSONObject(); + entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); // 任务列表名称 + entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); // 是否删除 + js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to generate tasklist-update jsonobject"); + } + + return js; + } + + /** + * 从远程 JSON 数据设置任务列表内容(用于同步) + * @param js 包含任务列表数据的 JSON 对象 + */ + public void setContentByRemoteJSON(JSONObject js) { + if (js != null) { + try { + // 设置任务列表 ID + if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { + setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); + } + + // 设置最后修改时间 + if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { + setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); + } + + // 设置任务列表名称 + if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { + setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); + } + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("fail to get tasklist content from jsonobject"); + } + } + } + + /** + * 从本地 JSON 数据设置任务列表内容 + * @param js 包含本地便签数据的 JSON 对象 + */ + public void setContentByLocalJSON(JSONObject js) { + if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) { + Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); + } + + try { + JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); + + if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { + // 普通文件夹类型 + String name = folder.getString(NoteColumns.SNIPPET); + // 添加小米便签前缀标识 + setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name); + } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { + // 系统文件夹类型 + if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER) + // 根文件夹命名 + setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT); + else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER) + // 通话记录文件夹命名 + setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + + GTaskStringUtils.FOLDER_CALL_NOTE); + else + Log.e(TAG, "invalid system folder"); // 无效系统文件夹类型 + } else { + Log.e(TAG, "error type"); // 错误类型 + } + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + } + + /** + * 将任务列表内容转换为本地 JSON 格式 + * @return 本地 JSON 格式的任务列表数据 + */ + public JSONObject getLocalJSONFromContent() { + try { + JSONObject js = new JSONObject(); + JSONObject folder = new JSONObject(); + + // 处理任务列表名称(去除可能的前缀) + String folderName = getName(); + if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) + folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), + folderName.length()); + + // 设置文件夹摘要(即任务列表名称) + folder.put(NoteColumns.SNIPPET, folderName); + + // 根据名称判断文件夹类型(系统文件夹或普通文件夹) + if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT) + || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE)) + folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); + else + folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); + + // 将文件夹数据放入主 JSON 对象 + js.put(GTaskStringUtils.META_HEAD_NOTE, folder); + + return js; + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return null; + } + } + + /** + * 判断同步操作类型(本地与远程数据对比) + * @param c 包含本地数据的 Cursor + * @return 同步操作类型(SYNC_ACTION_NONE-无操作,SYNC_ACTION_UPDATE_LOCAL-更新本地,SYNC_ACTION_UPDATE_REMOTE-更新远程) + */ + public int getSyncAction(Cursor c) { + try { + if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { + // 本地没有修改 + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { + // 本地和远程都没有更新 + return SYNC_ACTION_NONE; + } else { + // 应用远程数据到本地 + return SYNC_ACTION_UPDATE_LOCAL; + } + } else { + // 本地有修改 + // 验证 Google Tasks ID 是否匹配 + if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { + Log.e(TAG, "gtask id doesn't match"); + return SYNC_ACTION_ERROR; + } + + if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { + // 只有本地修改 + return SYNC_ACTION_UPDATE_REMOTE; + } else { + // 文件夹冲突时,默认应用本地修改 + return SYNC_ACTION_UPDATE_REMOTE; + } + } + } catch (Exception e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + } + + return SYNC_ACTION_ERROR; + } + + /** + * 获取子任务数量 + * @return 子任务数量 + */ + public int getChildTaskCount() { + return mChildren.size(); + } + + /** + * 添加子任务到任务列表末尾 + * @param task 要添加的任务 + * @return 是否添加成功 + */ + public boolean addChildTask(Task task) { + boolean ret = false; + if (task != null && !mChildren.contains(task)) { + ret = mChildren.add(task); + if (ret) { + // 设置任务的前置兄弟任务和父任务列表 + task.setPriorSibling(mChildren.isEmpty() ? null : mChildren + .get(mChildren.size() - 1)); + task.setParent(this); + } + } + return ret; + } + + /** + * 在指定位置添加子任务 + * @param task 要添加的任务 + * @param index 指定位置索引 + * @return 是否添加成功 + */ + public boolean addChildTask(Task task, int index) { + if (index < 0 || index > mChildren.size()) { + Log.e(TAG, "add child task: invalid index"); + return false; + } + + int pos = mChildren.indexOf(task); + if (task != null && pos == -1) { + mChildren.add(index, task); + + // 更新任务列表中的前置兄弟关系 + Task preTask = null; + Task afterTask = null; + if (index != 0) + preTask = mChildren.get(index - 1); + if (index != mChildren.size() - 1) + afterTask = mChildren.get(index + 1); + + task.setPriorSibling(preTask); + if (afterTask != null) + afterTask.setPriorSibling(task); + } + + return true; + } + + /** + * 移除子任务 + * @param task 要移除的任务 + * @return 是否移除成功 + */ + public boolean removeChildTask(Task task) { + boolean ret = false; + int index = mChildren.indexOf(task); + if (index != -1) { + ret = mChildren.remove(task); + + if (ret) { + // 重置任务的前置兄弟和父任务列表 + task.setPriorSibling(null); + task.setParent(null); + + // 更新任务列表中的前置兄弟关系 + if (index != mChildren.size()) { + mChildren.get(index).setPriorSibling( + index == 0 ? null : mChildren.get(index - 1)); + } + } + } + return ret; + } + + /** + * 移动子任务到指定位置 + * @param task 要移动的任务 + * @param index 目标位置索引 + * @return 是否移动成功 + */ + public boolean moveChildTask(Task task, int index) { + if (index < 0 || index >= mChildren.size()) { + Log.e(TAG, "move child task: invalid index"); + return false; + } + + int pos = mChildren.indexOf(task); + if (pos == -1) { + Log.e(TAG, "move child task: the task should in the list"); + return false; + } + + if (pos == index) + return true; + + // 先移除再添加实现移动 + return (removeChildTask(task) && addChildTask(task, index)); + } + + /** + * 根据 Google Tasks ID 查找子任务 + * @param gid 任务的 Google Tasks ID + * @return 找到的任务,未找到则返回 null + */ + public Task findChildTaskByGid(String gid) { + for (int i = 0; i < mChildren.size(); i++) { + Task t = mChildren.get(i); + if (t.getGid().equals(gid)) { + return t; + } + } + return null; + } + + /** + * 获取子任务在列表中的索引位置 + * @param task 要查找的任务 + * @return 任务的索引位置,未找到返回 -1 + */ + public int getChildTaskIndex(Task task) { + return mChildren.indexOf(task); + } + + /** + * 根据索引获取子任务 + * @param index 索引位置 + * @return 指定位置的任务,索引无效则返回 null + */ + public Task getChildTaskByIndex(int index) { + if (index < 0 || index >= mChildren.size()) { + Log.e(TAG, "getTaskByIndex: invalid index"); + return null; + } + return mChildren.get(index); + } + + /** + * 根据 Google Tasks ID 获取子任务 + * @param gid 任务的 Google Tasks ID + * @return 找到的任务,未找到则返回 null + */ + public Task getChilTaskByGid(String gid) { + for (Task task : mChildren) { + if (task.getGid().equals(gid)) + return task; + } + return null; + } + + /** + * 获取所有子任务列表 + * @return 子任务列表 + */ + public ArrayList getChildTaskList() { + return this.mChildren; + } + + /** + * 设置任务列表在同步队列中的索引 + * @param index 索引值 + */ + public void setIndex(int index) { + this.mIndex = index; + } + + /** + * 获取任务列表在同步队列中的索引 + * @return 索引值 + */ + public int getIndex() { + return this.mIndex; + } +} \ No newline at end of file diff --git a/gtask/exception/ActionFailureException.java b/gtask/exception/ActionFailureException.java new file mode 100644 index 0000000..5598d37 --- /dev/null +++ b/gtask/exception/ActionFailureException.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * 遵循 Apache 许可证 2.0 版("许可证"); + * 除非遵守许可证,否则不得使用此文件。 + * 您可以在以下网址获取许可证副本: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 除非适用法律要求或书面同意,否则根据许可证分发的软件是按"原样"提供的, + * 不附带任何明示或暗示的保证或条件。请参阅许可证,了解管理权限和限制的具体语言。 + */ + +package net.micode.notes.gtask.exception; + +/** + * 操作失败异常类(运行时异常) + * 用于标识业务操作执行失败的场景(如数据解析失败、同步操作失败等) + */ +public class ActionFailureException extends RuntimeException { + private static final long serialVersionUID = 4425249765923293627L; // 序列化版本号,用于兼容反序列化 + + /** + * 无参构造函数 + * 创建一个默认的操作失败异常 + */ + public ActionFailureException() { + super(); // 调用父类(RuntimeException)的无参构造 + } + + /** + * 带错误消息的构造函数 + * @param paramString 异常消息,描述具体失败原因(如"生成任务列表 JSON 失败") + */ + public ActionFailureException(String paramString) { + super(paramString); // 调用父类带消息的构造函数,便于日志记录和问题定位 + } + + /** + * 带错误消息和根源异常的构造函数 + * @param paramString 异常消息,描述表面失败原因 + * @param paramThrowable 根源异常(导致当前异常的原始异常),如 JSON 解析异常 + * 用于保留完整的异常栈信息,方便排查底层问题 + */ + public ActionFailureException(String paramString, Throwable paramThrowable) { + super(paramString, paramThrowable); // 调用父类带消息和 Throwable 的构造函数 + } +} \ No newline at end of file diff --git a/gtask/exception/NetworkFailureException.java b/gtask/exception/NetworkFailureException.java new file mode 100644 index 0000000..39339a4 --- /dev/null +++ b/gtask/exception/NetworkFailureException.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * 遵循 Apache 许可证 2.0 版("许可证"); + * 除非遵守许可证,否则不得使用此文件。 + * 您可以在以下网址获取许可证副本: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 除非适用法律要求或书面同意,否则根据许可证分发的软件是按"原样"提供的, + * 不附带任何明示或暗示的保证或条件。请参阅许可证,了解管理权限和限制的具体语言。 + */ + +package net.micode.notes.gtask.exception; + +/** + * 网络失败异常类 + * 用于标识与网络请求相关的异常(如连接失败、超时等) + */ +public class NetworkFailureException extends Exception { + private static final long serialVersionUID = 2107610287180234136L; // 序列化版本号 + + /** + * 无参构造函数 + */ + public NetworkFailureException() { + super(); // 调用父类(Exception)的无参构造 + } + + /** + * 带错误消息的构造函数 + * @param paramString 异常消息 + */ + public NetworkFailureException(String paramString) { + super(paramString); // 调用父类带消息的构造函数 + } + + /** + * 带错误消息和根源异常的构造函数 + * @param paramString 异常消息 + * @param paramThrowable 根源异常(导致当前异常的原始异常) + */ + public NetworkFailureException(String paramString, Throwable paramThrowable) { + super(paramString, paramThrowable); // 调用父类带消息和 Throwable 的构造函数 + } +} \ No newline at end of file diff --git a/gtask/remote/GTaskASyncTask.java b/gtask/remote/GTaskASyncTask.java new file mode 100644 index 0000000..788ee9c --- /dev/null +++ b/gtask/remote/GTaskASyncTask.java @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * 遵循 Apache 许可证 2.0 版("许可证"); + * 除非遵守许可证,否则不得使用此文件。 + * 您可以在以下网址获取许可证副本: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 除非适用法律要求或书面同意,否则根据许可证分发的软件是按"原样"提供的, + * 不附带任何明示或暗示的保证或条件。请参阅许可证,了解管理权限和限制的具体语言。 + */ + +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; + +/** + * Google Tasks 同步的异步任务类 + * 负责在后台执行与 Google Tasks 的同步操作,并通过通知栏显示进度和结果 + */ +public class GTaskASyncTask extends AsyncTask { + + private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; // 同步通知的唯一标识符 + + /** + * 同步完成监听器接口 + * 用于在同步任务完成后回调通知调用者 + */ + public interface OnCompleteListener { + void onComplete(); // 同步完成时调用的方法 + } + + private Context mContext; // 应用上下文 + private NotificationManager mNotifiManager; // 通知管理器 + private GTaskManager mTaskManager; // Google Tasks 管理类实例 + private OnCompleteListener mOnCompleteListener; // 同步完成监听器 + + /** + * 构造函数 + * @param context 应用上下文 + * @param listener 同步完成监听器 + */ + public GTaskASyncTask(Context context, OnCompleteListener listener) { + mContext = context; + mOnCompleteListener = listener; + // 获取系统通知服务 + mNotifiManager = (NotificationManager) mContext + .getSystemService(Context.NOTIFICATION_SERVICE); + mTaskManager = GTaskManager.getInstance(); // 获取单例的任务管理器 + } + + /** + * 取消同步操作 + */ + public void cancelSync() { + mTaskManager.cancelSync(); // 调用任务管理器的取消同步方法 + } + + /** + * 发布同步进度 + * @param message 进度消息 + */ + public void publishProgess(String message) { + publishProgress(new String[] { message }); // 调用 AsyncTask 的进度发布方法 + } + + /** + * 显示通知栏消息 + * @param tickerId 通知提示文本的资源 ID + * @param content 通知内容 + */ + private void showNotification(int tickerId, String content) { + // 创建通知对象,设置图标、提示文本和时间戳 + Notification notification = new Notification(R.drawable.notification, mContext + .getString(tickerId), System.currentTimeMillis()); + notification.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); + } + + /** + * 后台执行的同步操作 + * @param unused 不使用的参数 + * @return 同步结果状态码 + */ + @Override + protected Integer doInBackground(Void... unused) { + // 发布登录进度 + publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity + .getSyncAccountName(mContext))); + // 调用任务管理器的同步方法并返回结果 + return mTaskManager.sync(mContext, this); + } + + /** + * 处理进度更新 + * @param progress 进度消息数组 + */ + @Override + protected void onProgressUpdate(String... progress) { + // 显示同步中的通知 + showNotification(R.string.ticker_syncing, progress[0]); + // 如果上下文是 GTaskSyncService,发送广播通知进度 + if (mContext instanceof GTaskSyncService) { + ((GTaskSyncService) mContext).sendBroadcast(progress[0]); + } + } + + /** + * 同步完成后的处理 + * @param result 同步结果状态码 + */ + @Override + protected void onPostExecute(Integer result) { + // 根据同步结果显示不同的通知 + if (result == GTaskManager.STATE_SUCCESS) { + // 同步成功 + showNotification(R.string.ticker_success, mContext.getString( + R.string.success_sync_account, mTaskManager.getSyncAccount())); + // 记录最后同步时间 + NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); + } else if (result == GTaskManager.STATE_NETWORK_ERROR) { + // 网络错误 + showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network)); + } else if (result == GTaskManager.STATE_INTERNAL_ERROR) { + // 内部错误 + showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal)); + } else if (result == GTaskManager.STATE_SYNC_CANCELLED) { + // 同步取消 + showNotification(R.string.ticker_cancel, mContext + .getString(R.string.error_sync_cancelled)); + } + + // 如果设置了完成监听器,则在线程池中执行回调 + if (mOnCompleteListener != null) { + new Thread(new Runnable() { + public void run() { + mOnCompleteListener.onComplete(); + } + }).start(); + } + } +} \ No newline at end of file diff --git a/gtask/remote/GTaskClient.java b/gtask/remote/GTaskClient.java new file mode 100644 index 0000000..28fb976 --- /dev/null +++ b/gtask/remote/GTaskClient.java @@ -0,0 +1,430 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * 遵循 Apache 许可证 2.0 版("许可证"); + * 除非遵守许可证,否则不得使用此文件。 + * 您可以在以下网址获取许可证副本: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 除非适用法律要求或书面同意,否则根据许可证分发的软件是按"原样"提供的, + * 不附带任何明示或暗示的保证或条件。请参阅许可证,了解管理权限和限制的具体语言。 + */ + +package net.micode.notes.gtask.remote; + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.accounts.AccountManagerFuture; +import android.app.Activity; +import android.os.Bundle; +import android.text.TextUtils; +import android.util.Log; + +import net.micode.notes.gtask.data.Node; +import net.micode.notes.gtask.data.Task; +import net.micode.notes.gtask.data.TaskList; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.gtask.exception.NetworkFailureException; +import net.micode.notes.tool.GTaskStringUtils; +import net.micode.notes.ui.NotesPreferenceActivity; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.cookie.Cookie; +import org.apache.http.impl.client.BasicCookieStore; +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; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.LinkedList; +import java.util.List; +import java.util.zip.GZIPInputStream; +import java.util.zip.Inflater; +import java.util.zip.InflaterInputStream; + + +/** + * Google Tasks 客户端类 + * 负责与 Google Tasks 服务进行网络通信,实现任务和任务列表的增删改查及同步 + */ +public class GTaskClient { + private static final String TAG = GTaskClient.class.getSimpleName(); + + 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"; // GET 请求 URL(获取数据) + private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; // POST 请求 URL(提交操作) + + private static GTaskClient mInstance = null; // 单例实例 + + private DefaultHttpClient mHttpClient; // HTTP 客户端 + private String mGetUrl; // 当前 GET 请求 URL(支持自定义域名) + private String mPostUrl; // 当前 POST 请求 URL(支持自定义域名) + private long mClientVersion; // Google Tasks 客户端版本号(用于协议兼容) + private boolean mLoggedin; // 登录状态 + private long mLastLoginTime; // 最后登录时间(用于超时管理) + private int mActionId; // 操作 ID 生成器(保证每次请求唯一) + private Account mAccount; // 当前同步的 Google 账号 + private JSONArray mUpdateArray; // 待提交的批量更新操作列表 + + /** + * 构造函数(私有化,单例模式) + */ + private GTaskClient() { + mHttpClient = null; + mGetUrl = GTASK_GET_URL; + mPostUrl = GTASK_POST_URL; + mClientVersion = -1; // 初始版本号无效 + mLoggedin = false; // 初始未登录 + mLastLoginTime = 0; // 初始无登录时间 + mActionId = 1; // 操作 ID 从 1 开始 + mAccount = null; // 初始无账号 + mUpdateArray = null; // 初始无待更新操作 + } + + /** + * 获取单例实例 + * @return GTaskClient 实例 + */ + public static synchronized GTaskClient getInstance() { + if (mInstance == null) { + mInstance = new GTaskClient(); + } + return mInstance; + } + + /** + * 登录 Google 账号并初始化 Tasks 客户端 + * @param activity 调用登录的 Activity(用于获取账号令牌) + * @return 是否登录成功 + */ + public boolean login(Activity activity) { + // 登录状态检查:超过 5 分钟或账号变更则重新登录 + final long interval = 1000 * 60 * 5; // 5 分钟超时时间 + if (mLastLoginTime + interval < System.currentTimeMillis()) { + mLoggedin = false; + } + if (mLoggedin && !TextUtils.equals(getSyncAccount().name, + NotesPreferenceActivity.getSyncAccountName(activity))) { + mLoggedin = false; + } + + if (mLoggedin) { + Log.d(TAG, "already logged in"); + return true; // 已登录且账号有效,直接返回 + } + + mLastLoginTime = System.currentTimeMillis(); // 更新最后登录时间 + String authToken = loginGoogleAccount(activity, false); // 获取 Google 账号令牌 + if (authToken == null) { + Log.e(TAG, "login google account failed"); + return false; + } + + // 处理自定义域名账号(非 @gmail.com 或 @googlemail.com) + if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || + mAccount.name.toLowerCase().endsWith("googlemail.com"))) { + StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); + int index = mAccount.name.indexOf('@') + 1; + String suffix = mAccount.name.substring(index); + url.append(suffix + "/"); + mGetUrl = url.toString() + "ig"; // 拼接自定义 GET URL + mPostUrl = url.toString() + "r/ig"; // 拼接自定义 POST URL + + if (tryToLoginGtask(activity, authToken)) { // 尝试登录 Tasks + mLoggedin = true; + } + } + + // 处理官方域名账号(默认情况) + if (!mLoggedin) { + mGetUrl = GTASK_GET_URL; + mPostUrl = GTASK_POST_URL; + if (!tryToLoginGtask(activity, authToken)) { // 再次尝试登录 + return false; + } + } + + mLoggedin = true; // 登录成功 + return true; + } + + /** + * 登录 Google 账号获取认证令牌 + * @param activity Activity 上下文 + * @param invalidateToken 是否失效现有令牌(用于重试场景) + * @return 认证令牌,失败返回 null + */ + private String loginGoogleAccount(Activity activity, boolean invalidateToken) { + String authToken; + AccountManager accountManager = AccountManager.get(activity); + Account[] accounts = accountManager.getAccountsByType("com.google"); // 获取所有 Google 账号 + + if (accounts.length == 0) { + Log.e(TAG, "there is no available google account"); + return null; + } + + // 获取设置中配置的同步账号 + String accountName = NotesPreferenceActivity.getSyncAccountName(activity); + Account account = null; + for (Account a : accounts) { + if (a.name.equals(accountName)) { + account = a; + break; + } + } + if (account == null) { + Log.e(TAG, "unable to get an account with the same name in the settings"); + return null; + } + mAccount = account; // 保存当前账号 + + // 获取认证令牌 + AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account, + "goanna_mobile", null, activity, null, null); + try { + Bundle authTokenBundle = accountManagerFuture.getResult(); + authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); + if (invalidateToken) { + // 失效现有令牌并重新获取(用于处理令牌过期) + accountManager.invalidateAuthToken("com.google", authToken); + loginGoogleAccount(activity, false); + } + } catch (Exception e) { + Log.e(TAG, "get auth token failed"); + authToken = null; + } + + return authToken; + } + + /** + * 尝试登录 Google Tasks 服务 + * @param activity Activity 上下文 + * @param authToken Google 认证令牌 + * @return 是否登录成功 + */ + private boolean tryToLoginGtask(Activity activity, String authToken) { + if (!loginGtask(authToken)) { // 首次登录失败 + // 重新获取令牌并再次尝试 + authToken = loginGoogleAccount(activity, true); + if (authToken == null) { + Log.e(TAG, "login google account failed"); + return false; + } + if (!loginGtask(authToken)) { // 再次登录失败 + Log.e(TAG, "login gtask failed"); + return false; + } + } + return true; + } + + /** + * 使用认证令牌登录 Google Tasks 服务 + * @param authToken Google 认证令牌 + * @return 是否登录成功 + */ + private boolean loginGtask(String authToken) { + int timeoutConnection = 10000; // 连接超时 10 秒 + int timeoutSocket = 15000; // 套接字超时 15 秒 + HttpParams httpParameters = new BasicHttpParams(); + HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); + HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); + mHttpClient = new DefaultHttpClient(httpParameters); // 创建带超时配置的 HTTP 客户端 + BasicCookieStore localBasicCookieStore = new BasicCookieStore(); + mHttpClient.setCookieStore(localBasicCookieStore); // 使用内存 Cookie 存储 + HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); + + try { + // 构造登录 URL(携带认证令牌) + String loginUrl = mGetUrl + "?auth=" + authToken; + HttpGet httpGet = new HttpGet(loginUrl); + HttpResponse response = mHttpClient.execute(httpGet); // 发送 GET 请求 + + // 检查响应中的认证 Cookie + List cookies = mHttpClient.getCookieStore().getCookies(); + boolean hasAuthCookie = false; + for (Cookie cookie : cookies) { + if (cookie.getName().contains("GTL")) { // GTL Cookie 是 Tasks 认证标识 + hasAuthCookie = true; + } + } + if (!hasAuthCookie) { + Log.w(TAG, "it seems that there is no auth cookie"); + } + + // 解析响应获取客户端版本号 + String resString = getResponseContent(response.getEntity()); + String jsBegin = "_setup("; + String jsEnd = ")}"; + int begin = resString.indexOf(jsBegin); + int end = resString.lastIndexOf(jsEnd); + String jsString = null; + if (begin != -1 && end != -1 && begin < end) { + jsString = resString.substring(begin + jsBegin.length(), end); + } + JSONObject js = new JSONObject(jsString); + mClientVersion = js.getLong("v"); // 保存客户端版本号 + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return false; + } catch (Exception e) { + Log.e(TAG, "httpget gtask_url failed"); + return false; + } + + return true; + } + + /** + * 生成唯一操作 ID(自增计数器) + * @return 操作 ID + */ + private int getActionId() { + return mActionId++; + } + + /** + * 创建 POST 请求对象(通用方法) + * @return HttpPost 对象 + */ + private HttpPost createHttpPost() { + HttpPost httpPost = new HttpPost(mPostUrl); + httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); + httpPost.setHeader("AT", "1"); // 可能用于标识请求类型或版本 + return httpPost; + } + + /** + * 解析 HTTP 响应内容(处理压缩格式) + * @param entity HTTP 实体对象 + * @return 响应内容字符串 + * @throws IOException 输入输出异常 + */ + private String getResponseContent(HttpEntity entity) throws IOException { + String contentEncoding = null; + if (entity.getContentEncoding() != null) { + contentEncoding = entity.getContentEncoding().getValue(); + Log.d(TAG, "encoding: " + contentEncoding); + } + + InputStream input = entity.getContent(); + // 处理 GZIP 压缩响应 + if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { + input = new GZIPInputStream(entity.getContent()); + // 处理 DEFLATE 压缩响应 + } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) { + Inflater inflater = new Inflater(true); + input = new InflaterInputStream(entity.getContent(), inflater); + } + + try { + // 读取响应内容为字符串 + InputStreamReader isr = new InputStreamReader(input); + BufferedReader br = new BufferedReader(isr); + StringBuilder sb = new StringBuilder(); + String buff; + while ((buff = br.readLine()) != null) { + sb.append(buff); + } + return sb.toString(); + } finally { + input.close(); // 确保流关闭 + } + } + + /** + * 发送 POST 请求并解析 JSON 响应 + * @param js 请求体 JSON 对象 + * @return 响应 JSON 对象 + * @throws NetworkFailureException 网络异常 + */ + private JSONObject postRequest(JSONObject js) throws NetworkFailureException { + if (!mLoggedin) { + Log.e(TAG, "please login first"); + throw new ActionFailureException("not logged in"); // 未登录时抛出异常 + } + + HttpPost httpPost = createHttpPost(); + try { + // 构造 POST 请求参数(将 JSON 放入请求体) + LinkedList list = new LinkedList<>(); + list.add(new BasicNameValuePair("r", js.toString())); + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); + httpPost.setEntity(entity); + + // 执行 POST 请求 + HttpResponse response = mHttpClient.execute(httpPost); + String jsString = getResponseContent(response.getEntity()); + return new JSONObject(jsString); // 解析响应为 JSON + + } catch (ClientProtocolException e) { + Log.e(TAG, e.toString()); + throw new NetworkFailureException("postRequest failed"); // 协议异常(网络问题) + } catch (IOException e) { + Log.e(TAG, e.toString()); + throw new NetworkFailureException("postRequest failed"); // 输入输出异常(网络问题) + } catch (JSONException e) { + Log.e(TAG, e.toString()); + throw new ActionFailureException("unable to convert response content to jsonobject"); // JSON 解析失败(数据格式问题) + } catch (Exception e) { + Log.e(TAG, e.toString()); + throw new ActionFailureException("error occurs when posting request"); // 其他异常 + } + } + + /** + * 创建任务(调用 Google Tasks API) + * @param task 要创建的任务对象 + * @throws NetworkFailureException 网络异常 + */ + public void createTask(Task task) throws NetworkFailureException { + commitUpdate(); // 提交之前的批量操作(如果有) + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + + // 添加创建任务的操作到请求中 + actionList.put(task.getCreateAction(getActionId())); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); // 携带客户端版本号 + + // 发送请求并解析响应 + JSONObject jsResponse = postRequest(jsPost); + JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( + GTaskStringUtils.GTASK_JSON_RESULTS).get(0); + task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); // 保存任务的 Google ID + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + throw new ActionFailureException("create task: handing jsonobject failed"); + } + } + + /** + * 创建任务列表(调用 Google Tasks API) + * @param tasklist 要创建的任务列表对象 + * @throws NetworkFailureException 网络异常 + */ + public void createTaskList(TaskList tasklist) throws NetworkFailureException { + commitUpdate(); // 提交之前的批量操作 + try { + JSONObject jsPost = new JSONObject \ No newline at end of file