Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Unverified Commit 7a697508 authored by alperozturk's avatar alperozturk
Browse files

Move repository

parent 07310454
Loading
Loading
Loading
Loading
+0 −74
Original line number Diff line number Diff line
/*
 * Nextcloud Android client application
 *
 * @author Alper Ozturk
 * Copyright (C) 2024 Alper Ozturk
 * Copyright (C) 2024 Nextcloud GmbH
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

package com.nextcloud.operations.assistant

import android.content.Context
import com.nextcloud.common.User
import com.nextcloud.operations.assistant.model.CreatedTask
import com.nextcloud.operations.assistant.model.CreatedTaskData
import com.nextcloud.operations.assistant.model.TaskTypes
import com.owncloud.android.lib.common.network.NetworkManager
import org.json.JSONObject

class AssistantRepository(user: User, context: Context) :
    AssistantRepositoryType {
    private val operation = NetworkManager(user, context)

    override fun getTaskTypes(): TaskTypes? {
        return operation.get("/ocs/v2.php/textprocessing/tasktypes", TaskTypes::class.java)
    }

     // TODO Check return type
     override fun getTaskList(appId: String): TaskTypes? {
        return operation.get("/ocs/v2.php/textprocessing/tasks/app/$appId", TaskTypes::class.java)
    }

    // TODO Check return type
    override fun deleteTask(id: String): CreatedTask? {
        return operation.delete("/ocs/v2.php/textprocessing/task/$id", TaskTypes::class.java)
    }

    // TODO Check return type
    override fun getTask(id: String): CreatedTask? {
        return operation.get("/ocs/v2.php/textprocessing/task/$id", TaskTypes::class.java)
    }

    override fun createTask(
        input: String,
        type: String,
        appId: String,
        identifier: String,
    ): CreatedTask? {
        val json = JSONObject().apply {
            put("input", input)
            put("type", type)
            put("appId", appId)
            put("identifier", identifier)
        }

        return operation.post(
            "/ocs/v2.php/textprocessing/schedule",
            CreatedTask::class.java,
            json
        )
    }
}
+0 −42
Original line number Diff line number Diff line
/*
 * Nextcloud Android client application
 *
 * @author Alper Ozturk
 * Copyright (C) 2024 Alper Ozturk
 * Copyright (C) 2024 Nextcloud GmbH
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

package com.nextcloud.operations.assistant

import com.nextcloud.operations.assistant.model.CreatedTask
import com.nextcloud.operations.assistant.model.TaskTypes

interface AssistantRepositoryType {
    fun getTaskTypes(): TaskTypes?

    fun getTask(id: String): CreatedTask?

    fun deleteTask(id: String): CreatedTask?

    fun getTaskList(appId: String): TaskTypes?

    fun createTask(
        input: String,
        type: String,
        appId: String = "assistant",
        identifier: String = ""
    ): CreatedTask?
}
+0 −150
Original line number Diff line number Diff line
/*
 * Nextcloud Android client application
 *
 * @author Alper Ozturk
 * Copyright (C) 2024 Alper Ozturk
 * Copyright (C) 2024 Nextcloud GmbH
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

package com.owncloud.android.lib.common.network

import android.content.Context
import com.google.gson.Gson
import com.nextcloud.common.NextcloudClient
import com.nextcloud.common.User
import com.owncloud.android.lib.common.OwnCloudClientFactory
import com.owncloud.android.lib.common.utils.Log_OC
import okhttp3.Headers
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.lang.reflect.Type

@Suppress("TooGenericExceptionCaught")
class NetworkManager(user: User, context: Context) {
    private val tag = "NetworkManager"

    private var client: NextcloudClient? = null

    init {
        try {
            client = OwnCloudClientFactory.createNextcloudClient(user, context)
        } catch (e: Throwable) {
            Log_OC.d(tag, "Error caught at creating NextCloud client")
        }
    }

    private val httpClient =
        OkHttpClient.Builder().addInterceptor(NetworkManagerInterceptor()).build()
    private val accessToken = client?.credentials
    private val gson = Gson()
    private val headers =
        Headers.Builder()
            .add("Accept", "application/json")
            .add("Authorization", "Bearer $accessToken")
            .add("ocs-apirequest", "true")
            .build()

    fun <T> get(
        endpoint: String,
        type: Type
    ): T? {
        if (client == null) {
            Log_OC.d(tag, "Trying to execute a remote operation with a null Nextcloud Client")
            return null
        }

        val url = "${client?.baseUri}$endpoint"

        val request =
            Request.Builder()
                .url(url)
                .headers(headers)
                .build()

        httpClient.newCall(request).execute().use { response ->
            if (!response.isSuccessful) {
                Log_OC.d(tag, "GET request couldn't fetched")
                return null
            }

            val json = response.body.string()
            Log_OC.d(tag, "GET response $endpoint: $json")
            return gson.fromJson(json, type)
        }
    }

    fun <T> delete(endpoint: String, type: Type): T? {
        if (client == null) {
            Log_OC.d(tag, "Trying to execute a remote operation with a null Nextcloud Client")
            return null
        }

        val url = "${client?.baseUri}$endpoint"

        val request = Request.Builder()
            .url(url)
            .delete()
            .headers(headers)
            .build()

        httpClient.newCall(request).execute().use { response ->
            if (!response.isSuccessful) {
                Log_OC.d(tag, "DELETE request couldn't be executed")
                return null
            }

            val json = response.body.string()
            Log_OC.d(tag, "DELETE response $endpoint: $json")
            return gson.fromJson(json, type)
        }
    }

    fun <T> post(
        endpoint: String,
        type: Type,
        json: JSONObject
    ): T? {
        if (client == null) {
            Log_OC.d(tag, "Trying to execute a remote operation with a null Nextcloud Client")
            return null
        }

        val url = "${client?.baseUri}$endpoint"

        val requestBody =
            json.toString().toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())

        val request = Request.Builder()
            .url(url)
            .headers(headers)
            .post(requestBody)
            .build()

        httpClient.newCall(request).execute().use { response ->
            if (!response.isSuccessful) {
                Log_OC.d(tag, "POST request couldn't fetched")
                return null
            }

            val json = response.body.string()
            Log_OC.d(tag, "POST response $endpoint: $json")
            return gson.fromJson(json, type)
        }
    }
}
+0 −6
Original line number Diff line number Diff line
@@ -50,9 +50,6 @@ public abstract class OCSRemoteOperation<T> extends RemoteOperation<T> {
        String response = method.getResponseBodyAsString();
        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(response);

        Gson gson = new Gson();

        return gson.fromJson(element, type.getType());
    }

@@ -60,9 +57,6 @@ public abstract class OCSRemoteOperation<T> extends RemoteOperation<T> {
        String response = method.getResponseBodyAsString();
        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(response);

        Gson gson = new Gson();

        return gson.fromJson(element, type.getType());
    }
}
+72 −0
Original line number Diff line number Diff line
@@ -19,55 +19,54 @@
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

package com.owncloud.android.lib.common.network
package com.owncloud.android.lib.resources.assistant

import com.google.gson.reflect.TypeToken
import com.nextcloud.common.NextcloudClient
import com.nextcloud.operations.GetMethod
import com.owncloud.android.lib.common.operations.RemoteOperationResult
import com.owncloud.android.lib.common.utils.Log_OC
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okio.Buffer
import java.io.IOException
import java.nio.charset.Charset
import com.owncloud.android.lib.ocs.ServerResponse
import com.owncloud.android.lib.resources.OCSRemoteOperation
import com.owncloud.android.lib.resources.assistant.model.TaskType
import org.apache.commons.httpclient.HttpStatus

class NetworkManagerInterceptor : Interceptor {

    private val tag = "NetworkManagerInterceptor"

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()

        Log_OC.d(tag, "Sending request: ${request.method} ${request.url}")

        logRequestBody(request)

        val response = chain.proceed(request)

        Log_OC.d(tag, "Received response: ${response.code} ${response.message} ${response.request.url}")

        logResponseBody(response)

        return response
class GetTaskTypesRemoteOperation : OCSRemoteOperation<List<TaskType>?>() {
    @Suppress("TooGenericExceptionCaught")
    override fun run(client: NextcloudClient): RemoteOperationResult<List<TaskType>?> {
        var result: RemoteOperationResult<List<TaskType>?>
        var getMethod: GetMethod? = null
        try {
            getMethod =
                GetMethod(client.baseUri.toString() + DIRECT_ENDPOINT + JSON_FORMAT, true)
            val status = client.execute(getMethod)
            if (status == HttpStatus.SC_OK) {
                val hoverCard: List<TaskType>? =
                    getServerResponse(
                        getMethod,
                        object : TypeToken<ServerResponse<List<TaskType>?>>() {}
                    )
                        .ocs.data
                result = RemoteOperationResult(true, getMethod)
                result.setResultData(hoverCard)
            } else {
                result = RemoteOperationResult(false, getMethod)
            }

    private fun logRequestBody(request: Request) {
        val requestBody = request.body ?: return
        val buffer = Buffer()
        requestBody.writeTo(buffer)
        val charset: Charset =
            requestBody.contentType()?.charset(Charset.forName("UTF-8")) ?: Charset.forName("UTF-8")

        Log_OC.d(tag, buffer.readString(charset))
        } catch (e: Exception) {
            result = RemoteOperationResult(e)
            Log_OC.e(
                TAG,
                "Get task types for user " + " failed: " + result.logMessage,
                result.exception
            )
        } finally {
            getMethod?.releaseConnection()
        }
        return result
    }

    private fun logResponseBody(response: Response) {
        val responseBody = response.body
        val source = responseBody.source()
        source.request(Long.MAX_VALUE)
        val buffer = source.buffer
        val charset: Charset = responseBody.contentType()?.charset(Charset.forName("UTF-8"))
            ?: Charset.forName("UTF-8")

        Log_OC.d(tag, buffer.clone().readString(charset))
    companion object {
        private val TAG = GetTaskTypesRemoteOperation::class.java.simpleName
        private const val DIRECT_ENDPOINT = "/ocs/v2.php/textprocessing/tasktypes"
    }
}
Loading