Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 93bb6d3c authored by Mohammed Althaf T's avatar Mohammed Althaf T 😊
Browse files

Merge branch '2984-main-export' into 'main'

Add support to export notes

See merge request !62
parents 8949e309 c5c4aa6c
Loading
Loading
Loading
Loading
Loading
+1 −0
Original line number Diff line number Diff line
@@ -6,6 +6,7 @@
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS"/>
    <uses-permission android:name="android.permission.READ_SYNC_SETTINGS"/>
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>

    <queries>
        <package android:name="com.nextcloud.client" />
+115 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2025 e Foundation
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package foundation.e.notes.export

import android.content.Context
import android.util.AttributeSet

import androidx.appcompat.app.AlertDialog
import androidx.preference.DialogPreference

import it.niedermann.owncloud.notes.R
import it.niedermann.owncloud.notes.persistence.NotesRepository
import it.niedermann.owncloud.notes.persistence.entity.Account

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class ExportPreference(context: Context, attrs: AttributeSet?) : DialogPreference(context, attrs) {
    private val selectedValues = mutableSetOf<String>()
    private var accounts: List<Account> = emptyList()
    private var alertDialog: AlertDialog? = null

    init {
        CoroutineScope(Dispatchers.IO).launch {
            val notesRepo = NotesRepository.getInstance(context)
            val fetchedAccounts = notesRepo.accounts ?: emptyList()

            withContext(Dispatchers.Main) {
                accounts = fetchedAccounts
            }
        }
        dialogLayoutResource = R.layout.dialog_export_notes
    }

    override fun onClick() {
        loadSavedAccounts()
        showDialog()
    }

    /**
     * Loads previously saved selected accounts.
     * If nothing was selected before, selects all by default.
     */
    private fun loadSavedAccounts() {
        val savedValues = getPersistedStringSet(emptySet())

        if (savedValues.isEmpty()) {
            selectedValues.addAll(accounts.map { it.id.toString() })
        } else {
            selectedValues.addAll(savedValues)
        }
    }

    private fun showDialog() {
        val builder = AlertDialog.Builder(context)
        builder.setTitle(context.getString(R.string.settings_export_notes_title))

        val accountNames = accounts.map { it.accountName }.toTypedArray()
        val checkedItems = BooleanArray(accounts.size) {
            selectedValues.contains(accounts[it].id.toString())
        }

        builder.setMultiChoiceItems(accountNames, checkedItems) { _, index, isChecked ->
            val id = accounts[index].id.toString()
            if (isChecked) {
                selectedValues.add(id)
            } else {
                selectedValues.remove(id)
            }
        }

        builder.setPositiveButton(R.string.settings_export) { _, _ -> saveSelection() }
        builder.setNegativeButton(android.R.string.cancel, null)

        alertDialog = builder.create().apply {
            setOnDismissListener { alertDialog = null }
            show()
        }
    }

    /**
     * Saves the selected accounts and triggers the export.
     */
    private fun saveSelection() {
        persistStringSet(selectedValues)

        CoroutineScope(Dispatchers.IO).launch {
            val accountIds = selectedValues.map { it.toLong() }
            NotesExporter().export(context, accountIds)
        }
    }

    override fun onDetached() {
        super.onDetached()
        alertDialog?.takeIf { it.isShowing }?.dismiss()
        alertDialog = null
    }
}
+122 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2025 e Foundation
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package foundation.e.notes.export

import android.content.Context
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast

import it.niedermann.owncloud.notes.R
import it.niedermann.owncloud.notes.persistence.NotesRepository
import it.niedermann.owncloud.notes.persistence.entity.Note

import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class NotesExporter {

    private var handler: Handler = Handler(Looper.getMainLooper())

    fun export(context: Context, accountIds: List<Long>) {
        val notesRepo = NotesRepository.getInstance(context)
        val accounts = notesRepo.accounts.filter { it.id in accountIds }

        if (accounts.isEmpty()) {
            handler.post {
                Toast.makeText(
                    context, context.getString(R.string.export_empty_accounts),
                    Toast.LENGTH_SHORT).show()
            }
            return
        }

        Log.d(TAG, "Exporting notes for ${accounts.size} accounts")

        accounts.forEach { account ->
            val notes = notesRepo.getNotesByAccountId(account.id)
            if (notes.isNotEmpty()) {
                exportNotesForAccount(notes, account.userName)
            }
        }

        handler.post {
            Toast.makeText(
                context, context.getString(R.string.export_finished_message),
                Toast.LENGTH_SHORT
            ).show()
        }
    }

    private fun exportNotesForAccount(notes: List<Note>, accountUserName: String) {
        Log.d(TAG, "Exporting ${notes.size} notes for account: $accountUserName")

        notes.forEach { note ->
            val notesDir = getNotesDirectory(accountUserName, note.category)
            ensureDirectoryExists(notesDir)
            val fileName = "${note.title}-${note.modified?.time?.let { getCurrentTimestamp(it) }}"
            writeNoteToFile(notesDir, fileName, note.content)
        }
    }

    private fun getNotesDirectory(userName: String, category: String): File {
        val combinedDir = if (category.isNotEmpty()) "/${category}" else ""
        return File(Environment.getExternalStorageDirectory(), "$EXPORT_DIR/$userName$combinedDir")
    }

    private fun ensureDirectoryExists(directory: File) {
        if (!directory.exists() && directory.mkdirs()) {
            Log.d(TAG, "Created directory: ${directory.absolutePath}")
        }
    }

    private fun writeNoteToFile(directory: File, title: String, content: String) {
        var sanitizedTitle = sanitizeFileName(title)
        if (sanitizedTitle.isBlank()) {
            sanitizedTitle = "Untitled-${getCurrentTimestamp(Date())}"
            Log.w(TAG, "Renaming note with a random title")
        }

        val noteFile = File(directory, "$sanitizedTitle.md")
        try {
            noteFile.writeText(content)
            Log.d(TAG, "Written file: ${noteFile.absolutePath}")
        } catch (e: IOException) {
            Log.e(TAG, "Failed to write file: ${noteFile.absolutePath}", e)
        }
    }

    private fun getCurrentTimestamp(date: Date): String {
        return SimpleDateFormat(DATE_TIME_FORMAT, Locale.getDefault()).format(date)
    }

    private fun sanitizeFileName(name: String): String {
        return name.trim().replace(Regex("[/:*?\"<>|]"), "_")
    }

    companion object {
        private const val TAG = "NotesExporter"
        private const val EXPORT_DIR = "Notes"
        private const val DATE_TIME_FORMAT = "yyyyMMdd-HHmmss"
    }
}
+7 −0
Original line number Diff line number Diff line
@@ -41,6 +41,8 @@ import com.nextcloud.android.sso.exceptions.NoCurrentAccountSelectedException;
import com.nextcloud.android.sso.helper.SingleAccountHelper;
import com.nextcloud.android.sso.model.SingleSignOnAccount;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
@@ -1177,4 +1179,9 @@ public class NotesRepository {
        newNote.setAccountId(note.getAccountId());
        db.getNoteDao().addNote(newNote);
    }

    @NotNull
    public List<Note> getNotesByAccountId(long accountId) {
        return db.getNoteDao().getNotesByAccountId(accountId);
    }
}
+4 −0
Original line number Diff line number Diff line
@@ -30,6 +30,7 @@ public interface NoteDao {
    int updateNote(Note newNote);

    String getNoteById = "SELECT * FROM NOTE WHERE id = :id";
    String getNoteByAccountId = "SELECT * FROM NOTE WHERE status != 'LOCAL_DELETED' AND accountId = :accountId ORDER BY modified DESC";
    String count = "SELECT COUNT(*) FROM NOTE WHERE status != 'LOCAL_DELETED' AND accountId = :accountId";
    String countFavorites = "SELECT COUNT(*) FROM NOTE WHERE status != 'LOCAL_DELETED' AND accountId = :accountId AND favorite = 1";
    String searchRecentByModified = "SELECT id, remoteId, accountId, title, favorite, excerpt, modified, category, status, '' as eTag, '' as content, 0 as scrollY FROM NOTE WHERE accountId = :accountId AND status != 'LOCAL_DELETED' AND (title LIKE :query OR content LIKE :query) ORDER BY favorite DESC, modified DESC";
@@ -161,6 +162,9 @@ public interface NoteDao {
    @Query("SELECT * FROM NOTE WHERE status != 'LOCAL_DELETED' AND accountId = :accountId ORDER BY modified DESC LIMIT 4")
    List<Note> getRecentNotes(long accountId);

    @Query(getNoteByAccountId)
    List<Note> getNotesByAccountId(long accountId);

    @Query("UPDATE NOTE SET status = :status, favorite = ((favorite | 1) - (favorite & 1)) WHERE id = :id")
    void toggleFavorite(long id, DBStatus status);

Loading