Files
otunes/apps/mobile/lib/share-media-link.ts
T

59 lines
1.6 KiB
TypeScript

import { requireOptionalNativeModule } from "expo"
import * as Sharing from "expo-sharing"
import { Platform, Share } from "react-native"
import type { MediaShareContext } from "@/lib/media-links"
import { mediaShareUrl } from "@/lib/media-links"
import { showError } from "@/lib/toast"
const nativeShare = requireOptionalNativeModule<{
share: (url: string, artwork: string, title: string) => Promise<void>
}>("MediaLinkShare")
export async function shareMediaLink(
serverUrl: string,
share: MediaShareContext
) {
const url = mediaShareUrl(serverUrl, share)
try {
if (Platform.OS === "web") {
if (!(await Sharing.isAvailableAsync())) {
showError("Sharing is not available on this device")
return
}
await Sharing.shareAsync(url, { dialogTitle: share.title })
return
}
if (nativeShare) {
const type = share.type === "song" ? "album" : share.type
const id =
share.type === "album" || share.type === "song"
? share.albumId
: share.type === "artist"
? share.artistId
: share.isFavorites
? "favorites"
: share.playlistId
await nativeShare.share(
url,
`${serverUrl.replace(/\/+$/, "")}/api/${type}/${id}/cover?size=512`,
share.title
)
return
}
await Share.share(
Platform.OS === "ios"
? { url, title: share.title }
: { message: url, title: share.title }
)
} catch (error) {
if (error instanceof Error && /cancel/i.test(error.message)) {
return
}
showError(error instanceof Error ? error.message : "Failed to share link")
}
}