diff --git a/src/lib/adapters/NextcloudBookmarks.ts b/src/lib/adapters/NextcloudBookmarks.ts index 406ff70b57..af38857d00 100644 --- a/src/lib/adapters/NextcloudBookmarks.ts +++ b/src/lib/adapters/NextcloudBookmarks.ts @@ -1,6 +1,6 @@ // Nextcloud ADAPTER // All owncloud specifc stuff goes in here -import { Capacitor } from '@capacitor/core' +import { Capacitor, CapacitorHttp as Http } from '@capacitor/core' import Adapter from '../interfaces/Adapter' import HtmlSerializer from '../serializers/Html' import Logger from '../Logger' @@ -867,9 +867,6 @@ export default class NextcloudBookmarksAdapter implements Adapter, BulkImportRes const url = this.normalizeServerURL(this.server.url) + relUrl let res let timedOut = false - const authString = Base64.encode( - this.server.username + ':' + this.server.password - ) if (type && type.includes('application/json')) { body = JSON.stringify(body) @@ -881,6 +878,14 @@ export default class NextcloudBookmarksAdapter implements Adapter, BulkImportRes body = params.toString() } + if (Capacitor.getPlatform() !== 'web') { + return this.sendRequestNative(verb, url, type, body, returnRawResponse) + } + + const authString = Base64.encode( + this.server.username + ':' + this.server.password + ) + try { res = await this.fetchQueue.add(() => Promise.race([ @@ -964,4 +969,60 @@ export default class NextcloudBookmarksAdapter implements Adapter, BulkImportRes return res.status === 200 } + + private async sendRequestNative(verb: string, url: string, type: string, body: any, returnRawResponse: boolean) { + let res + let timedOut = false + const authString = Base64.encode( + this.server.username + ':' + this.server.password + ) + try { + res = await this.fetchQueue.add(() => + Promise.race([ + Http.request({ + url, + method: verb, + disableRedirects: !this.server.allowRedirects, + headers: { + ...(type && type !== 'multipart/form-data' && { 'Content-type': type }), + Authorization: 'Basic ' + authString, + }, + responseType: 'json', + ...(body && !['get', 'head'].includes(verb.toLowerCase()) && { data: body }), + }), + new Promise((resolve, reject) => + setTimeout(() => { + timedOut = true + reject(new RequestTimeoutError()) + }, TIMEOUT) + ), + ]) + ) + } catch (e) { + if (timedOut) throw e + console.log(e) + throw new NetworkError() + } + + if (res.status < 400 && res.status >= 300) { + throw new RedirectError() + } + + if (returnRawResponse) { + return res + } + + if (res.status === 401 || res.status === 403) { + throw new AuthenticationError() + } + if (res.status === 503 || res.status > 400) { + throw new HttpError(res.status, verb) + } + const json = res.data + if (json.status !== 'success') { + throw new Error('Nextcloud API error: \n' + JSON.stringify(json)) + } + + return json + } }