import { IHttpClient } from '@/common/http'; import { IAdBreakParams } from '@/common/ads'; import { EventPromiseHandler } from '../event-listener'; import { UnlockOptionsEventName, IUnlockOptionsEvent } from '@/common/rewards/reward-emitter'; import { rewardsCommands } from '../coins/rewards-command'; import { RewardsCommandType } from '@jolibox/types'; import { createShowSubscriptionModal } from './commands/use-subscription'; import { registerUseSubscriptionCommand } from './commands'; import { context } from '@/common/context'; import { checkIfSupportSubscription } from '../common'; import { refreshBalanceCache } from '../coins/jolicoin/cached-fetch-balance'; import { refreshGemBalanceCache } from '../coins/joligem/cached-fetch-gem-balance'; export const createCommonSubscriptionHandler = ( type: 'SUBSCRIPTION', httpClient: IHttpClient, { handlers: { handleSubSuccess, handleSubFailed, unlockOptionsHandler, showSubscriptionModal, hasSubscription } }: { handlers: { handleSubSuccess?: () => void; handleSubFailed?: (params: IAdBreakParams) => void; unlockOptionsHandler: EventPromiseHandler; showSubscriptionModal: ReturnType; hasSubscription?: () => boolean; }; } ) => { // register commands registerUseSubscriptionCommand({ showSubscriptionModal: showSubscriptionModal }); const commands = [`Rewards.subscription`]; return async (params: IAdBreakParams) => { try { const unlockOptions = await unlockOptionsHandler.getData(); const supportSubscription = checkIfSupportSubscription(unlockOptions, hasSubscription); if (!supportSubscription) { // pass to next handler return false; } let result = true; for (const command of commands) { const commandResult = await rewardsCommands.executeCommand(command as RewardsCommandType); result = result && commandResult.result !== 'FAILED'; if (commandResult.result !== 'CONTINUE') { break; } } // refresh balance and gem balance cache.in case of user login, the balance and gem balance is not updated. refreshBalanceCache(httpClient); refreshGemBalanceCache(httpClient); console.log('-----unlockWithSubscription result-----', result); if (result) { try { params.adBreakDone?.({ breakType: params.type, breakName: 'name' in params ? params.name ?? '' : '', breakFormat: params.type === 'reward' ? 'reward' : 'interstitial', breakStatus: 'viewed' }); if ('adViewed' in params) { params.adViewed?.(); } context.onEnvConfigChanged?.({ hostUserInfo: { ...(context.hostUserInfo ?? { isLogin: false }), isSubUser: true } }); } catch (e) { console.error('-----unlockWithSubscription adBreakDone error-----', e); } handleSubSuccess?.(); return true; } handleSubFailed?.(params); return false; } catch (e) { console.info(`SubscriptionRewardHandler error:`, e); if (e instanceof Error && e.message == 'CANCEL') { // Cancel should terminate the reward handler, invoke unlock failed throw e; } handleSubFailed?.(params); return false; } finally { // unlockOptionsHandler.clearCache(); } }; };