1
+ package com.lvaccaro.alcore
2
+
3
+ import android.content.Context
4
+ import android.os.Build
5
+ import org.json.JSONObject
6
+ import java.io.BufferedReader
7
+ import java.io.File
8
+ import java.io.InputStream
9
+ import java.io.OutputStream
10
+ import java.util.logging.Logger
11
+
12
+
13
+ class LightningCli {
14
+
15
+ val command = " lightning-cli"
16
+ val log = Logger .getLogger(LightningService ::class .java.name)
17
+
18
+ @Throws(Exception ::class )
19
+ fun exec (c : Context , options : Array <String >, json : Boolean = true): InputStream {
20
+ val binaryDir = rootDir(c)
21
+ val lightningDir = File (rootDir(c), " .lightning" )
22
+
23
+ val args =
24
+ arrayOf( String .format(" %s/%s" , binaryDir.canonicalPath, command),
25
+ String .format(" --lightning-dir=%s" , lightningDir.path),
26
+ String .format(" --%s" , if (json == = true ) " json" else " raw" ))
27
+
28
+ val pb = ProcessBuilder ((args + options).asList())
29
+ pb.directory(binaryDir)
30
+ // pb.redirectErrorStream(true)
31
+
32
+ val process = pb.start()
33
+ val code = process.waitFor()
34
+ if (code == null || code != 0 ) {
35
+ val error = toString(process.errorStream)
36
+ val input = toString(process.inputStream)
37
+ log.info(error)
38
+ log.info(input)
39
+ throw Exception (if (! error.isEmpty()) error else input)
40
+ }
41
+ return process.inputStream
42
+
43
+ }
44
+
45
+ fun toJSONObject (stream : InputStream ): JSONObject {
46
+ log.info(" --- start ---" )
47
+ val text = toString(stream)
48
+ val json = JSONObject (text)
49
+ log.info(json.toString())
50
+ log.info(" --- end ---" )
51
+ return json
52
+ }
53
+
54
+ fun toString (stream : InputStream ): String {
55
+ val reader = stream.bufferedReader()
56
+ val builder = StringBuilder ()
57
+ var line = reader.readLine()
58
+ while (line != null ) {
59
+ log.info(line)
60
+ if (! line.startsWith(" **" )) {
61
+ builder.append(line)
62
+ }
63
+ line = reader.readLine()
64
+ }
65
+ return builder.toString()
66
+ }
67
+
68
+ fun rootDir (c : Context ): File {
69
+ if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .LOLLIPOP ) {
70
+ return c.noBackupFilesDir
71
+ }
72
+ return c.filesDir
73
+ }
74
+ }
0 commit comments