Disable CapacitorHttp and add plugin to replace axios calls #781

This commit is contained in:
advplyr 2023-09-15 17:35:44 -05:00
parent 27bbe40874
commit 57d1fbfa83
21 changed files with 142 additions and 62 deletions

View file

@ -5,7 +5,7 @@
"bundledWebRuntime": false, "bundledWebRuntime": false,
"plugins": { "plugins": {
"CapacitorHttp": { "CapacitorHttp": {
"enabled": true "enabled": false
} }
} }
} }

View file

@ -5,7 +5,7 @@
"bundledWebRuntime": false, "bundledWebRuntime": false,
"plugins": { "plugins": {
"CapacitorHttp": { "CapacitorHttp": {
"enabled": true "enabled": false
} }
} }
} }

View file

@ -139,8 +139,8 @@ export default {
async logout() { async logout() {
await this.$hapticsImpact() await this.$hapticsImpact()
if (this.user) { if (this.user) {
await this.$axios.$post('/logout').catch((error) => { await this.$nativeHttp.post('/logout').catch((error) => {
console.error(error) console.error('Failed to logout', error)
}) })
} }

View file

@ -166,7 +166,7 @@ export default {
const sfQueryString = this.currentSFQueryString ? this.currentSFQueryString + '&' : '' const sfQueryString = this.currentSFQueryString ? this.currentSFQueryString + '&' : ''
const fullQueryString = `?${sfQueryString}limit=${this.booksPerFetch}&page=${page}&minified=1&include=rssfeed,numEpisodesIncomplete` const fullQueryString = `?${sfQueryString}limit=${this.booksPerFetch}&page=${page}&minified=1&include=rssfeed,numEpisodesIncomplete`
const payload = await this.$axios.$get(`/api/libraries/${this.currentLibraryId}/${entityPath}${fullQueryString}`).catch((error) => { const payload = await this.$nativeHttp.get(`/api/libraries/${this.currentLibraryId}/${entityPath}${fullQueryString}`).catch((error) => {
console.error('failed to fetch books', error) console.error('failed to fetch books', error)
return null return null
}) })

View file

@ -58,24 +58,7 @@ export default {
return this._author.numBooks || 0 return this._author.numBooks || 0
} }
}, },
methods: { methods: {},
async searchAuthor() {
this.searching = true
var response = await this.$axios.$post(`/api/authors/${this.authorId}/match`, { q: this.name }).catch((error) => {
console.error('Failed', error)
return null
})
if (!response) {
this.$toast.error('Author not found')
} else if (response.updated) {
if (response.author.imagePath) this.$toast.success('Author was updated')
else this.$toast.success('Author was updated (no image found)')
} else {
this.$toast.info('No updates were made for Author')
}
this.searching = false
}
},
mounted() {} mounted() {}
} }
</script> </script>

View file

@ -77,6 +77,7 @@
<script> <script>
import { Dialog } from '@capacitor/dialog' import { Dialog } from '@capacitor/dialog'
import { CapacitorHttp } from '@capacitor/core'
export default { export default {
data() { data() {
@ -217,27 +218,57 @@ export default {
return null return null
} }
}, },
pingServerAddress(address, customHeaders) { async getRequest(url, headers, connectTimeout = 6000) {
const options = { timeout: 3000 } const options = {
if (customHeaders) { url,
options.headers = customHeaders headers,
connectTimeout
} }
return this.$axios const response = await CapacitorHttp.get(options)
.$get(`${address}/ping`, options) console.log('[ServerConnectForm] GET request response', response)
.then((data) => data.success) if (response.status >= 400) {
throw new Error(response.data)
} else {
return response.data
}
},
async postRequest(url, data, headers, connectTimeout = 6000) {
if (!headers) headers = {}
if (!headers['Content-Type'] && data) {
headers['Content-Type'] = 'application/json'
}
const options = {
url,
headers,
data,
connectTimeout
}
const response = await CapacitorHttp.post(options)
console.log('[ServerConnectForm] POST request response', response)
if (response.status >= 400) {
throw new Error(response.data)
} else {
return response.data
}
},
pingServerAddress(address, customHeaders) {
return this.getRequest(`${address}/ping`, customHeaders)
.then((data) => {
return data.success
})
.catch((error) => { .catch((error) => {
console.error('Server check failed', error) console.error('Server ping failed', error)
const errorMsg = error.message || error
this.error = 'Failed to ping server' this.error = 'Failed to ping server'
if (typeof errorMsg === 'string') {
this.error += ` (${errorMsg})`
}
return false return false
}) })
}, },
requestServerLogin() { requestServerLogin() {
const options = {} return this.postRequest(`${this.serverConfig.address}/login`, { username: this.serverConfig.username, password: this.password }, this.serverConfig.customHeaders, 20000)
if (this.serverConfig.customHeaders) {
options.headers = this.serverConfig.customHeaders
}
return this.$axios
.$post(`${this.serverConfig.address}/login`, { username: this.serverConfig.username, password: this.password }, options)
.then((data) => { .then((data) => {
if (!data.user) { if (!data.user) {
console.error(data.error) console.error(data.error)
@ -248,8 +279,11 @@ export default {
}) })
.catch((error) => { .catch((error) => {
console.error('Server auth failed', error) console.error('Server auth failed', error)
var errorMsg = error.response ? error.response.data || 'Unknown Error' : 'Unknown Error' const errorMsg = error.message || error
this.error = errorMsg this.error = 'Failed to login'
if (typeof errorMsg === 'string') {
this.error += ` (${errorMsg})`
}
return false return false
}) })
}, },
@ -330,12 +364,19 @@ export default {
this.error = null this.error = null
this.processing = true this.processing = true
var authRes = await this.$axios.$post(`${this.serverConfig.address}/api/authorize`, null, { headers: { Authorization: `Bearer ${this.serverConfig.token}` } }).catch((error) => {
console.error('[Server] Server auth failed', error) const authRes = await this.postRequest(`${this.serverConfig.address}/api/authorize`, null, { Authorization: `Bearer ${this.serverConfig.token}` }).catch((error) => {
var errorMsg = error.response ? error.response.data || 'Unknown Error' : 'Unknown Error' console.error('[ServerConnectForm] Server auth failed', error)
this.error = errorMsg const errorMsg = error.message || error
this.error = 'Failed to authorize'
if (typeof errorMsg === 'string') {
this.error += ` (${errorMsg})`
}
return false return false
}) })
console.log('[ServerConnectForm] authRes=', authRes)
this.processing = false this.processing = false
return authRes return authRes
}, },

View file

@ -183,7 +183,7 @@ export default {
// Update server item // Update server item
if (this.serverLibraryItemId) { if (this.serverLibraryItemId) {
this.$axios.$patch(`/api/me/progress/${this.serverLibraryItemId}`, payload).catch((error) => { this.$nativeHttp.patch(`/api/me/progress/${this.serverLibraryItemId}`, payload).catch((error) => {
console.error('ComicReader.updateProgress failed:', error) console.error('ComicReader.updateProgress failed:', error)
}) })
} }

View file

@ -171,7 +171,7 @@ export default {
// Update server item // Update server item
if (this.serverLibraryItemId) { if (this.serverLibraryItemId) {
this.$axios.$patch(`/api/me/progress/${this.serverLibraryItemId}`, payload).catch((error) => { this.$nativeHttp.patch(`/api/me/progress/${this.serverLibraryItemId}`, payload).catch((error) => {
console.error('EpubReader.updateProgress failed:', error) console.error('EpubReader.updateProgress failed:', error)
}) })
} }

View file

@ -146,7 +146,7 @@ export default {
// Update server item // Update server item
if (this.serverLibraryItemId) { if (this.serverLibraryItemId) {
this.$axios.$patch(`/api/me/progress/${this.serverLibraryItemId}`, payload).catch((error) => { this.$nativeHttp.patch(`/api/me/progress/${this.serverLibraryItemId}`, payload).catch((error) => {
console.error('PdfReader.updateProgress failed:', error) console.error('PdfReader.updateProgress failed:', error)
}) })
} }

View file

@ -230,7 +230,7 @@ export default {
return this.$toast.error('Podcast does not have an RSS Feed') return this.$toast.error('Podcast does not have an RSS Feed')
} }
this.fetchingRSSFeed = true this.fetchingRSSFeed = true
const payload = await this.$axios.$post(`/api/podcasts/feed`, { rssFeed: this.mediaMetadata.feedUrl }).catch((error) => { const payload = await this.$nativeHttp.post(`/api/podcasts/feed`, { rssFeed: this.mediaMetadata.feedUrl }).catch((error) => {
console.error('Failed to get feed', error) console.error('Failed to get feed', error)
this.$toast.error('Failed to get podcast feed') this.$toast.error('Failed to get podcast feed')
return null return null

View file

@ -5,7 +5,7 @@
"bundledWebRuntime": false, "bundledWebRuntime": false,
"plugins": { "plugins": {
"CapacitorHttp": { "CapacitorHttp": {
"enabled": true "enabled": false
} }
} }
} }

View file

@ -15,6 +15,8 @@
</template> </template>
<script> <script>
import { CapacitorHttp } from '@capacitor/core'
export default { export default {
data() { data() {
return { return {
@ -97,6 +99,21 @@ export default {
await this.$store.dispatch('user/loadUserSettings') await this.$store.dispatch('user/loadUserSettings')
}, },
async postRequest(url, data, headers, connectTimeout = 30000) {
const options = {
url,
headers,
data,
connectTimeout
}
const response = await CapacitorHttp.post(options)
console.log('[default] POST request response', response)
if (response.status >= 400) {
throw new Error(response.data)
} else {
return response.data
}
},
async attemptConnection() { async attemptConnection() {
console.warn('[default] attemptConnection') console.warn('[default] attemptConnection')
if (!this.networkConnected) { if (!this.networkConnected) {
@ -126,10 +143,8 @@ export default {
console.log(`[default] Got server config, attempt authorize ${serverConfig.address}`) console.log(`[default] Got server config, attempt authorize ${serverConfig.address}`)
const authRes = await this.$axios.$post(`${serverConfig.address}/api/authorize`, null, { headers: { Authorization: `Bearer ${serverConfig.token}` }, timeout: 3000 }).catch((error) => { const authRes = await this.postRequest(`${serverConfig.address}/api/authorize`, null, { Authorization: `Bearer ${serverConfig.token}` }, 10000).catch((error) => {
console.error('[Server] Server auth failed', error) console.error('[default] Server auth failed', error)
const errorMsg = error.response ? error.response.data || 'Unknown Error' : 'Unknown Error'
this.error = errorMsg
return false return false
}) })
if (!authRes) { if (!authRes) {

View file

@ -44,6 +44,7 @@ export default {
'@/plugins/localStore.js', '@/plugins/localStore.js',
'@/plugins/init.client.js', '@/plugins/init.client.js',
'@/plugins/axios.js', '@/plugins/axios.js',
'@/plugins/nativeHttp.js',
'@/plugins/capacitor/index.js', '@/plugins/capacitor/index.js',
'@/plugins/capacitor/AbsAudioPlayer.js', '@/plugins/capacitor/AbsAudioPlayer.js',
'@/plugins/toast.js', '@/plugins/toast.js',

View file

@ -49,7 +49,7 @@ export default {
async logout() { async logout() {
await this.$hapticsImpact() await this.$hapticsImpact()
if (this.user) { if (this.user) {
await this.$axios.$post('/logout').catch((error) => { await this.$nativeHttp.post('/logout').catch((error) => {
console.error(error) console.error(error)
}) })
} }

View file

@ -236,7 +236,7 @@ export default {
console.log('[categories] Local shelves set', this.shelves.length, this.lastLocalFetch) console.log('[categories] Local shelves set', this.shelves.length, this.lastLocalFetch)
if (isConnectedToServerWithInternet) { if (isConnectedToServerWithInternet) {
const categories = await this.$axios.$get(`/api/libraries/${this.currentLibraryId}/personalized?minified=1&include=rssfeed,numEpisodesIncomplete`).catch((error) => { const categories = await this.$nativeHttp.get(`/api/libraries/${this.currentLibraryId}/personalized?minified=1&include=rssfeed,numEpisodesIncomplete`).catch((error) => {
console.error('[categories] Failed to fetch categories', error) console.error('[categories] Failed to fetch categories', error)
return [] return []
}) })

View file

@ -29,7 +29,7 @@ export default {
}, },
methods: { methods: {
async addEpisodeToPlaylist(episode) { async addEpisodeToPlaylist(episode) {
const libraryItem = await this.$axios.$get(`/api/items/${episode.libraryItemId}`).catch((error) => { const libraryItem = await this.$nativeHttp.get(`/api/items/${episode.libraryItemId}`).catch((error) => {
console.error('Failed to get library item', error) console.error('Failed to get library item', error)
this.$toast.error('Failed to get library item') this.$toast.error('Failed to get library item')
return null return null
@ -42,7 +42,7 @@ export default {
async loadRecentEpisodes(page = 0) { async loadRecentEpisodes(page = 0) {
this.loadedLibraryId = this.currentLibraryId this.loadedLibraryId = this.currentLibraryId
this.processing = true this.processing = true
const episodePayload = await this.$axios.$get(`/api/libraries/${this.currentLibraryId}/recent-episodes?limit=25&page=${page}`).catch((error) => { const episodePayload = await this.$nativeHttp.get(`/api/libraries/${this.currentLibraryId}/recent-episodes?limit=25&page=${page}`).catch((error) => {
console.error('Failed to get recent episodes', error) console.error('Failed to get recent episodes', error)
this.$toast.error('Failed to get recent episodes') this.$toast.error('Failed to get recent episodes')
return null return null

View file

@ -88,7 +88,7 @@ export default {
}, },
async checkRSSFeed(rssFeed) { async checkRSSFeed(rssFeed) {
this.processing = true this.processing = true
var payload = await this.$axios.$post(`/api/podcasts/feed`, { rssFeed }).catch((error) => { var payload = await this.$nativeHttp.post(`/api/podcasts/feed`, { rssFeed }).catch((error) => {
console.error('Failed to get feed', error) console.error('Failed to get feed', error)
this.$toast.error('Failed to get podcast feed') this.$toast.error('Failed to get podcast feed')
return null return null
@ -103,7 +103,7 @@ export default {
async submitSearch(term) { async submitSearch(term) {
this.processing = true this.processing = true
this.termSearched = '' this.termSearched = ''
const results = await this.$axios.$get(`/api/search/podcast?term=${encodeURIComponent(term)}`).catch((error) => { const results = await this.$nativeHttp.get(`/api/search/podcast?term=${encodeURIComponent(term)}`).catch((error) => {
console.error('Search request failed', error) console.error('Search request failed', error)
return [] return []
}) })
@ -119,7 +119,7 @@ export default {
return return
} }
this.processing = true this.processing = true
const payload = await this.$axios.$post(`/api/podcasts/feed`, { rssFeed: podcast.feedUrl }).catch((error) => { const payload = await this.$nativeHttp.post(`/api/podcasts/feed`, { rssFeed: podcast.feedUrl }).catch((error) => {
console.error('Failed to get feed', error) console.error('Failed to get feed', error)
this.$toast.error('Failed to get podcast feed') this.$toast.error('Failed to get podcast feed')
return null return null

View file

@ -503,7 +503,7 @@ export default {
const updatePayload = { const updatePayload = {
isFinished: !this.userIsFinished isFinished: !this.userIsFinished
} }
this.$axios.$patch(`/api/me/progress/${this.libraryItemId}/${this.episode.id}`, updatePayload).catch((error) => { this.$nativeHttp.patch(`/api/me/progress/${this.libraryItemId}/${this.episode.id}`, updatePayload).catch((error) => {
console.error('Failed', error) console.error('Failed', error)
this.$toast.error(`Failed to mark as ${updatePayload.isFinished ? 'Finished' : 'Not Finished'}`) this.$toast.error(`Failed to mark as ${updatePayload.isFinished ? 'Finished' : 'Not Finished'}`)
}) })

View file

@ -100,7 +100,7 @@ export default {
return return
} }
this.isFetching = true this.isFetching = true
const results = await this.$axios.$get(`/api/libraries/${this.currentLibraryId}/search?q=${value}&limit=5`).catch((error) => { const results = await this.$nativeHttp.get(`/api/libraries/${this.currentLibraryId}/search?q=${value}&limit=5`).catch((error) => {
console.error('Search error', error) console.error('Search error', error)
return null return null
}) })

View file

@ -99,7 +99,7 @@ export default {
}, },
methods: { methods: {
async init() { async init() {
this.listeningStats = await this.$axios.$get(`/api/me/listening-stats`).catch((err) => { this.listeningStats = await this.$nativeHttp.get(`/api/me/listening-stats`).catch((err) => {
console.error('Failed to load listening sesions', err) console.error('Failed to load listening sesions', err)
return [] return []
}) })

40
plugins/nativeHttp.js Normal file
View file

@ -0,0 +1,40 @@
import { CapacitorHttp } from '@capacitor/core'
export default function ({ store }, inject) {
const nativeHttp = {
request(method, _url, data, options = {}) {
let url = _url
const headers = {}
if (!url.startsWith('http') && !url.startsWith('capacitor')) {
const bearerToken = store.getters['user/getToken']
if (bearerToken) {
headers['Authorization'] = `Bearer ${bearerToken}`
} else {
console.warn('[nativeHttp] No Bearer Token for request')
}
const serverUrl = store.getters['user/getServerAddress']
if (serverUrl) {
url = `${serverUrl}${url}`
}
}
console.log(`[nativeHttp] Making ${method} request to ${url}`)
return CapacitorHttp.request({
method,
url,
data,
headers,
...options
}).then(res => res.data)
},
get(url, options = {}) {
return this.request('GET', url, undefined, options)
},
post(url, data, options = {}) {
return this.request('POST', url, data, options)
},
patch(url, data, options = {}) {
return this.request('PATCH', url, data, options)
}
}
inject('nativeHttp', nativeHttp)
}