This repository has been archived by the owner on Feb 13, 2024. It is now read-only.
/
FileStore.kt
399 lines (332 loc) · 12.8 KB
/
FileStore.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
package nl.mpcjanssen.simpletask.remote
import android.Manifest
import android.app.*
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.*
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v4.content.LocalBroadcastManager
import nl.mpcjanssen.simpletask.Constants
import nl.mpcjanssen.simpletask.Logger
import nl.mpcjanssen.simpletask.TodoApplication
import nl.mpcjanssen.simpletask.util.*
import java.io.File
import java.io.FilenameFilter
import java.io.IOException
import java.util.*
import java.util.concurrent.CopyOnWriteArrayList
object FileStore : FileStoreInterface {
override fun getVersion(filename: String): String {
return File(filename).lastModified().toString()
}
override fun needsRefresh(currentVersion: String?): Boolean {
return currentVersion?.toLong() ?: 0 < Config.todoFile.lastModified()
}
override val isOnline = true
private val TAG = javaClass.simpleName
private val bm: LocalBroadcastManager
private val log: Logger
private var observer: TodoObserver? = null
override var isLoading: Boolean = false
private var fileOperationsQueue: Handler? = null
init {
log = Logger
log.info(TAG, "onCreate")
observer = null
this.bm = LocalBroadcastManager.getInstance(TodoApplication.app)
// Set up the message queue
val t = Thread(Runnable {
Looper.prepare()
fileOperationsQueue = Handler()
Looper.loop()
})
t.start()
}
override val isAuthenticated: Boolean
get() = true
fun queueRunnable(description: String, r: Runnable) {
log.info(TAG, "Handler: Queue " + description)
while (fileOperationsQueue == null) {
try {
Thread.sleep(100)
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
fileOperationsQueue!!.post(r)
}
@Synchronized override fun loadTasksFromFile(path: String, backup: BackupInterface?, eol: String): List<String> {
log.info(TAG, "Loading tasks")
val result = CopyOnWriteArrayList<String>()
isLoading = true
try {
val completeFile = ArrayList<String>()
val lines = File(path).readLines()
log.info(TAG, "Read ${lines.size} lines from $path")
for (line in lines) {
completeFile.add(line)
result.add(line)
}
backup?.backup(path, join(completeFile, "\n"))
} catch (e: IOException) {
log.info(TAG, "Read read failed", e)
e.printStackTrace()
} finally {
isLoading = false
}
setWatching(TodoApplication.app, path)
return result
}
override fun sync() {
}
override fun writeFile(file: File, contents: String) {
log.info(TAG, "Writing file to ${file.canonicalPath}")
file.writeText(contents)
}
override fun readFile(file: String, fileRead: FileStoreInterface.FileReadListener?): String {
log.info(TAG, "Reading file: {}" + file)
isLoading = true
val contents: String
val lines = File(file).readLines()
contents = join(lines, "\n")
isLoading = false
fileRead?.fileRead(contents)
return contents
}
override fun supportsSync(): Boolean {
return false
}
override fun changesPending(): Boolean {
return false
}
override fun startLogin(caller: Activity) {
// FIXME possible add permission retrieval on Lollipop here
}
@Synchronized private fun setWatching(caller: Context, path: String) {
log.info(TAG, "Starting observe service on $path")
val i = Intent(caller, FileWatchService::class.java)
i.putExtra(FileWatchService.pathExtra, path)
caller.startService(i)
}
override fun browseForNewFile(act: Activity, path: String, listener: FileStoreInterface.FileSelectedListener, txtOnly: Boolean) {
val dialog = FileDialog(act, path, txtOnly)
dialog.addFileListener(listener)
dialog.createFileDialog(act, this)
}
@Synchronized override fun saveTasksToFile(path: String, lines: List<String>, backup: BackupInterface?, eol: String, updateVersion: Boolean) {
log.info(TAG, "Saving tasks to file: {}" + path)
backup?.backup(path, join(lines, "\n"))
val obs = observer
obs?.ignoreEvents(true)
queueRunnable("Save ${lines.size} lines to file " + path, Runnable {
try {
writeToFile(join(lines, eol) + eol, File(path), false)
if (updateVersion) {
Config.currentVersionId = File(path).lastModified().toString()
}
} catch (e: IOException) {
log.error(TAG, "Saving $path failed", e)
e.printStackTrace()
} finally {
obs?.delayedStartListen(1000)
}
})
}
override fun appendTaskToFile(path: String, lines: List<String>, eol: String) {
queueRunnable("Appending ${lines.size} lines tasks to $path", Runnable {
log.info(TAG, "Appending ${lines.size} tasks to $path")
try {
writeToFile(join(lines, eol) + eol, File(path), true)
} catch (e: IOException) {
e.printStackTrace()
}
bm.sendBroadcast(Intent(Constants.BROADCAST_SYNC_DONE))
})
}
override val type: Int
get() = Constants.STORE_SDCARD
override fun getWritePermission(act: Activity, activityResult: Int): Boolean {
val permissionCheck = ContextCompat.checkSelfPermission(act,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (permissionCheck == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(act,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), activityResult)
}
return permissionCheck == PackageManager.PERMISSION_GRANTED
}
class FileDialog
/**
* @param activity
* *
* @param pathName
*/
(private val activity: Activity, pathName: String, private val txtOnly: Boolean) {
private var fileList: Array<String>? = null
private var currentPath: File? = null
private val fileListenerList = ListenerList<FileStoreInterface.FileSelectedListener>()
init {
var path = File(pathName)
if (!path.exists() || !path.isDirectory) path = Environment.getExternalStorageDirectory()
loadFileList(path)
}
/**
* @return file dialog
*/
// Parameters are needed for dropbox version
fun createFileDialog(@Suppress("UNUSED_PARAMETER") ctx: Context?, @Suppress("UNUSED_PARAMETER") fs: FileStoreInterface?): Dialog {
val dialog: Dialog
val builder = AlertDialog.Builder(activity)
builder.setTitle(currentPath!!.path)
builder.setItems(fileList) { dialog, which ->
val fileChosen = fileList!![which]
val chosenFile = getChosenFile(fileChosen)
if (chosenFile.isDirectory) {
loadFileList(chosenFile)
dialog.cancel()
dialog.dismiss()
showDialog()
} else
fireFileSelectedEvent(chosenFile)
}
dialog = builder.show()
return dialog
}
fun addFileListener(listener: FileStoreInterface.FileSelectedListener) {
fileListenerList.add(listener)
}
/**
* Show file dialog
*/
fun showDialog() {
createFileDialog(null, null).show()
}
private fun fireFileSelectedEvent(file: File) {
fileListenerList.fireEvent(object : ListenerList.FireHandler<FileStoreInterface.FileSelectedListener> {
override fun fireEvent(listener: FileStoreInterface.FileSelectedListener) {
listener.fileSelected(file.toString())
}
})
}
private fun loadFileList(path: File) {
this.currentPath = path
val r = ArrayList<String>()
if (path.exists()) {
if (path.parentFile != null) r.add(PARENT_DIR)
val filter = FilenameFilter { dir, filename ->
val sel = File(dir, filename)
if (!sel.canRead())
false
else {
val txtFile = filename.toLowerCase(Locale.getDefault()).endsWith(".txt")
!txtOnly || sel.isDirectory || txtFile
}
}
val fileList1 = path.list(filter)
if (fileList1 != null) {
Collections.addAll(r, *fileList1)
} else {
// Fallback to root
r.add("/")
}
} else {
// Fallback to root
r.add("/")
}
Collections.sort(r)
fileList = r.toArray(arrayOfNulls<String>(r.size))
}
private fun getChosenFile(fileChosen: String): File {
if (fileChosen == PARENT_DIR)
return currentPath!!.parentFile
else
return File(currentPath, fileChosen)
}
companion object {
private val PARENT_DIR = ".."
}
}
override fun logout() {
}
fun getDefaultPath(): String {
return "${Environment.getExternalStorageDirectory()}/data/nl.mpcjanssen.simpletask/todo.txt"
}
}
class TodoObserver(val path: String) : FileObserver(File(path).parentFile.absolutePath) {
private val TAG = "FileWatchService"
private val bm: LocalBroadcastManager = LocalBroadcastManager.getInstance(TodoApplication.app)
private val fileName: String
private var log = Logger
private var ignoreEvents: Boolean = false
private val handler: Handler
private val delayedEnable = Runnable {
log.info(TAG, "Observer: Delayed enabling events for: " + path)
ignoreEvents(false)
}
init {
this.startWatching()
this.fileName = File(path).name
log.info(TAG, "Observer: creating observer on: {}")
this.ignoreEvents = false
this.handler = Handler(Looper.getMainLooper())
}
fun ignoreEvents(ignore: Boolean) {
log.info(TAG, "Observer: observing events on " + this.path + "? ignoreEvents: " + ignore)
this.ignoreEvents = ignore
}
override fun onEvent(event: Int, eventPath: String?) {
if (eventPath != null && eventPath == fileName) {
log.debug(TAG, "Observer event: $path:$event")
if (event == FileObserver.CLOSE_WRITE ||
event == FileObserver.MODIFY ||
event == FileObserver.MOVED_TO) {
if (ignoreEvents) {
log.info(TAG, "Observer: ignored event on: " + path)
} else {
log.info(TAG, "File changed {}" + path)
broadcastFileChanged(bm)
}
}
}
}
fun delayedStartListen(ms: Int) {
// Cancel any running timers
handler.removeCallbacks(delayedEnable)
// Reschedule
Logger.info(TAG, "Observer: Adding delayed enabling to queue")
handler.postDelayed(delayedEnable, ms.toLong())
}
}
class FileWatchService : Service() {
var observer: TodoObserver? = null
val TAG = "FileWatchService"
override fun onBind(p0: Intent?): IBinder {
throw UnsupportedOperationException("not implemented")
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Logger.info(TAG, "Received start id $startId: $intent")
val path = intent?.getStringExtra(pathExtra)
Logger.info(TAG, "Path = $path")
setWatching(path)
return Service.START_STICKY
}
@Synchronized private fun setWatching(path: String?) {
val path = path ?: Config.todoFileName
Logger.info(TAG, "Observer: adding folder watcher on ${File(path).parentFile.absolutePath}")
val obs = observer
if (obs != null && path == obs.path) {
Logger.warn(TAG, "Observer: already watching: $path")
return
} else if (obs != null) {
Logger.warn(TAG, "Observer: already watching different path: ${obs.path}")
obs.ignoreEvents(true)
obs.stopWatching()
}
observer = TodoObserver(path)
Logger.info(TAG, "Observer: modifying done")
}
companion object {
val pathExtra = "path"
}
}