Welcome to mirror list, hosted at ThFree Co, Russian Federation.

OkHttpMethodBase.kt « common « nextcloud « com « java « main « src « library - github.com/nextcloud/android-library.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 16a71d730c9f14928686eaa7cbb9163035741fd2 (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
177
178
179
180
181
182
183
184
/* Nextcloud Android Library is available under MIT license
 *
 *   @author Tobias Kaminsky
 *   Copyright (C) 2019 Tobias Kaminsky
 *   Copyright (C) 2019 Nextcloud GmbH
 *
 *   Permission is hereby granted, free of charge, to any person obtaining a copy
 *   of this software and associated documentation files (the "Software"), to deal
 *   in the Software without restriction, including without limitation the rights
 *   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *   copies of the Software, and to permit persons to whom the Software is
 *   furnished to do so, subject to the following conditions:
 *
 *   The above copyright notice and this permission notice shall be included in
 *   all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 *   BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 *   ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 *   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *   THE SOFTWARE.
 *
 */

package com.nextcloud.common

import com.owncloud.android.lib.common.OwnCloudClientManagerFactory
import com.owncloud.android.lib.common.operations.RemoteOperation
import com.owncloud.android.lib.common.utils.Log_OC
import okhttp3.Headers
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

/**
 * Common base class for all new OkHttpMethods
 */
@Suppress("TooManyFunctions")
abstract class OkHttpMethodBase(
    var uri: String,
    private val useOcsApiRequestHeader: Boolean
) {
    companion object {
        const val UNKNOWN_STATUS_CODE: Int = -1
        const val USER_AGENT = "User-Agent"
        const val AUTHORIZATION = "Authorization"
    }

    private var response: Response? = null
    private var queryMap: Map<String, String> = HashMap()
    private val requestHeaders: MutableMap<String, String> = HashMap()
    private val requestBuilder: Request.Builder = Request.Builder()
    private var request: Request? = null

    init {
        requestHeaders["http.protocol.single-cookie-header"] = "true"
    }

    @Throws(IllegalStateException::class)
    private fun buildQueryParameter(): HttpUrl {
        val httpBuilder =
            uri.toHttpUrlOrNull()?.newBuilder() ?: throw IllegalStateException("Error")

        queryMap.forEach { (k, v) -> httpBuilder.addQueryParameter(k, v) }

        return httpBuilder.build()
    }

    /**
     * Set request headers completely replacing existing headers.
     * To clear request headers, call this method with empty list.
     *
     * @param headers List of header-value pairs
     */
    fun setRequestHeaders(vararg headers: Pair<String, String>) {
        requestHeaders.clear()
        requestHeaders.putAll(headers)
    }

    /**
     * Adds request header, overwriting any existing value.
     *
     * @param header HTTP request header name
     * @param value HTTP request header value
     */
    fun addRequestHeader(header: String, value: String) {
        requestHeaders[header] = value
    }

    fun setQueryString(params: Map<String, String>) {
        queryMap = params
    }

    fun getResponseBodyAsString(): String {
        return response?.body?.string() ?: ""
    }

    fun getResponseContentLength(): Long {
        return response?.body?.contentLength() ?: -1
    }

    fun releaseConnection() {
        response?.body?.close()
    }

    fun getStatusCode(): Int {
        return response?.code ?: UNKNOWN_STATUS_CODE
    }

    fun getStatusText(): String {
        return response?.message ?: ""
    }

    fun getResponseHeaders(): Headers {
        return response?.headers ?: Headers.Builder().build()
    }

    fun getResponseHeader(name: String): String? {
        return response?.header(name)
    }

    fun getRequestHeader(name: String): String {
        return request?.header(name) ?: ""
    }

    /**
     * Execute operation using nextcloud client.
     *
     * @return HTTP return code or [UNKNOWN_STATUS_CODE] in case of network error.
     */
    fun execute(nextcloudClient: NextcloudClient): Int {
        val temp = requestBuilder.url(buildQueryParameter())

        requestHeaders[AUTHORIZATION] = nextcloudClient.credentials
        requestHeaders[USER_AGENT] = OwnCloudClientManagerFactory.getUserAgent()
        requestHeaders.forEach { (name, value) -> temp.header(name, value) }

        if (useOcsApiRequestHeader) {
            temp.header(RemoteOperation.OCS_API_HEADER, RemoteOperation.OCS_API_HEADER_VALUE)
        }

        applyType(temp)

        val request = temp.build()

        try {
            response = nextcloudClient.client.newCall(request).execute()
        } catch (ex: IOException) {
            return UNKNOWN_STATUS_CODE
        }

        return if (nextcloudClient.followRedirects) {
            nextcloudClient.followRedirection(this).lastStatus
        } else {
            response?.code ?: UNKNOWN_STATUS_CODE
        }
    }

    fun execute(client: PlainClient): Int {
        val temp = requestBuilder.url(buildQueryParameter())

        requestHeaders[USER_AGENT] = OwnCloudClientManagerFactory.getUserAgent()
        requestHeaders.forEach { (name, value) -> temp.header(name, value) }

        applyType(temp)

        val request = temp.build()

        try {
            response = client.client.newCall(request).execute()
        } catch (ex: IOException) {
            Log_OC.e(this, "Error executing method", ex)
        }

        return response?.code ?: UNKNOWN_STATUS_CODE
    }

    abstract fun applyType(temp: Request.Builder)
}