Update DataUtils.java

main
pwiz98tyo 2 months ago
parent 3453fe47e3
commit 5039cd6b33

@ -16,280 +16,395 @@
package net.micode.notes.tool; package net.micode.notes.tool;
import android.content.ContentProviderOperation; import android.content.Context;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor; import android.database.Cursor;
import android.os.RemoteException; import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log; import android.util.Log;
import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote; 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.Notes.NoteColumns;
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.List;
public class BackupUtils {
private static final String TAG = "BackupUtils";
// Singleton stuff
private static BackupUtils sInstance;
public class DataUtils { public static synchronized BackupUtils getInstance(Context context) {
public static final String TAG = "DataUtils"; if (sInstance == null) {
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) { sInstance = new BackupUtils(context);
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
} }
if (ids.size() == 0) { return sInstance;
Log.d(TAG, "no id is in the hashset");
return true;
} }
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); /**
for (long id : ids) { * Following states are signs to represents backup or restore
if(id == Notes.ID_ROOT_FOLDER) { * status
Log.e(TAG, "Don't delete system folder root"); */
continue; // Currently, the sdcard is not mounted
public static final int STATE_SD_CARD_UNMOUONTED = 0;
// The backup file not exist
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
// The data is not well formated, may be changed by other programs
public static final int STATE_DATA_DESTROIED = 2;
// Some run-time exception which causes restore or backup fails
public static final int STATE_SYSTEM_ERROR = 3;
// Backup or restore success
public static final int STATE_SUCCESS = 4;
// Permission denied
public static final int STATE_PERMISSION_DENIED = 5;
private TextExport mTextExport;
private BackupUtils(Context context) {
mTextExport = new TextExport(context);
} }
ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); private static boolean externalStorageAvailable() {
operationList.add(builder.build()); return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
} }
try {
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); public int exportToText() {
if (results == null || results.length == 0 || results[0] == null) { return mTextExport.exportToText();
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
} }
return true;
} catch (RemoteException e) { public String getExportedTextFileName() {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); return mTextExport.mFileName;
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} }
return false;
public String getExportedTextFileDir() {
return mTextExport.mFileDirectory;
} }
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) { private static class TextExport {
ContentValues values = new ContentValues(); private static final String[] NOTE_PROJECTION = {
values.put(NoteColumns.PARENT_ID, desFolderId); NoteColumns.ID,
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); NoteColumns.MODIFIED_DATE,
values.put(NoteColumns.LOCAL_MODIFIED, 1); NoteColumns.SNIPPET,
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); NoteColumns.TYPE,
NoteColumns.PARENT_ID
};
private static final int NOTE_COLUMN_ID = 0;
private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
private static final int NOTE_COLUMN_SNIPPET = 2;
private static final int NOTE_COLUMN_TYPE = 3;
private static final int NOTE_COLUMN_PARENT_ID = 4;
private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
DataColumns.DATA1,
DataColumns.DATA2,
DataColumns.DATA3,
DataColumns.DATA4,
};
private static final int DATA_COLUMN_CONTENT = 0;
private static final int DATA_COLUMN_MIME_TYPE = 1;
private static final int DATA_COLUMN_CALL_DATE = 2;
private static final int DATA_COLUMN_PHONE_NUMBER = 4;
private final String [] TEXT_FORMAT;
private static final int FORMAT_FOLDER_NAME = 0;
private static final int FORMAT_NOTE_DATE = 1;
private static final int FORMAT_NOTE_CONTENT = 2;
private Context mContext;
private String mFileName;
private String mFileDirectory;
private BufferedWriter mWriter;
private int mNotesCount;
private int mFoldersCount;
public TextExport(Context context) {
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context;
mFileName = "";
mFileDirectory = "";
mNotesCount = 0;
mFoldersCount = 0;
} }
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids, private String getFormat(int id) {
long folderId) { return TEXT_FORMAT[id];
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
} }
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); /**
for (long id : ids) { * Export notes to text file
ContentProviderOperation.Builder builder = ContentProviderOperation */
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); public int exportToText() {
builder.withValue(NoteColumns.PARENT_ID, folderId); if (!externalStorageAvailable()) {
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); Log.d(TAG, "Media was not mounted");
operationList.add(builder.build()); return STATE_SD_CARD_UNMOUONTED;
} }
try { File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); R.string.file_name_txt_format);
if (results == null || results.length == 0 || results[0] == null) { if (file == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString()); Log.e(TAG, "create file to exported failed");
return false; return STATE_SYSTEM_ERROR;
} }
return true;
} catch (RemoteException e) { mFileName = file.getName();
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); mFileDirectory = mContext.getString(R.string.file_path);
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); // 使用try-with-resources确保资源释放
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))) {
mWriter = writer;
// 导出文件夹和笔记
exportFoldersAndNotes();
// 写入导出统计信息
writeExportSummary();
Log.d(TAG, "Export successful. Exported " + mFoldersCount + " folders and " + mNotesCount + " notes.");
return STATE_SUCCESS;
} catch (IOException e) {
Log.e(TAG, "Error during export: " + e.getMessage(), e);
return STATE_SYSTEM_ERROR;
} }
return false;
} }
/** /**
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}} *
*/ */
public static int getUserFolderCount(ContentResolver resolver) { private void writeExportSummary() throws IOException {
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI, mWriter.write("\n");
new String[] { "COUNT(*)" }, mWriter.write("==============================\n");
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", mWriter.write(mContext.getString(R.string.export_summary) + "\n");
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, mWriter.write(mContext.getString(R.string.export_date) + ": "
null); + DateFormat.format(mContext.getString(R.string.format_datetime_ymdhm), System.currentTimeMillis()) + "\n");
mWriter.write(mContext.getString(R.string.folder_count) + ": " + mFoldersCount + "\n");
int count = 0; mWriter.write(mContext.getString(R.string.note_count) + ": " + mNotesCount + "\n");
if(cursor != null) { mWriter.write("==============================\n");
if(cursor.moveToFirst()) {
try {
count = cursor.getInt(0);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "get folder count failed:" + e.toString());
} finally {
cursor.close();
} }
/**
*
*/
private void exportFoldersAndNotes() throws IOException {
// 首先导出文件夹和其中的笔记
exportFolders();
// 导出根文件夹中的笔记
exportRootNotes();
} }
}
return count;
}
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { /**
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), *
null, */
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, private void exportFolders() throws IOException {
new String [] {String.valueOf(type)}, // 查询所有文件夹
null); String selection = "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
+ NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER;
try (Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
selection, null, null)) {
boolean exist = false; if (folderCursor != null && folderCursor.moveToFirst()) {
if (cursor != null) { do {
if (cursor.getCount() > 0) { mFoldersCount++;
exist = true; exportFolder(folderCursor);
} while (folderCursor.moveToNext());
} }
cursor.close();
} }
return exist;
} }
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { /**
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), *
null, null, null, null); */
private void exportFolder(Cursor folderCursor) throws IOException {
String folderId = folderCursor.getString(NOTE_COLUMN_ID);
String folderName;
boolean exist = false; if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
if (cursor != null) { folderName = mContext.getString(R.string.call_record_folder_name);
if (cursor.getCount() > 0) { } else {
exist = true; folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);
} }
cursor.close();
if (!TextUtils.isEmpty(folderName)) {
mWriter.write(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
mWriter.newLine();
} }
return exist;
// 导出文件夹中的笔记
exportNotesInFolder(folderId);
// 添加文件夹分隔线
mWriter.write("\n");
} }
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { /**
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), *
null, null, null, null); */
private void exportNotesInFolder(String folderId) throws IOException {
try (Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { folderId }, null)) {
boolean exist = false; if (notesCursor != null && notesCursor.moveToFirst()) {
if (cursor != null) { do {
if (cursor.getCount() > 0) { mNotesCount++;
exist = true; exportNote(notesCursor);
} while (notesCursor.moveToNext());
} }
cursor.close();
} }
return exist;
} }
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { /**
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, *
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + */
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + private void exportRootNotes() throws IOException {
" AND " + NoteColumns.SNIPPET + "=?", try (Cursor noteCursor = mContext.getContentResolver().query(
new String[] { name }, null); Notes.CONTENT_NOTE_URI,
boolean exist = false; NOTE_PROJECTION,
if(cursor != null) { NoteColumns.TYPE + "=" + Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID + "=0",
if(cursor.getCount() > 0) { null, null)) {
exist = true;
if (noteCursor != null && noteCursor.moveToFirst()) {
do {
mNotesCount++;
exportNote(noteCursor);
} while (noteCursor.moveToNext());
} }
cursor.close();
} }
return exist;
} }
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) { /**
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, *
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, */
NoteColumns.PARENT_ID + "=?", private void exportNote(Cursor noteCursor) throws IOException {
new String[] { String.valueOf(folderId) }, // 打印笔记的最后修改日期
null); mWriter.write(String.format(getFormat(FORMAT_NOTE_DATE),
DateFormat.format(mContext.getString(R.string.format_datetime_mdhm),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
mWriter.newLine();
// 查询并导出笔记的数据
String noteId = noteCursor.getString(NOTE_COLUMN_ID);
exportNoteData(noteId);
// 添加笔记分隔线
mWriter.write("\n");
}
HashSet<AppWidgetAttribute> set = null; /**
if (c != null) { *
if (c.moveToFirst()) { */
set = new HashSet<AppWidgetAttribute>(); private void exportNoteData(String noteId) throws IOException {
try (Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { noteId }, null)) {
if (dataCursor != null && dataCursor.moveToFirst()) {
do { do {
try { String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
AppWidgetAttribute widget = new AppWidgetAttribute(); if (DataConstants.CALL_NOTE.equals(mimeType)) {
widget.widgetId = c.getInt(0); exportCallNote(dataCursor);
widget.widgetType = c.getInt(1); } else if (DataConstants.NOTE.equals(mimeType)) {
set.add(widget); exportTextNote(dataCursor);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, e.toString());
} }
} while (c.moveToNext()); } while (dataCursor.moveToNext());
} }
c.close();
} }
return set;
} }
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { /**
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, *
new String [] { CallNote.PHONE_NUMBER }, */
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", private void exportCallNote(Cursor dataCursor) throws IOException {
new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE }, // 打印电话号码
null); String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
String location = dataCursor.getString(DATA_COLUMN_CONTENT);
if (cursor != null && cursor.moveToFirst()) { if (!TextUtils.isEmpty(phoneNumber)) {
try { mWriter.write(String.format(getFormat(FORMAT_NOTE_CONTENT), phoneNumber));
return cursor.getString(0); mWriter.newLine();
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call number fails " + e.toString());
} finally {
cursor.close();
}
}
return "";
} }
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { // 打印通话日期
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, mWriter.write(String.format(getFormat(FORMAT_NOTE_CONTENT),
new String [] { CallNote.NOTE_ID }, DateFormat.format(mContext.getString(R.string.format_datetime_mdhm), callDate)));
CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" mWriter.newLine();
+ CallNote.PHONE_NUMBER + ",?)",
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
null);
if (cursor != null) { // 打印通话附件位置
if (cursor.moveToFirst()) { if (!TextUtils.isEmpty(location)) {
try { mWriter.write(String.format(getFormat(FORMAT_NOTE_CONTENT), location));
return cursor.getLong(0); mWriter.newLine();
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call note id fails " + e.toString());
} }
} }
cursor.close();
/**
*
*/
private void exportTextNote(Cursor dataCursor) throws IOException {
String content = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(content)) {
mWriter.write(String.format(getFormat(FORMAT_NOTE_CONTENT), content));
mWriter.newLine();
} }
return 0;
} }
public static String getSnippetById(ContentResolver resolver, long noteId) { /**
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, * Generate the text file to store imported data
new String [] { NoteColumns.SNIPPET }, */
NoteColumns.ID + "=?", private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
new String [] { String.valueOf(noteId)}, StringBuilder sb = new StringBuilder();
null);
if (cursor != null) { // 适配Android 10+的存储访问
String snippet = ""; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (cursor.moveToFirst()) { sb.append(context.getExternalFilesDir(null));
snippet = cursor.getString(0); } else {
} sb.append(Environment.getExternalStorageDirectory());
cursor.close();
return snippet;
} }
throw new IllegalArgumentException("Note is not found with id: " + noteId);
sb.append(context.getString(filePathResId));
File filedir = new File(sb.toString());
// 确保目录存在
if (!filedir.exists() && !filedir.mkdirs()) {
Log.e(TAG, "Failed to create directory: " + filedir.getAbsolutePath());
return null;
} }
public static String getFormattedSnippet(String snippet) { // 构建文件名
if (snippet != null) { sb.append(context.getString(
snippet = snippet.trim(); fileNameFormatResId,
int index = snippet.indexOf('\n'); DateFormat.format(context.getString(R.string.format_date_ymd),
if (index != -1) { System.currentTimeMillis())));
snippet = snippet.substring(0, index); File file = new File(sb.toString());
try {
if (!file.exists() && !file.createNewFile()) {
Log.e(TAG, "Failed to create file: " + file.getAbsolutePath());
return null;
}
return file;
} catch (SecurityException | IOException e) {
Log.e(TAG, "Error creating file: " + e.getMessage(), e);
return null;
} }
} }
return snippet;
} }
} }

Loading…
Cancel
Save