1
0

LoginActivity.kt 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. package io.github.zadam.triliumsender
  2. import android.os.AsyncTask
  3. import android.os.Bundle
  4. import android.support.v7.app.AppCompatActivity
  5. import android.text.TextUtils
  6. import android.util.Log
  7. import android.view.View
  8. import android.view.inputmethod.EditorInfo
  9. import android.widget.TextView
  10. import android.widget.Toast
  11. import io.github.zadam.triliumsender.services.TriliumSettings
  12. import io.github.zadam.triliumsender.services.Utils
  13. import kotlinx.android.synthetic.main.activity_login.*
  14. import okhttp3.OkHttpClient
  15. import okhttp3.Request
  16. import okhttp3.RequestBody
  17. import okhttp3.Response
  18. import org.json.JSONObject
  19. class LoginActivity : AppCompatActivity() {
  20. /**
  21. * Keep track of the login task to ensure we can cancel it if requested.
  22. */
  23. private var loginTask: UserLoginTask? = null
  24. override fun onCreate(savedInstanceState: Bundle?) {
  25. super.onCreate(savedInstanceState)
  26. setContentView(R.layout.activity_login)
  27. passwordEditText.setOnEditorActionListener(TextView.OnEditorActionListener { _, id, _ ->
  28. if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
  29. attemptLogin()
  30. return@OnEditorActionListener true
  31. }
  32. false
  33. })
  34. loginButton.setOnClickListener { attemptLogin() }
  35. }
  36. /**
  37. * Attempts to sign in or register the account specified by the login form.
  38. * If there are form errors (invalid email, missing fields, etc.), the
  39. * errors are presented and no actual login attempt is made.
  40. */
  41. private fun attemptLogin() {
  42. if (loginTask != null) {
  43. return
  44. }
  45. // Reset errors.
  46. usernameEditText.error = null
  47. passwordEditText.error = null
  48. // Store values at the time of the login attempt.
  49. val triliumAddress = triliumAddressEditText.text.toString();
  50. val username = usernameEditText.text.toString()
  51. val password = passwordEditText.text.toString()
  52. var cancel = false
  53. var focusView: View? = null
  54. // Check for a valid username
  55. if (TextUtils.isEmpty(username)) {
  56. usernameEditText.error = getString(R.string.error_field_required)
  57. focusView = usernameEditText
  58. cancel = true
  59. }
  60. if (cancel) {
  61. // There was an error; don't attempt login and focus the first
  62. // form field with an error.
  63. focusView?.requestFocus()
  64. } else {
  65. loginTask = UserLoginTask(triliumAddress, username, password)
  66. loginTask!!.execute(null as Void?)
  67. }
  68. }
  69. inner class LoginResult (val success: Boolean, val errorCode : Int?,
  70. val token : String? = null);
  71. /**
  72. * Represents an asynchronous login/registration task used to authenticate
  73. * the user.
  74. */
  75. inner class UserLoginTask internal constructor(private val triliumAddress: String, private val username: String, private val password: String) : AsyncTask<Void, Void, LoginResult>() {
  76. val TAG : String = "UserLoginTask"
  77. override fun doInBackground(vararg params: Void): LoginResult {
  78. val client = OkHttpClient()
  79. val json = JSONObject()
  80. json.put("username", username)
  81. json.put("password", password)
  82. val body = RequestBody.create(Utils.JSON, json.toString())
  83. val request = Request.Builder()
  84. .url(triliumAddress + "/api/sender/login")
  85. .post(body)
  86. .build()
  87. val response: Response;
  88. try {
  89. response = client.newCall(request).execute()
  90. }
  91. catch (e: Exception) {
  92. Log.e(TAG, "Can't connect to Trilium server", e);
  93. return LoginResult(false, R.string.error_network_error)
  94. }
  95. Log.i(TAG,"Response code: " + response.code())
  96. if (response.code() == 401) {
  97. return LoginResult(false, R.string.error_incorrect_credentials)
  98. }
  99. else if (response.code() != 200) {
  100. return LoginResult(false, R.string.error_unexpected_response)
  101. }
  102. val responseText = response.body()?.string()
  103. Log.i(TAG,"Response text: " + responseText)
  104. val resp = JSONObject(responseText)
  105. val token : String = resp.get("token") as String
  106. Log.i(TAG,"Token: " + token)
  107. return LoginResult(true, null, token);
  108. }
  109. override fun onPostExecute(loginResult: LoginResult) {
  110. loginTask = null
  111. if (loginResult.success) {
  112. TriliumSettings(this@LoginActivity).save(triliumAddress, loginResult.token!!)
  113. Toast.makeText(this@LoginActivity, "Trilium connection settings have been successfully configured.", Toast.LENGTH_LONG).show()
  114. finish()
  115. } else {
  116. if (loginResult.errorCode == R.string.error_network_error
  117. || loginResult.errorCode == R.string.error_unexpected_response) {
  118. triliumAddressEditText.error = getString(loginResult.errorCode)
  119. triliumAddressEditText.requestFocus()
  120. }
  121. else if (loginResult.errorCode == R.string.error_incorrect_credentials) {
  122. passwordEditText.error = getString(loginResult.errorCode)
  123. passwordEditText.requestFocus()
  124. }
  125. else {
  126. throw RuntimeException("Unknown code: " + loginResult.errorCode);
  127. }
  128. }
  129. }
  130. override fun onCancelled() {
  131. loginTask = null
  132. }
  133. }
  134. }