TagSpaces is an offline, open source, document manager with tagging support
feat: add IAP purchase functionality for the iOS and Android apps
Ilian Sapundshiev39de58bfaf22
diff --git a/README.md b/README.mdindex 5ffabc7bd..43de467f3 100644--- a/README.md+++ b/README.md@@ -155,7 +155,7 @@ We welcome contributions! Please review and sign the [Contributor License Agreem## 🌍 Localization-TagSpaces is available in over 20 languages. Help us translate the app by joining our team on [Transifex](https://www.transifex.com/tagspaces/tagspaces/).+TagSpaces is available in over 20 languages. Help us translate the app by joining our team on [Transifex](https://explore.transifex.com/tagspaces/tagspaces/).## 💡 Ideas & Suggestionsdiff --git a/assets/links.ts b/assets/links.tsindex 53cfd9572..025071e18 100644--- a/assets/links.ts+++ b/assets/links.ts@@ -48,7 +48,7 @@ const Links = {suggestFeature: 'https://tagspaces.discourse.group/c/feature-requests/6',forumsUrl: 'https://tagspaces.discourse.group',reportIssue: 'https://github.com/tagspaces/tagspaces/issues/',- helpTranslating: 'https://www.transifex.com/tagspaces/tagspaces/',+ helpTranslating: 'https://explore.transifex.com/tagspaces/tagspaces/',webClipperChrome:'https://chrome.google.com/webstore/detail/tagspaces-web-clipper/ldalmgifdlgpiiadeccbcjojljeanhjk',webClipperFirefox:diff --git a/capacitor/android/app/capacitor.build.gradle b/capacitor/android/app/capacitor.build.gradleindex dc6f9e781..b6f137d25 100644--- a/capacitor/android/app/capacitor.build.gradle+++ b/capacitor/android/app/capacitor.build.gradle@@ -20,6 +20,7 @@ dependencies {implementation project(':capacitor-splash-screen')implementation project(':capacitor-status-bar')implementation project(':capawesome-capacitor-file-picker')+ implementation project(':capacitor-plugin-cdv-purchase')}diff --git a/capacitor/android/capacitor.settings.gradle b/capacitor/android/capacitor.settings.gradleindex be855530e..fbe557b21 100644--- a/capacitor/android/capacitor.settings.gradle+++ b/capacitor/android/capacitor.settings.gradle@@ -34,3 +34,6 @@ project(':capacitor-status-bar').projectDir = new File('../node_modules/@capacitinclude ':capawesome-capacitor-file-picker'project(':capawesome-capacitor-file-picker').projectDir = new File('../node_modules/@capawesome/capacitor-file-picker/android')++include ':capacitor-plugin-cdv-purchase'+project(':capacitor-plugin-cdv-purchase').projectDir = new File('../node_modules/capacitor-plugin-cdv-purchase/android')diff --git a/capacitor/ios/App/App.xcodeproj/project.pbxproj b/capacitor/ios/App/App.xcodeproj/project.pbxprojindex 7e1edb9d4..d2d67cd72 100644--- a/capacitor/ios/App/App.xcodeproj/project.pbxproj+++ b/capacitor/ios/App/App.xcodeproj/project.pbxproj@@ -319,7 +319,7 @@CODE_SIGN_ENTITLEMENTS = App/App.entitlements;CODE_SIGN_IDENTITY = "Apple Development";CODE_SIGN_STYLE = Automatic;- CURRENT_PROJECT_VERSION = 10265;+ CURRENT_PROJECT_VERSION = 10272;DEVELOPMENT_TEAM = DLK22E2679;INFOPLIST_FILE = App/Info.plist;IPHONEOS_DEPLOYMENT_TARGET = 15.0;@@ -327,7 +327,7 @@"$(inherited)","@executable_path/Frameworks",);- MARKETING_VERSION = 6.13.1;+ MARKETING_VERSION = 6.13.2;OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\"";PRODUCT_BUNDLE_IDENTIFIER = org.tagspaces.mobileapp;PRODUCT_NAME = TagSpaces;@@ -345,7 +345,7 @@CODE_SIGN_ENTITLEMENTS = App/App.entitlements;CODE_SIGN_IDENTITY = "Apple Development";CODE_SIGN_STYLE = Automatic;- CURRENT_PROJECT_VERSION = 10265;+ CURRENT_PROJECT_VERSION = 10272;DEVELOPMENT_TEAM = DLK22E2679;INFOPLIST_FILE = App/Info.plist;IPHONEOS_DEPLOYMENT_TARGET = 15.0;@@ -353,7 +353,7 @@"$(inherited)","@executable_path/Frameworks",);- MARKETING_VERSION = 6.13.1;+ MARKETING_VERSION = 6.13.2;PRODUCT_BUNDLE_IDENTIFIER = org.tagspaces.mobileapp;PRODUCT_NAME = TagSpaces;PROVISIONING_PROFILE_SPECIFIER = "";diff --git a/capacitor/ios/App/CapApp-SPM/Package.swift b/capacitor/ios/App/CapApp-SPM/Package.swiftindex cb639d37e..e24be5abd 100644--- a/capacitor/ios/App/CapApp-SPM/Package.swift+++ b/capacitor/ios/App/CapApp-SPM/Package.swift@@ -21,7 +21,8 @@ let package = Package(.package(name: "CapacitorShare", path: "../../../node_modules/@capacitor/share"),.package(name: "CapacitorSplashScreen", path: "../../../node_modules/@capacitor/splash-screen"),.package(name: "CapacitorStatusBar", path: "../../../node_modules/@capacitor/status-bar"),- .package(name: "CapawesomeCapacitorFilePicker", path: "../../../node_modules/@capawesome/capacitor-file-picker")+ .package(name: "CapawesomeCapacitorFilePicker", path: "../../../node_modules/@capawesome/capacitor-file-picker"),+ .package(name: "CapacitorPluginCdvPurchase", path: "../../../node_modules/capacitor-plugin-cdv-purchase")],targets: [.target(@@ -38,7 +39,8 @@ let package = Package(.product(name: "CapacitorShare", package: "CapacitorShare"),.product(name: "CapacitorSplashScreen", package: "CapacitorSplashScreen"),.product(name: "CapacitorStatusBar", package: "CapacitorStatusBar"),- .product(name: "CapawesomeCapacitorFilePicker", package: "CapawesomeCapacitorFilePicker")+ .product(name: "CapawesomeCapacitorFilePicker", package: "CapawesomeCapacitorFilePicker"),+ .product(name: "CapacitorPluginCdvPurchase", package: "CapacitorPluginCdvPurchase")])]diff --git a/capacitor/package-lock.json b/capacitor/package-lock.jsonindex a706f99e7..973abc37e 100644--- a/capacitor/package-lock.json+++ b/capacitor/package-lock.json@@ -23,7 +23,8 @@"@capacitor/share": "^8.0.1","@capacitor/splash-screen": "^8.0.1","@capacitor/status-bar": "^8.0.2",- "@capawesome/capacitor-file-picker": "^8.0.2"+ "@capawesome/capacitor-file-picker": "^8.0.2",+ "capacitor-plugin-cdv-purchase": "^13.17.1"}},"node_modules/@anuradev/capacitor-background-mode": {@@ -504,6 +505,15 @@"node": "*"}},+ "node_modules/capacitor-plugin-cdv-purchase": {+ "version": "13.17.1",+ "resolved": "https://registry.npmjs.org/capacitor-plugin-cdv-purchase/-/capacitor-plugin-cdv-purchase-13.17.1.tgz",+ "integrity": "sha512-HRfjSrepv1ElXCw/zA933s0LMOkcVO2c/NGxR64wf7G5lAjHM2E2LLf2fRSVhOeF9jORoZsZzmoLqlr7/DVGdg==",+ "license": "MIT",+ "peerDependencies": {+ "@capacitor/core": "^6.0.0 || ^7.0.0 || ^8.0.0"+ }+ },"node_modules/chownr": {"version": "3.0.0","resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz",diff --git a/capacitor/package.json b/capacitor/package.jsonindex d1d88259b..f6df5e286 100644--- a/capacitor/package.json+++ b/capacitor/package.json@@ -25,6 +25,7 @@"@capacitor/share": "^8.0.1","@capacitor/splash-screen": "^8.0.1","@capacitor/status-bar": "^8.0.2",- "@capawesome/capacitor-file-picker": "^8.0.2"+ "@capawesome/capacitor-file-picker": "^8.0.2",+ "capacitor-plugin-cdv-purchase": "^13.17.1"}}diff --git a/package-lock.json b/package-lock.jsonindex 116f212a6..d04c4822c 100644--- a/package-lock.json+++ b/package-lock.json@@ -37,6 +37,7 @@"@tagspaces/tagspaces-common-cordova": "4.8.7","@tagspaces/tagspaces-indexer": "4.8.7","@tagspaces/tagspaces-search": "4.8.7",+ "capacitor-plugin-cdv-purchase": "13.17.1","coordinate-parser": "1.0.7","crypto-js": "4.2.0","date-fns": "4.1.0",@@ -12605,6 +12606,15 @@],"license": "CC-BY-4.0"},+ "node_modules/capacitor-plugin-cdv-purchase": {+ "version": "13.17.1",+ "resolved": "https://registry.npmjs.org/capacitor-plugin-cdv-purchase/-/capacitor-plugin-cdv-purchase-13.17.1.tgz",+ "integrity": "sha512-HRfjSrepv1ElXCw/zA933s0LMOkcVO2c/NGxR64wf7G5lAjHM2E2LLf2fRSVhOeF9jORoZsZzmoLqlr7/DVGdg==",+ "license": "MIT",+ "peerDependencies": {+ "@capacitor/core": "^6.0.0 || ^7.0.0 || ^8.0.0"+ }+ },"node_modules/ccount": {"version": "2.0.1","resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz",diff --git a/package.json b/package.jsonindex bfccb87c9..1b38d8c2a 100644--- a/package.json+++ b/package.json@@ -195,6 +195,7 @@"@tagspaces/tagspaces-common-cordova": "4.8.7","@tagspaces/tagspaces-indexer": "4.8.7","@tagspaces/tagspaces-search": "4.8.7",+ "capacitor-plugin-cdv-purchase": "13.17.1","coordinate-parser": "1.0.7","crypto-js": "4.2.0","date-fns": "4.1.0",diff --git a/src/renderer/components/dialogs/BuyProDialog.tsx b/src/renderer/components/dialogs/BuyProDialog.tsxnew file mode 100644index 000000000..00368d041--- /dev/null+++ b/src/renderer/components/dialogs/BuyProDialog.tsx@@ -0,0 +1,261 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2017-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * 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/>.+ *+ */++// In-app purchase sheet for the Capacitor mobile apps. Shown when the+// user taps "Compare and Upgrade" inside the ProTeaserDialog on iOS or+// Android. Drives the StoreKit / Play Billing purchase via the iap+// service. Both stores forbid linking out from the purchase flow, so+// this sheet replaces the external URL CTA used on desktop.++import AppConfig from '-/AppConfig';+import TsButton from '-/components/TsButton';+import TsDialogTitle from '-/components/dialogs/components/TsDialogTitle';+import {+ getProProduct,+ IAPProduct,+ isIapAvailable,+ purchasePro,+ restoreProPurchase,+} from '-/services/iap';+import { openURLExternally } from '-/services/utils-io';+import {+ Alert,+ Box,+ CircularProgress,+ Dialog,+ DialogActions,+ DialogContent,+ Link,+ Stack,+ Typography,+} from '@mui/material';+import { useTheme } from '@mui/material/styles';+import useMediaQuery from '@mui/material/useMediaQuery';+import Links from 'assets/links';+import React, { useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++interface Props {+ open: boolean;+ onClose: () => void;+}++function BuyProDialog(props: Props) {+ const { open, onClose } = props;+ const { t } = useTranslation();+ const theme = useTheme();+ const smallScreen = useMediaQuery(theme.breakpoints.down('md'));++ const [product, setProduct] = useState<IAPProduct | null>(null);+ const [loadingProduct, setLoadingProduct] = useState<boolean>(false);+ const [purchaseInFlight, setPurchaseInFlight] = useState<boolean>(false);+ const [restoreInFlight, setRestoreInFlight] = useState<boolean>(false);+ const [statusMessage, setStatusMessage] = useState<{+ kind: 'info' | 'error' | 'success';+ text: string;+ } | null>(null);++ useEffect(() => {+ if (!open) return;+ if (!isIapAvailable()) return;+ let cancelled = false;+ setLoadingProduct(true);+ setStatusMessage(null);+ getProProduct()+ .then((p) => {+ if (cancelled) return;+ setProduct(p);+ })+ .catch(() => {+ if (cancelled) return;+ setProduct(null);+ })+ .finally(() => {+ if (cancelled) return;+ setLoadingProduct(false);+ });+ return () => {+ cancelled = true;+ };+ }, [open]);++ async function onBuyClick() {+ setPurchaseInFlight(true);+ setStatusMessage(null);+ try {+ const result = await purchasePro();+ if (result.success) {+ setStatusMessage({+ kind: 'success',+ text: t('core:purchaseCompleteReloading'),+ });+ // The verify→finish listener in iap.ts triggers a reload shortly.+ return;+ }+ if (result.cancelled) {+ setStatusMessage(null);+ return;+ }+ setStatusMessage({+ kind: 'error',+ text: result.error ?? t('core:purchaseFailed'),+ });+ } finally {+ setPurchaseInFlight(false);+ }+ }++ async function onRestoreClick() {+ setRestoreInFlight(true);+ setStatusMessage(null);+ try {+ const result = await restoreProPurchase();+ if (result.restored) {+ setStatusMessage({+ kind: 'success',+ text: t('core:restoreCompleteReloading'),+ });+ return;+ }+ setStatusMessage({+ kind: 'info',+ text: t('core:noPurchaseFoundToRestore'),+ });+ } finally {+ setRestoreInFlight(false);+ }+ }++ const priceLine =+ product?.price ||+ (loadingProduct ? t('core:loading') : t('core:priceUnavailable'));++ return (+ <Dialog+ open={open}+ onClose={purchaseInFlight ? undefined : onClose}+ fullScreen={smallScreen}+ keepMounted+ scroll="paper"+ aria-labelledby="buy-pro-dialog-title"+ >+ <TsDialogTitle+ dialogTitle={t('core:tagSpacesPro')}+ closeButtonTestId="closeBuyProDialogTID"+ onClose={purchaseInFlight ? undefined : onClose}+ />+ <DialogContent>+ <Stack spacing={2} sx={{ paddingTop: 1 }}>+ <Typography variant="body1">{t('core:buyProSubtitle')}</Typography>++ <Box+ sx={{+ borderRadius: AppConfig.defaultCSSRadius + 'px',+ border: '1px solid',+ borderColor: 'divider',+ padding: 2,+ }}+ >+ <Typography variant="body2">+ {t('core:buyProFeaturesList')}+ </Typography>+ </Box>++ <Box+ sx={{+ textAlign: 'center',+ paddingTop: 1,+ }}+ >+ <Typography variant="h4" data-tid="buyProPriceTID">+ {priceLine}+ </Typography>+ <Typography variant="caption" color="text.secondary">+ {t('core:oneTimePurchase')}+ </Typography>+ </Box>++ {statusMessage && (+ <Alert severity={statusMessage.kind}>{statusMessage.text}</Alert>+ )}++ <Typography+ variant="caption"+ color="text.secondary"+ sx={{ textAlign: 'center' }}+ >+ {t('core:familySharingNote')}{' '}+ <Link+ component="button"+ type="button"+ onClick={() => openURLExternally(Links.links.privacyURL, true)}+ underline="hover"+ >+ {t('core:privacyPolicy')}+ </Link>+ </Typography>+ </Stack>+ </DialogContent>+ <DialogActions+ sx={{+ // env(safe-area-inset-*) keeps buttons clear of the iPhone home+ // indicator and Android gesture-nav strip on fullScreen mobile.+ paddingLeft: 'max(16px, env(safe-area-inset-left))',+ paddingRight: 'max(16px, env(safe-area-inset-right))',+ paddingTop: 1,+ paddingBottom: 'max(16px, env(safe-area-inset-bottom))',+ borderTop: '1px solid',+ borderColor: 'divider',+ gap: 1,+ flexDirection: 'column',+ alignItems: 'stretch',+ }}+ >+ <TsButton+ data-tid="buyProConfirmTID"+ variant="contained"+ onClick={onBuyClick}+ disabled={+ purchaseInFlight || restoreInFlight || loadingProduct || !product+ }+ sx={{ minHeight: 48 }}+ >+ {purchaseInFlight ? (+ <CircularProgress size={20} />+ ) : (+ t('core:buyProAction', { price: product?.price ?? '' })+ )}+ </TsButton>+ <TsButton+ data-tid="buyProRestoreTID"+ variant="text"+ onClick={onRestoreClick}+ disabled={purchaseInFlight || restoreInFlight}+ >+ {restoreInFlight ? (+ <CircularProgress size={18} />+ ) : (+ t('core:restorePurchases')+ )}+ </TsButton>+ </DialogActions>+ </Dialog>+ );+}++export default BuyProDialog;diff --git a/src/renderer/components/dialogs/ProTeaserDialog.tsx b/src/renderer/components/dialogs/ProTeaserDialog.tsxindex b88a2e348..a9d313df7 100644--- a/src/renderer/components/dialogs/ProTeaserDialog.tsx+++ b/src/renderer/components/dialogs/ProTeaserDialog.tsx@@ -20,6 +20,7 @@ import AppConfig from '-/AppConfig';import DraggablePaper from '-/components/DraggablePaper';import TsButton from '-/components/TsButton';import TsDialogTitle from '-/components/dialogs/components/TsDialogTitle';+import { BuyProDialogContext } from '-/components/dialogs/hooks/BuyProDialogContextProvider';import { getProTeaserSlides } from '-/content/ProTeaserSlides';import { openURLExternally } from '-/services/utils-io';import { Box, ButtonGroup } from '@mui/material';@@ -31,7 +32,7 @@ import Typography from '@mui/material/Typography';import { useTheme } from '@mui/material/styles';import useMediaQuery from '@mui/material/useMediaQuery';import Links from 'assets/links';-import React, { useEffect, useRef, useState } from 'react';+import React, { useContext, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { Pagination } from 'swiper/modules';import { Swiper, SwiperSlide } from 'swiper/react';@@ -69,6 +70,18 @@ function Slide(props: SlideProps) {pictureShadow,} = props;const { t } = useTranslation();+ const { openBuyProDialog } = useContext(BuyProDialogContext);++ // On Capacitor mobile (App Store / Play) we cannot link out to an+ // external upgrade page from the purchase CTA — both stores reject+ // builds that do. Route to the in-app StoreKit / Play Billing sheet+ // via BuyProDialog instead. Desktop and web keep the external link.+ const onUpgradeClick = AppConfig.isCapacitor+ ? () => openBuyProDialog?.()+ : () => openURLExternally(Links.links.productsOverview, true);+ const onCtaClick = AppConfig.isCapacitor+ ? () => openBuyProDialog?.()+ : () => openURLExternally(ctaURL, true);return (<Box@@ -96,8 +109,9 @@ function Slide(props: SlideProps) {{pictureURL && (<ahref="#"- onClick={() => {- openURLExternally(ctaURL, true);+ onClick={(e) => {+ e.preventDefault();+ onCtaClick();}}style={{paddingTop: 15,@@ -134,18 +148,12 @@ function Slide(props: SlideProps) {<br /><Box sx={{ whiteSpace: 'nowrap' }}><ButtonGroup>- <TsButton- onClick={() => {- openURLExternally(Links.links.productsOverview, true);- }}- >+ <TsButton onClick={onUpgradeClick}>{t('core:compareAndUpgrade')}</TsButton>{ctaTitle && (<TsButton- onClick={() => {- openURLExternally(ctaURL, true);- }}+ onClick={onCtaClick}sx={{ marginLeft: AppConfig.defaultSpaceBetweenButtons }}>{ctaTitle}diff --git a/src/renderer/components/dialogs/components/SettingsGeneral.tsx b/src/renderer/components/dialogs/components/SettingsGeneral.tsxindex 735079b55..e2061881f 100644--- a/src/renderer/components/dialogs/components/SettingsGeneral.tsx+++ b/src/renderer/components/dialogs/components/SettingsGeneral.tsx@@ -70,6 +70,7 @@ import {} from '-/services/secure-crypto';import { isAnotherTabOpen } from '-/services/credentialsTabGuard';import CredentialsPasswordSetupDialog from '-/components/dialogs/CredentialsPasswordSetupDialog';+import { presentCodeRedemption, restoreProPurchase } from '-/services/iap';import { isWorkerAvailable, setLanguage } from '-/services/utils-io';import { TS } from '-/tagspaces.namespace';import { clearAllURLParams } from '-/utils/dom';@@ -1803,6 +1804,39 @@ function SettingsGeneral() {</ListItem>),},+ // Capacitor-only: in-app purchase management. Apple App Review+ // requires a visible "Restore Purchases" entry for any app that+ // ships IAP. Redeem Code surfaces promo codes (Apple offer codes+ // / Play promo codes) so users who got a free Pro code via a+ // desktop bundle have a clear way to apply it.+ AppConfig.isCapacitor && {+ label: t('core:restorePurchases'),+ jsx: (+ <ListItem>+ <ListItemText primary={t('core:restorePurchases')} />+ <TsButton+ data-tid="settingsRestoreProTID"+ onClick={() => restoreProPurchase()}+ >+ {t('core:restorePurchases')}+ </TsButton>+ </ListItem>+ ),+ },+ AppConfig.isCapacitor && {+ label: t('core:redeemCode'),+ jsx: (+ <ListItem>+ <ListItemText primary={t('core:redeemCode')} />+ <TsButton+ data-tid="settingsRedeemCodeTID"+ onClick={() => presentCodeRedemption()}+ >+ {t('core:redeemCode')}+ </TsButton>+ </ListItem>+ ),+ },].filter(Boolean),[t,diff --git a/src/renderer/components/dialogs/hooks/BuyProDialogContextProvider.tsx b/src/renderer/components/dialogs/hooks/BuyProDialogContextProvider.tsxnew file mode 100644index 000000000..fe81cadff--- /dev/null+++ b/src/renderer/components/dialogs/hooks/BuyProDialogContextProvider.tsx@@ -0,0 +1,80 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2017-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * 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/>.+ *+ */++import LoadingLazy from '-/components/LoadingLazy';+import React, { createContext, useMemo, useReducer, useRef } from 'react';++type BuyProDialogContextData = {+ openBuyProDialog: () => void;+ closeBuyProDialog: () => void;+};++export const BuyProDialogContext = createContext<BuyProDialogContextData>({+ openBuyProDialog: undefined,+ closeBuyProDialog: undefined,+});++export type BuyProDialogContextProviderProps = {+ children: React.ReactNode;+};++const BuyProDialog = React.lazy(+ () => import(/* webpackChunkName: "BuyProDialog" */ '../BuyProDialog'),+);++export const BuyProDialogContextProvider = ({+ children,+}: BuyProDialogContextProviderProps) => {+ const open = useRef<boolean>(false);+ const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);++ function openDialog() {+ open.current = true;+ forceUpdate();+ }++ function closeDialog() {+ open.current = false;+ forceUpdate();+ }++ function BuyProDialogAsync(props) {+ return (+ <React.Suspense fallback={<LoadingLazy />}>+ <BuyProDialog {...props} />+ </React.Suspense>+ );+ }++ const context = useMemo(+ () => ({+ openBuyProDialog: openDialog,+ closeBuyProDialog: closeDialog,+ }),+ [],+ );++ return (+ <BuyProDialogContext.Provider value={context}>+ {children}+ {open.current && (+ <BuyProDialogAsync open={open.current} onClose={closeDialog} />+ )}+ </BuyProDialogContext.Provider>+ );+};diff --git a/src/renderer/containers/DialogsRoot.tsx b/src/renderer/containers/DialogsRoot.tsxindex 3202d2972..71cf6d116 100644--- a/src/renderer/containers/DialogsRoot.tsx+++ b/src/renderer/containers/DialogsRoot.tsx@@ -33,6 +33,7 @@ import { NewAudioDialogContextProvider } from '-/components/dialogs/hooks/NewAudimport { NewFileDialogContextProvider } from '-/components/dialogs/hooks/NewFileDialogContextProvider';import { OnboardingDialogContextProvider } from '-/components/dialogs/hooks/OnboardingDialogContextProvider';import { PerspectiveOnboardingContextProvider } from '-/components/dialogs/hooks/PerspectiveOnboardingContextProvider';+import { BuyProDialogContextProvider } from '-/components/dialogs/hooks/BuyProDialogContextProvider';import { ProTeaserDialogContextProvider } from '-/components/dialogs/hooks/ProTeaserDialogContextProvider';import { ProgressDialogContextProvider } from '-/components/dialogs/hooks/ProgressDialogContextProvider';import { ResolveConflictContextProvider } from '-/components/dialogs/hooks/ResolveConflictContextProvider';@@ -76,6 +77,11 @@ const providers = [KeyboardDialogContextProvider,LinkDialogContextProvider,ProTeaserDialogContextProvider,+ // BuyProDialogContextProvider must wrap ProTeaserDialogContextProvider so+ // the "Compare and Upgrade" CTA inside ProTeaserDialog can call+ // openBuyProDialog() on Capacitor mobile (replaces the external URL link+ // — both stores forbid linking out from the actual purchase flow).+ BuyProDialogContextProvider,AiGenerationDialogContextProvider,ResolveConflictContextProvider,DownloadUrlContextProvider,diff --git a/src/renderer/locales/en/core.json b/src/renderer/locales/en/core.jsonindex 7b96a4d77..79add88fc 100644--- a/src/renderer/locales/en/core.json+++ b/src/renderer/locales/en/core.json@@ -1149,5 +1149,18 @@"coreExtensionsTooltip": "These are extensions which are packaged with the current version of the app","globalShortcutsTooltip": "Enables global shortcut for creating new files, file navigation, play/pause audio files or opening the search. Global shortcuts are working even if the app window is not currently in focus or visible.","devModeTooltip": "Will enable some experimental features and turn on extra debugging",+ "tagSpacesPro": "TagSpaces Pro",+ "buyProSubtitle": "Unlock TagSpaces Pro on this device — one-time purchase, yours forever.",+ "buyProFeaturesList": "Includes Kanban, Calendar, Mapique and FolderViz perspectives, annotations, AI chat, and more.",+ "buyProAction": "Buy TagSpaces Pro for {{price}}",+ "restorePurchases": "Restore Purchases",+ "redeemCode": "Redeem code",+ "oneTimePurchase": "One-time purchase",+ "familySharingNote": "Family Sharing supported on iOS — your purchase extends to family members.",+ "purchaseCompleteReloading": "Purchase complete. Restarting…",+ "purchaseFailed": "Purchase could not be completed.",+ "restoreCompleteReloading": "Purchase restored. Restarting…",+ "noPurchaseFoundToRestore": "No previous purchase found on this account.",+ "priceUnavailable": "Price unavailable","-": "-"}diff --git a/src/renderer/pro/index.ts b/src/renderer/pro/index.tsindex 034a9816d..8842cea51 100644--- a/src/renderer/pro/index.ts+++ b/src/renderer/pro/index.ts@@ -17,6 +17,7 @@*/import AppConfig from '-/AppConfig';+import { isProUnlockedSync } from '-/services/iap';let tsPro;@@ -30,7 +31,10 @@ try {}}-if (AppConfig.isCapacitorAndroid) {+// On Capacitor (iOS + Android) the Pro feature set additionally requires a+// valid entitlement, resolved by services/iap.ts. Other platforms gate+// purely on the require() result above.+if (AppConfig.isCapacitor && !isProUnlockedSync()) {tsPro = undefined;}diff --git a/src/renderer/services/iap.ts b/src/renderer/services/iap.tsnew file mode 100644index 000000000..5afbb8629--- /dev/null+++ b/src/renderer/services/iap.ts@@ -0,0 +1,358 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2017-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * 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/>.+ */++// In-app purchase service for the Capacitor mobile apps. Wraps+// capacitor-plugin-cdv-purchase (the Capacitor edition of Fovea's+// well-known cordova-plugin-purchase) which talks to StoreKit 2 on iOS+// and Google Play Billing v8.3+ on Android. No third-party data+// processor — receipts only go to Apple/Google.+//+// The entitlement is resolved from the store and exposed synchronously so+// consumers can read it at module-load time without awaiting a Promise.+// After a verified purchase or restore it is refreshed and a soft reload+// re-evaluates the Pro gate with the new value.+//+// The CdvPurchase store is event-driven: register product → set up+// listeners → initialize. The verified→finish flow is mandatory on+// StoreKit 2 / Play Billing v8 (otherwise the platforms keep retrying).+// No-op on desktop and web.++import AppConfig from '-/AppConfig';++const PRO_PRODUCT_ID = 'org.tagspaces.mobileapp.pro';+const TS_IAP_PRO_KEY = 'tsIapProEntitlement';++export interface IAPProduct {+ id: string;+ title: string;+ description: string;+ /** Localized formatted price, e.g. "$29.99". Display this directly. */+ price: string;+ currency?: string;+}++export interface IAPPurchaseResult {+ success: boolean;+ cancelled?: boolean;+ error?: string;+}++/**+ * Synchronous Pro entitlement check for the Capacitor mobile platforms.+ * Reflects the entitlement resolved by initializeIap() and refreshed by+ * the post-purchase listeners. Returns false on non-Capacitor builds.+ *+ * Safe to call from a module-load context (no async, no React).+ */+export function isProUnlockedSync(): boolean {+ if (!AppConfig.isCapacitor) return false;+ try {+ return localStorage.getItem(TS_IAP_PRO_KEY) === 'true';+ } catch {+ return false;+ }+}++/** Whether IAP is usable on the current platform. */+export function isIapAvailable(): boolean {+ return Boolean(AppConfig.isCapacitor);+}++function setEntitlementCache(unlocked: boolean): void {+ try {+ localStorage.setItem(TS_IAP_PRO_KEY, unlocked ? 'true' : 'false');+ } catch {+ /* localStorage unavailable — entitlement won't persist across reloads */+ }+}++function reloadAfterEntitlementChange(): void {+ // The Pro gate is evaluated once at bundle load. After a successful+ // purchase or restore we reload so it re-evaluates. Brief flash; simplest+ // model that doesn't require migrating every `if (Pro)` call site.+ setTimeout(() => {+ try {+ window.location.reload();+ } catch {+ /* ignore */+ }+ }, 250);+}++// --- CdvPurchase plugin singleton ---++type CdvStore = any;+type CdvPurchaseModule = any;++let cachedModule: CdvPurchaseModule | null = null;+let initializePromise: Promise<void> | null = null;++async function loadPlugin(): Promise<CdvPurchaseModule | null> {+ if (!isIapAvailable()) return null;+ if (cachedModule) return cachedModule;+ try {+ // Dynamic import keeps the dependency out of desktop/web hot paths;+ // webpack still resolves it at build time (it's in node_modules), so+ // run `npm install` after pulling these changes.+ cachedModule = await import('capacitor-plugin-cdv-purchase');+ return cachedModule;+ } catch (e) {+ console.warn(+ '[iap] capacitor-plugin-cdv-purchase not resolvable:',+ (e as Error)?.message,+ );+ return null;+ }+}++/**+ * Initialize the CdvPurchase store once at app boot. Registers our Pro+ * product against both platforms, wires the verify→finish purchase+ * lifecycle, and queries current ownership. If the entitlement state+ * changes during init (fresh install with prior purchase, or refund+ * detected since last launch) we reload so the Pro module gate at+ * src/renderer/pro/index.ts re-evaluates.+ *+ * Safe to call on any platform — no-ops off-Capacitor. Idempotent: extra+ * calls return the in-flight or completed promise.+ */+export async function initializeIap(): Promise<void> {+ if (!isIapAvailable()) return;+ if (initializePromise) return initializePromise;+ initializePromise = (async () => {+ const mod = await loadPlugin();+ if (!mod) return;+ const { store, ProductType, Platform } = mod;+ if (!store) return;++ const wasUnlocked = isProUnlockedSync();++ // Register the non-consumable Pro product for both stores. The+ // platform-appropriate one activates at initialize() time below.+ try {+ store.register([+ {+ id: PRO_PRODUCT_ID,+ type: ProductType.NON_CONSUMABLE,+ platform: Platform.APPLE_APPSTORE,+ },+ {+ id: PRO_PRODUCT_ID,+ type: ProductType.NON_CONSUMABLE,+ platform: Platform.GOOGLE_PLAY,+ },+ ]);+ } catch (e) {+ console.warn('[iap] store.register failed:', e);+ return;+ }++ // Purchase lifecycle: approved → verify (server-side or local) →+ // finish. For a non-consumable IAP with no backend, the plugin's+ // built-in local verification is enough; once finished we mark the+ // entitlement cache and reload.+ try {+ store+ .when()+ .approved((transaction: any) => {+ try {+ return transaction.verify();+ } catch (e) {+ console.warn('[iap] verify call failed:', e);+ return undefined;+ }+ })+ .verified((receipt: any) => {+ try {+ return receipt.finish();+ } catch (e) {+ console.warn('[iap] receipt.finish failed:', e);+ return undefined;+ }+ })+ .finished((_transaction: any) => {+ if (store.owned?.(PRO_PRODUCT_ID)) {+ setEntitlementCache(true);+ reloadAfterEntitlementChange();+ }+ })+ .productUpdated(() => {+ syncOwnedToCache(store);+ })+ .receiptUpdated(() => {+ syncOwnedToCache(store);+ });+ } catch (e) {+ console.warn('[iap] failed to register lifecycle listeners:', e);+ }++ try {+ const platforms = [Platform.APPLE_APPSTORE, Platform.GOOGLE_PLAY];+ await store.initialize(platforms);+ } catch (e) {+ console.warn('[iap] store.initialize failed:', e);+ return;+ }++ // After initialize the store has refreshed receipts and products.+ syncOwnedToCache(store);+ const isUnlocked = isProUnlockedSync();+ if (wasUnlocked !== isUnlocked) {+ reloadAfterEntitlementChange();+ }+ })();+ return initializePromise;+}++function syncOwnedToCache(store: CdvStore): void {+ try {+ const owned = Boolean(store.owned?.(PRO_PRODUCT_ID));+ setEntitlementCache(owned);+ } catch (e) {+ console.warn('[iap] owned() lookup failed:', e);+ }+}++/**+ * Fetch the Pro product details (localized price, title) for display+ * inside the Buy Pro sheet. Returns null on non-Capacitor or if the+ * store hasn't loaded the product yet.+ */+export async function getProProduct(): Promise<IAPProduct | null> {+ if (!isIapAvailable()) return null;+ try {+ await initializeIap();+ const mod = await loadPlugin();+ if (!mod) return null;+ const { store } = mod;+ const product = store?.get?.(PRO_PRODUCT_ID);+ if (!product) return null;+ const offer = product.offers?.[0];+ const pricingPhase = offer?.pricingPhases?.[0];+ return {+ id: PRO_PRODUCT_ID,+ title: product.title ?? 'TagSpaces Pro',+ description: product.description ?? '',+ price: pricingPhase?.price ?? '',+ currency: pricingPhase?.currency,+ };+ } catch (e) {+ console.warn('[iap] getProProduct failed:', e);+ return null;+ }+}++/**+ * Initiate the Pro purchase flow. Shows the native StoreKit / Play+ * Billing sheet. Returns immediately after the user closes the sheet;+ * the entitlement is set by the verify→finish listener wired up in+ * initializeIap(), which then triggers a reload. Callers can check+ * isProUnlockedSync() after the reload.+ */+export async function purchasePro(): Promise<IAPPurchaseResult> {+ if (!isIapAvailable()) {+ return { success: false, error: 'IAP not available on this platform' };+ }+ try {+ await initializeIap();+ const mod = await loadPlugin();+ if (!mod) return { success: false, error: 'IAP plugin unavailable' };+ const { store } = mod;+ const product = store?.get?.(PRO_PRODUCT_ID);+ const offer = product?.offers?.[0];+ if (!offer) {+ return { success: false, error: 'Pro product not loaded from store' };+ }+ const result = await store.order(offer);+ // result is undefined on success; or an error object with .isError.+ if (result && (result as any).isError) {+ const err = result as any;+ const code = err.code ?? err.errorCode;+ if (code === 6500 || /cancel/i.test(err.message ?? '')) {+ return { success: false, cancelled: true };+ }+ return { success: false, error: err.message ?? 'Purchase failed' };+ }+ // No error returned — purchase succeeded or is pending verification.+ // Entitlement cache + reload is handled by the verify→finish listener.+ return { success: true };+ } catch (e: any) {+ const msg = e?.message ?? String(e);+ if (e?.code === 6500 || /cancel/i.test(msg)) {+ return { success: false, cancelled: true };+ }+ return { success: false, error: msg };+ }+}++/**+ * User-triggered restore. Asks the store to refresh and re-emit any+ * receipts; if the user already owns Pro, the verify→finish listener+ * updates the cache and reloads.+ */+export async function restoreProPurchase(): Promise<{ restored: boolean }> {+ if (!isIapAvailable()) return { restored: false };+ try {+ await initializeIap();+ const mod = await loadPlugin();+ if (!mod) return { restored: false };+ const { store } = mod;+ await store.restorePurchases();+ syncOwnedToCache(store);+ return { restored: isProUnlockedSync() };+ } catch (e) {+ console.warn('[iap] restore failed:', e);+ return { restored: false };+ }+}++/**+ * Open the platform's promo-code redemption UI. iOS uses StoreKit's+ * native redemption sheet (CdvPurchase exposes it via+ * store.manageSubscriptions / a dedicated method depending on plugin+ * version); Android has no in-app API, so we deep-link to the Play+ * Store's promo redemption page.+ */+export async function presentCodeRedemption(): Promise<void> {+ if (!isIapAvailable()) return;+ try {+ if (AppConfig.isCapacitoriOS) {+ await initializeIap();+ const mod = await loadPlugin();+ if (!mod) return;+ const { store } = mod;+ // CdvPurchase 13+ exposes redeemCode() on iOS for the offer code+ // redemption sheet. Older versions used presentCodeRedemptionSheet+ // on the iOS adapter directly; try both for forward compatibility.+ const redeem =+ store?.redeemCode ?? store?.iosAdapter?.presentCodeRedemptionSheet;+ if (typeof redeem === 'function') {+ await redeem.call(store);+ }+ return;+ }+ if (AppConfig.isCapacitorAndroid) {+ // Play has no in-app API for promo code redemption. Deep-link to+ // the Play Store redemption page; user pastes the code there.+ window.open('https://play.google.com/redeem', '_blank');+ }+ } catch (e) {+ console.warn('[iap] redeem code failed:', e);+ }+}++export const ProProductId = PRO_PRODUCT_ID;diff --git a/src/renderer/services/io-capacitor.ts b/src/renderer/services/io-capacitor.tsindex d7082400f..98a9d23ca 100644--- a/src/renderer/services/io-capacitor.ts+++ b/src/renderer/services/io-capacitor.ts@@ -163,6 +163,13 @@ async function onDeviceReady() {// Initialize file system and load settingsgetFileSystem();+ // Refresh Pro entitlement cache from the store (StoreKit / Play Billing).+ // Fire-and-forget: rest of bootstrap doesn't depend on it. If the+ // entitlement state changes (fresh install with prior purchase, refund+ // processed since last launch) the service triggers a reload so the+ // Pro gate at src/renderer/pro/index.ts re-evaluates.+ void import('-/services/iap').then(({ initializeIap }) => initializeIap());+// iOS: hide splash screen after a delayif (Capacitor.getPlatform() === 'ios') {setTimeout(() => {