2022-12-04 19:56:33 +00:00
|
|
|
export default defineNuxtRouteMiddleware(async (to, from) => {
|
2022-12-20 08:20:40 +00:00
|
|
|
if (process.server)
|
|
|
|
return
|
|
|
|
|
2022-12-20 15:56:54 +00:00
|
|
|
const masto = useMasto()
|
|
|
|
|
2022-12-04 19:56:33 +00:00
|
|
|
// Skip running middleware before masto has been initialised
|
2022-12-20 15:56:54 +00:00
|
|
|
if (!masto)
|
2022-12-04 19:56:33 +00:00
|
|
|
return
|
|
|
|
|
|
|
|
if (!('server' in to.params))
|
|
|
|
return
|
|
|
|
|
2022-12-11 23:30:26 +00:00
|
|
|
const user = currentUser.value
|
|
|
|
|
|
|
|
if (!user) {
|
2022-12-04 19:56:33 +00:00
|
|
|
if (from.params.server !== to.params.server) {
|
2022-12-20 15:56:54 +00:00
|
|
|
await masto.loginTo({
|
2022-12-04 19:56:33 +00:00
|
|
|
server: to.params.server as string,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// No need to additionally resolve an id if we're already logged in
|
2022-12-11 23:30:26 +00:00
|
|
|
if (user.server === to.params.server)
|
2022-12-04 19:56:33 +00:00
|
|
|
return
|
|
|
|
|
|
|
|
// Tags don't need to be redirected to a local id
|
|
|
|
if (to.params.tag)
|
|
|
|
return
|
|
|
|
|
|
|
|
// Handle redirecting to new permalink structure for users with old links
|
|
|
|
if (!to.params.server) {
|
|
|
|
return {
|
|
|
|
...to,
|
|
|
|
params: {
|
|
|
|
...to.params,
|
2022-12-11 23:30:26 +00:00
|
|
|
server: user.server,
|
2022-12-04 19:56:33 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
2022-12-11 23:30:26 +00:00
|
|
|
// If we're already on an account page, we can search for this on the new instance
|
2022-12-14 20:57:15 +00:00
|
|
|
if (to.params.account && to.name !== 'status' && to.params.account.includes('@')) {
|
2022-12-11 23:30:26 +00:00
|
|
|
const account = await fetchAccountByHandle(to.params.account as string)
|
|
|
|
if (account)
|
|
|
|
return getAccountRoute(account)
|
|
|
|
}
|
|
|
|
|
2022-12-20 08:20:40 +00:00
|
|
|
if (!masto.loggedIn.value)
|
|
|
|
await masto.loginTo(currentUser.value)
|
|
|
|
|
2022-12-04 19:56:33 +00:00
|
|
|
// If we're logged in, search for the local id the account or status corresponds to
|
2023-01-08 06:21:09 +00:00
|
|
|
const { value } = await masto.v2.search({ q: `https:/${to.fullPath}`, resolve: true, limit: 1 }).next()
|
2022-12-04 19:56:33 +00:00
|
|
|
|
|
|
|
const { accounts, statuses } = value
|
|
|
|
if (statuses[0])
|
|
|
|
return getStatusRoute(statuses[0])
|
|
|
|
|
|
|
|
if (accounts[0])
|
|
|
|
return getAccountRoute(accounts[0])
|
|
|
|
}
|
2023-01-12 05:39:22 +00:00
|
|
|
catch (err) {
|
|
|
|
console.error(err)
|
|
|
|
}
|
2022-12-04 19:56:33 +00:00
|
|
|
|
|
|
|
return '/home'
|
|
|
|
})
|