From 9bec0e9ecaeff2f14a11e8e5e1055e081bb48af7 Mon Sep 17 00:00:00 2001
From: Nikola Trubitsyn <nikola.trubitsyn@gmail.com>
Date: Thu, 14 Sep 2017 20:29:55 +0300
Subject: [PATCH] Allow to act as a default text file opener

---
 app/src/main/AndroidManifest.xml              |  6 ++
 .../notes/activities/MainActivity.kt          | 63 ++++++++++++++++---
 .../notes/helpers/DBHelper.kt                 | 18 ++++++
 3 files changed, 77 insertions(+), 10 deletions(-)

diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 7df2aedd..88f60429 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -32,6 +32,12 @@
                 <category android:name="android.intent.category.DEFAULT"/>
                 <data android:mimeType="text/plain"/>
             </intent-filter>
+
+            <intent-filter>
+                <action android:name="android.intent.action.VIEW" />
+                <category android:name="android.intent.category.DEFAULT" />
+                <data android:mimeType="text/plain" />
+            </intent-filter>
         </activity>
 
         <activity
diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/activities/MainActivity.kt b/app/src/main/kotlin/com/simplemobiletools/notes/activities/MainActivity.kt
index 0c6ef472..4ef6c50e 100644
--- a/app/src/main/kotlin/com/simplemobiletools/notes/activities/MainActivity.kt
+++ b/app/src/main/kotlin/com/simplemobiletools/notes/activities/MainActivity.kt
@@ -36,8 +36,11 @@ import java.io.File
 import java.nio.charset.Charset
 
 class MainActivity : SimpleActivity(), ViewPager.OnPageChangeListener {
+    private val STORAGE_OPEN_FILE_ACTION = 0
     private val STORAGE_OPEN_FILE = 1
     private val STORAGE_EXPORT_AS_FILE = 2
+
+    private var openFilePath = ""
     private var mAdapter: NotesPagerAdapter? = null
 
     lateinit var mCurrentNote: Note
@@ -65,6 +68,12 @@ class MainActivity : SimpleActivity(), ViewPager.OnPageChangeListener {
                     intent.removeExtra(Intent.EXTRA_TEXT)
                 }
             }
+
+            if (action == Intent.ACTION_VIEW) {
+                handleFile(data.path)
+                intent.removeCategory(Intent.CATEGORY_DEFAULT)
+                intent.action = null
+            }
         }
     }
 
@@ -87,6 +96,22 @@ class MainActivity : SimpleActivity(), ViewPager.OnPageChangeListener {
         }
     }
 
+    private fun handleFile(path: String) {
+        val id = mDb.getNoteId(path)
+
+        if (mDb.isValidId(id)) {
+            updateSelectedNote(id)
+            return
+        }
+
+        if (hasWriteStoragePermission()) {
+            importFileWithSync(path)
+        } else {
+            this.openFilePath = path
+            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), STORAGE_OPEN_FILE_ACTION)
+        }
+    }
+
     private fun initViewPager() {
         mNotes = mDb.getNotes()
         mCurrentNote = mNotes[0]
@@ -220,21 +245,37 @@ class MainActivity : SimpleActivity(), ViewPager.OnPageChangeListener {
 
     private fun openFile() {
         FilePickerDialog(this) {
-            val file = File(it)
-            if (file.isImageVideoGif()) {
-                toast(R.string.invalid_file_format)
-            } else if (file.length() > 10 * 1000 * 1000) {
-                toast(R.string.file_too_large)
-            } else if (mDb.doesTitleExist(it.getFilenameFromPath())) {
-                toast(R.string.title_taken)
-            } else {
-                OpenFileDialog(this, it) {
+            openFile(it, true, {
+                OpenFileDialog(this, it.path) {
                     addNewNote(it)
                 }
-            }
+            })
         }
     }
 
+    private fun openFile(path: String, checkTitle: Boolean, onChecksPassed: (file: File) -> Unit) {
+        val file = File(path)
+        if (file.isImageVideoGif()) {
+            toast(R.string.invalid_file_format)
+        } else if (file.length() > 10 * 1000 * 1000) {
+            toast(R.string.file_too_large)
+        } else if (checkTitle && mDb.doesTitleExist(path.getFilenameFromPath())) {
+            toast(R.string.title_taken)
+        } else {
+            onChecksPassed(file)
+        }
+    }
+
+    private fun importFileWithSync(path: String) {
+        openFile(path, false, {
+            var title = path.getFilenameFromPath()
+            if (mDb.doesTitleExist(title)) title += " (file)"
+
+            val note = Note(0, title, "", TYPE_NOTE, path)
+            addNewNote(note)
+        })
+    }
+
     private fun tryExportAsFile() {
         if (hasWriteStoragePermission()) {
             exportAsFile()
@@ -365,6 +406,8 @@ class MainActivity : SimpleActivity(), ViewPager.OnPageChangeListener {
                 openFile()
             } else if (requestCode == STORAGE_EXPORT_AS_FILE) {
                 exportAsFile()
+            } else if (requestCode == STORAGE_OPEN_FILE_ACTION) {
+                importFileWithSync(openFilePath)
             }
         }
     }
diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/helpers/DBHelper.kt b/app/src/main/kotlin/com/simplemobiletools/notes/helpers/DBHelper.kt
index 284b04a5..81270a8d 100644
--- a/app/src/main/kotlin/com/simplemobiletools/notes/helpers/DBHelper.kt
+++ b/app/src/main/kotlin/com/simplemobiletools/notes/helpers/DBHelper.kt
@@ -138,6 +138,22 @@ class DBHelper private constructor(private val mContext: Context) : SQLiteOpenHe
         return note
     }
 
+    fun getNoteId(path: String): Int {
+        val cols = arrayOf(COL_ID)
+        val selection = "$COL_PATH = ?"
+        val selectionArgs = arrayOf(path)
+        var cursor: Cursor? = null
+        try {
+            cursor = mDb.query(TABLE_NAME, cols, selection, selectionArgs, null, null, null)
+            if (cursor?.moveToFirst() == true) {
+                return cursor.getIntValue(COL_ID)
+            }
+        } finally {
+            cursor?.close()
+        }
+        return 0
+    }
+
     fun updateNoteValue(note: Note) {
         val values = ContentValues().apply { put(COL_VALUE, note.value) }
         updateNote(note.id, values)
@@ -158,4 +174,6 @@ class DBHelper private constructor(private val mContext: Context) : SQLiteOpenHe
         val selectionArgs = arrayOf(id.toString())
         mDb.update(TABLE_NAME, values, selection, selectionArgs)
     }
+
+    fun isValidId(id: Int) = id > 0
 }