aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/com/zeapo/pwdstore/git/GitAsyncTask.kt
blob: 66d953e918cc4c6adca8a6c9384224cc3b2235bf (plain)
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
/*
 * Copyright © 2014-2020 The Android Password Store Authors. All Rights Reserved.
 * SPDX-License-Identifier: GPL-3.0-only
 */
package com.zeapo.pwdstore.git

import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.os.AsyncTask
import androidx.appcompat.app.AppCompatActivity
import com.github.ajalt.timberkt.e
import com.zeapo.pwdstore.R
import com.zeapo.pwdstore.git.config.SshjSessionFactory
import net.schmizz.sshj.common.DisconnectReason
import net.schmizz.sshj.common.SSHException
import net.schmizz.sshj.userauth.UserAuthException
import org.eclipse.jgit.api.CommitCommand
import org.eclipse.jgit.api.GitCommand
import org.eclipse.jgit.api.PullCommand
import org.eclipse.jgit.api.PushCommand
import org.eclipse.jgit.api.RebaseResult
import org.eclipse.jgit.api.StatusCommand
import org.eclipse.jgit.transport.RemoteRefUpdate
import org.eclipse.jgit.transport.SshSessionFactory
import java.io.IOException
import java.lang.ref.WeakReference


class GitAsyncTask(
    activity: AppCompatActivity,
    private val operation: GitOperation,
    private val finishWithResultOnEnd: Intent?,
    private val silentlyExecute: Boolean = false
) : AsyncTask<GitCommand<*>, Int, GitAsyncTask.Result>() {

    private val activityWeakReference: WeakReference<AppCompatActivity> = WeakReference(activity)
    private val activity: AppCompatActivity?
        get() = activityWeakReference.get()
    private val context: Context = activity.applicationContext
    private val dialog = ProgressDialog(activity)

    sealed class Result {
        object Ok : Result()
        data class Err(val err: Exception) : Result()
    }

    override fun onPreExecute() {
        if (silentlyExecute) return
        dialog.run {
            setMessage(activity!!.resources.getString(R.string.running_dialog_text))
            setCancelable(false)
            show()
        }
    }

    override fun doInBackground(vararg commands: GitCommand<*>): Result? {
        var nbChanges: Int? = null
        for (command in commands) {
            try {
                when (command) {
                    is StatusCommand -> {
                        // in case we have changes, we want to keep track of it
                        val status = command.call()
                        nbChanges = status.changed.size + status.missing.size
                    }
                    is CommitCommand -> {
                        // the previous status will eventually be used to avoid a commit
                        if (nbChanges == null || nbChanges > 0) command.call()
                    }
                    is PullCommand -> {
                        val result = command.call()
                        val rr = result.rebaseResult
                        if (rr.status === RebaseResult.Status.STOPPED) {
                            return Result.Err(IOException(context.getString(R.string
                                .git_pull_fail_error)))
                        }
                    }
                    is PushCommand -> {
                        for (result in command.call()) {
                            // Code imported (modified) from Gerrit PushOp, license Apache v2
                            for (rru in result.remoteUpdates) {
                                val error = when (rru.status) {
                                    RemoteRefUpdate.Status.REJECTED_NONFASTFORWARD ->
                                        context.getString(R.string.git_push_nff_error)
                                    RemoteRefUpdate.Status.REJECTED_NODELETE,
                                    RemoteRefUpdate.Status.REJECTED_REMOTE_CHANGED,
                                    RemoteRefUpdate.Status.NON_EXISTING,
                                    RemoteRefUpdate.Status.NOT_ATTEMPTED
                                    ->
                                        (activity!!.getString(R.string.git_push_generic_error) + rru.status.name)
                                    RemoteRefUpdate.Status.REJECTED_OTHER_REASON -> {
                                        if
                                            ("non-fast-forward" == rru.message) {
                                            context.getString(R.string.git_push_other_error)
                                        } else {
                                            (context.getString(R.string.git_push_generic_error)
                                                + rru.message)
                                        }
                                    }
                                    else -> null

                                }
                                if (error != null)
                                    Result.Err(IOException(error))
                            }
                        }
                    }
                    else -> {
                        command.call()
                    }
                }
            } catch (e: Exception) {
                return Result.Err(e)
            }
        }
        return Result.Ok
    }

    private fun rootCauseException(e: Exception): Exception {
        var rootCause = e
        // JGit's TransportException hides the more helpful SSHJ exceptions.
        // Also, SSHJ's UserAuthException about exhausting available authentication methods hides
        // more useful exceptions.
        while ((rootCause is org.eclipse.jgit.errors.TransportException ||
                rootCause is org.eclipse.jgit.api.errors.TransportException ||
                (rootCause is UserAuthException &&
                    rootCause.message == "Exhausted available authentication methods"))) {
            rootCause = rootCause.cause as? Exception ?: break
        }
        return rootCause
    }

    private fun isExplicitlyUserInitiatedError(e: Exception): Boolean {
        var cause: Exception? = e
        while (cause != null) {
            if (cause is SSHException &&
                cause.disconnectReason == DisconnectReason.AUTH_CANCELLED_BY_USER)
                return true
            cause = cause.cause as? Exception
        }
        return false
    }

    override fun onPostExecute(maybeResult: Result?) {
        if (!silentlyExecute) dialog.dismiss()
        when (val result = maybeResult ?: Result.Err(IOException("Unexpected error"))) {
            is Result.Err -> {
                if (isExplicitlyUserInitiatedError(result.err)) {
                    // Currently, this is only executed when the user cancels a password prompt
                    // during authentication.
                    if (finishWithResultOnEnd != null) {
                        activity?.setResult(AppCompatActivity.RESULT_CANCELED)
                        activity?.finish()
                    }
                } else {
                    e(result.err)
                    operation.onError(rootCauseException(result.err))
                    if (finishWithResultOnEnd != null) {
                        activity?.setResult(AppCompatActivity.RESULT_CANCELED)
                    }
                }
            }
            is Result.Ok -> {
                operation.onSuccess()
                if (finishWithResultOnEnd != null) {
                    activity?.setResult(AppCompatActivity.RESULT_OK, finishWithResultOnEnd)
                    activity?.finish()
                }
            }
        }
        (SshSessionFactory.getInstance() as? SshjSessionFactory)?.clearCredentials()
        SshSessionFactory.setInstance(null)
    }

}