@huaapp001/m-play 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,11 +1,10 @@
1
1
  {
2
2
  "name": "@huaapp001/m-play",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "description": "m-play",
5
5
  "main": "./lib/module/index.js",
6
6
  "module": "./lib/module/index.js",
7
7
  "types": "./lib/typescript/src/index.d.ts",
8
- "private": false,
9
8
  "exports": {
10
9
  ".": {
11
10
  "import": "./lib/module/index.js",
@@ -17,6 +16,7 @@
17
16
  "./package.json": "./package.json"
18
17
  },
19
18
  "files": [
19
+ "src",
20
20
  "lib",
21
21
  "android",
22
22
  "ios",
@@ -0,0 +1,8 @@
1
+ import type { TurboModule } from 'react-native';
2
+ import { TurboModuleRegistry } from 'react-native';
3
+
4
+ export interface Spec extends TurboModule {
5
+ multiply(a: number, b: number): number;
6
+ }
7
+
8
+ export default TurboModuleRegistry.getEnforcing<Spec>('MPlay');
@@ -0,0 +1,48 @@
1
+ // 定义配置类型
2
+ export interface ConfigType {
3
+ header: {
4
+ apiUrl?: string;
5
+ appId?: string;
6
+ PACKAGENAME?: string;
7
+ };
8
+ webviewUrl: string;
9
+ adjustConfig: {
10
+ devKey: string;
11
+ appId: string;
12
+ ADJUST_MAX_DELAY_TIME: number;
13
+ ONELINK_SHARE_VALUE: string;
14
+ ONELINK_NO_HTTP_VALUE: string;
15
+ bgImage: string
16
+ appName: string;
17
+ loadingText: string;
18
+ completePrefixUrl: string;
19
+ }
20
+ }
21
+
22
+ // 声明全局类型
23
+ declare global {
24
+ var __MPLAY_CONFIG__: ConfigType | null;
25
+ }
26
+
27
+ // 初始化全局配置
28
+ if (!global.__MPLAY_CONFIG__) {
29
+ global.__MPLAY_CONFIG__ = null;
30
+ }
31
+
32
+ // 设置配置
33
+ export const initializeConfig = (config: ConfigType) => {
34
+ global.__MPLAY_CONFIG__ = config;
35
+ };
36
+
37
+ // 获取配置
38
+ export const getConfig = (): ConfigType => {
39
+ if (!global.__MPLAY_CONFIG__) {
40
+ throw new Error('Config not initialized. Please call initializeConfig first.');
41
+ }
42
+ return global.__MPLAY_CONFIG__;
43
+ };
44
+
45
+ // 重置配置
46
+ export const resetConfig = () => {
47
+ global.__MPLAY_CONFIG__ = null;
48
+ };
package/src/index.tsx ADDED
@@ -0,0 +1,3 @@
1
+ import ProviderBPackageIndex from './package/screens/home';
2
+ import { initializeConfig } from './config';
3
+ export { ProviderBPackageIndex, initializeConfig };
Binary file
@@ -0,0 +1,19 @@
1
+ import { atom } from 'jotai';
2
+ import { Platform } from 'react-native';
3
+
4
+ /** 是否允许att权限访问 */
5
+ export const isAllowAttAccessAtom = atom<boolean>(
6
+ Platform.OS === 'android' ? true : false
7
+ );
8
+
9
+ /** 存储的深链后面的参数-临时存储 后期需要清除 */
10
+ export const schemeDeepLinkParamsAtom = atom<Record<string, string>>({});
11
+
12
+ /** 是否第一次初始化af成功 */
13
+ export const isFirstInitAfSuccessAtom = atom(false);
14
+
15
+ /** b包webview是否加载完成 */
16
+ export const bPackageWebviewLoadingFinishAtom = atom(false);
17
+
18
+ /** 中间页是否加载完成 */
19
+ export const MiddleScreenLoadingFinishAtom = atom(false);
@@ -0,0 +1,89 @@
1
+ import React, { useRef, useImperativeHandle, forwardRef } from 'react';
2
+ import { onMessageForRN } from '@tianzhitong/js-bridge';
3
+ import { WebView } from 'react-native-webview';
4
+
5
+ // 注入初始化代码
6
+ const injectJavaScriptInit = `
7
+ (function(){
8
+ window.ReactNativeJsBridge = {
9
+ callbackSeq: 1,
10
+ send: function(data) {
11
+ return new Promise(function(resolve, reject) {
12
+ const callbackName = 'ReactNativeWebViewCallback_' + ReactNativeJsBridge.callbackSeq++;
13
+
14
+ window[callbackName] = function(result) {
15
+ resolve(result);
16
+ delete window[callbackName];
17
+ };
18
+
19
+ window.ReactNativeWebView.postMessage(
20
+ JSON.stringify({
21
+ callbackId: callbackName,
22
+ data,
23
+ }),
24
+ );
25
+ });
26
+ },
27
+ };
28
+
29
+ window.ReactNativeJsBridge.send({
30
+ type: 'titleChange',
31
+ data: document.title,
32
+ });
33
+
34
+ new MutationObserver(function(mutations) {
35
+ window.ReactNativeJsBridge.send({
36
+ type: 'titleChange',
37
+ data: mutations[0].target.nodeValue,
38
+ });
39
+ }).observe(
40
+ document.querySelector('title'),
41
+ { subtree: true, characterData: true, childList: true }
42
+ );
43
+ })();
44
+ `;
45
+
46
+ export default (props: any) => {
47
+ const {
48
+ source = {},
49
+ ref,
50
+ onLoad = () => {},
51
+ onLoadEnd = () => {},
52
+ onShouldStartLoadWithRequest = null,
53
+ injectJavaScript = '',
54
+ ...other
55
+ } = props;
56
+
57
+ const handleOnLoad = (e) => {
58
+ onLoad(e);
59
+ };
60
+
61
+ const handleOnLoadEnd = (e) => {
62
+ onLoadEnd(e);
63
+ };
64
+
65
+ const hanldeShouldStartLoadWithRequest = (e) => {
66
+ if (onShouldStartLoadWithRequest) {
67
+ return onShouldStartLoadWithRequest(e);
68
+ }
69
+ return true;
70
+ };
71
+
72
+ return (
73
+ <WebView
74
+ ref={ref}
75
+ source={source}
76
+ webviewDebuggingEnabled
77
+ domStorageEnabled={true} // 启用 DOM 存储
78
+ startInLoadingState={true} // 显示加载指示器
79
+ javaScriptEnabled={true} // 启用 JavaScript
80
+ onLoad={handleOnLoad}
81
+ onMessage={onMessageForRN}
82
+ onLoadEnd={handleOnLoadEnd}
83
+ onShouldStartLoadWithRequest={hanldeShouldStartLoadWithRequest}
84
+ injectedJavaScript={`${injectJavaScriptInit}${injectJavaScript}`}
85
+ allowsInlineMediaPlayback={true}
86
+ {...other}
87
+ />
88
+ );
89
+ };
@@ -0,0 +1,10 @@
1
+ export const STORAGE_USER_ID = 'STORAGE_USER_ID';
2
+
3
+ export const STORAGE_USER_TOKEN = 'STORAGE_USER_TOKEN';
4
+
5
+ /** 第一次初始化adjust存储key */
6
+ export const APP_FIRST_INIT_ADJUST_KEY = 'APP_FIRST_INIT_ADJUST_KEY';
7
+ /** 不带协议的 */
8
+ export const ONELINK_NO_HTTP_VALUE = 'com.play.flamshort://';
9
+ /** TODO 链接需要替换 */
10
+ export const ONELINK_SHARE_VALUE = 'https://flamshort.onelink.me/';
@@ -0,0 +1,52 @@
1
+ import { axiosGet, axiosPost } from '../request';
2
+ import AsyncStorage from '@react-native-async-storage/async-storage';
3
+ import { useEffect, useState } from 'react';
4
+ import { NativeModules, Platform } from 'react-native';
5
+ import deviceInfo from 'react-native-device-info';
6
+ import { STORAGE_USER_ID } from '../const/storage';
7
+ import useGetNetwork from './useGetNetwork';
8
+
9
+ const useAppGetUID = () => {
10
+ const [isLoading, setIsLoading] = useState(false);
11
+ const [isAPackage, setIsAPackage] = useState(false);
12
+ const [isConnectNetwork] = useGetNetwork();
13
+ useEffect(() => {
14
+ if(!isConnectNetwork) return;
15
+ const getUserId = async () => {
16
+ try {
17
+ // 获取ip地址
18
+ const ipRes = await axiosGet('/get_ip_info/');
19
+ console.log('ipRes', ipRes);
20
+ // 获取版本信息
21
+ const res = await axiosPost('/get_version/', {
22
+ phone_version: deviceInfo.getBrand(),
23
+ system_version: deviceInfo.getSystemVersion(),
24
+ language:
25
+ Platform.OS === 'ios'
26
+ ? NativeModules.SettingsManager?.settings?.AppleLocale ||
27
+ NativeModules.SettingsManager?.settings?.AppleLanguages[0]
28
+ : NativeModules?.I18nManager?.localeIdentifier,
29
+ app_version: deviceInfo.getVersion(),
30
+ unique_id: deviceInfo.getUniqueIdSync() + '1112',
31
+ ip: ipRes.data.ip,
32
+ });
33
+
34
+ console.log('resresres',res)
35
+ setIsAPackage(res.data.publishStatus !== '1');
36
+ global.GLOBAL_USER_UID = res.data.user_id;
37
+ AsyncStorage.setItem(STORAGE_USER_ID, String(res.data.user_id));
38
+ setIsLoading(true);
39
+ } catch (ex) {
40
+ console.log('ex111', ex);
41
+ }
42
+ };
43
+ getUserId();
44
+ }, [isConnectNetwork]);
45
+
46
+ return {
47
+ isLoading,
48
+ isAPackage,
49
+ };
50
+ };
51
+
52
+ export default useAppGetUID;
@@ -0,0 +1,15 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { useNetInfo } from '@react-native-community/netinfo';
3
+
4
+ const useGetNetwork = () => {
5
+ /** 启动app时是否有网络 */
6
+ const [isConnectNetwork, setIsConnectNetwork] = useState(false);
7
+ const { isConnected } = useNetInfo();
8
+ useEffect(() => {
9
+ if (isConnected) {
10
+ setIsConnectNetwork(true);
11
+ }
12
+ }, [isConnected, setIsConnectNetwork]);
13
+ return [isConnectNetwork];
14
+ };
15
+ export default useGetNetwork;
@@ -0,0 +1,51 @@
1
+ import { useEffect } from 'react';
2
+ import useGoogleAndIosLogin from './useGoogleAndIosLogin';
3
+ import DeviceInfo from 'react-native-device-info';
4
+ import { NativeModules, Platform } from 'react-native';
5
+ import { axiosPost } from '../request';
6
+ import AsyncStorage from '@react-native-async-storage/async-storage';
7
+ import { STORAGE_USER_TOKEN } from '../const/storage';
8
+
9
+ const useGetUserToken = (jsbridge: any) => {
10
+ const { googleLogin } = useGoogleAndIosLogin();
11
+ useEffect(() => {
12
+ jsbridge.addEventListener('LOG_IN', (type: string) => {
13
+ googleLogin().then((googleCredential) => {
14
+ const params = {
15
+ uid: global.GLOBAL_USER_UID,
16
+ source: '',
17
+ phone_version: DeviceInfo.getBrand(),
18
+ system_version: DeviceInfo.getSystemVersion(),
19
+ language:
20
+ Platform.OS === 'ios'
21
+ ? NativeModules.SettingsManager.settings.AppleLocale ||
22
+ NativeModules.SettingsManager.settings.AppleLanguages[0]
23
+ : NativeModules.I18nManager.localeIdentifier,
24
+ app_version: DeviceInfo.getVersion(),
25
+ account_type: 'google',
26
+ unique_id: '',
27
+ ip: DeviceInfo.getIpAddressSync(),
28
+ id_token: googleCredential?.token,
29
+ };
30
+ console.log('params', googleCredential?.token);
31
+ axiosPost('/register/', params)
32
+ .then((res) => {
33
+ console.log('res', res);
34
+ AsyncStorage.setItem(STORAGE_USER_TOKEN, res.data.token);
35
+ console.log('res.data.token', res.data.token);
36
+ jsbridge.postMessage({
37
+ type: 'USER_STATUS',
38
+ payload: {
39
+ token: res.data.token,
40
+ },
41
+ });
42
+ })
43
+ .catch((err) => {
44
+ console.log('err', err);
45
+ });
46
+ });
47
+ });
48
+ }, []);
49
+ };
50
+
51
+ export default useGetUserToken;
@@ -0,0 +1,34 @@
1
+ import { useEffect } from 'react';
2
+ import { GoogleSignin } from '@react-native-google-signin/google-signin';
3
+ import auth from '@react-native-firebase/auth';
4
+
5
+ const useGoogleAndIosLogin = () => {
6
+ useEffect(() => {
7
+ GoogleSignin.configure({
8
+ webClientId:
9
+ '964229154053-r3o5j6c6fpq7r35eia03mpfnr5r8frgm.apps.googleusercontent.com',
10
+ iosClientId:
11
+ '964229154053-kv218k58e53un307mu8d2i7lrr2ok1kt.apps.googleusercontent.com',
12
+ });
13
+ }, []);
14
+
15
+ const googleLogin = async () => {
16
+ try {
17
+ await GoogleSignin.hasPlayServices({
18
+ showPlayServicesUpdateDialog: true,
19
+ });
20
+ await GoogleSignin.signOut();
21
+ const { data }: any = await GoogleSignin.signIn();
22
+ let googleCredential = auth.GoogleAuthProvider.credential(data.idToken);
23
+ return googleCredential;
24
+ } catch (error) {
25
+ // Toast.info('Login failed, please try again later');
26
+ console.log('谷歌catch错误', error);
27
+ }
28
+ };
29
+
30
+ return {
31
+ googleLogin,
32
+ };
33
+ };
34
+ export default useGoogleAndIosLogin;
@@ -0,0 +1,213 @@
1
+ import AsyncStorage from '@react-native-async-storage/async-storage';
2
+ import Clipboard from '@react-native-clipboard/clipboard';
3
+ import {
4
+ isFirstInitAfSuccessAtom,
5
+ schemeDeepLinkParamsAtom,
6
+ } from '../atoms/global';
7
+ import { useAtomValue, useSetAtom } from 'jotai';
8
+ import { useEffect } from 'react';
9
+ import { Linking } from 'react-native';
10
+ import appsFlyer from 'react-native-appsflyer';
11
+ import { APP_FIRST_INIT_ADJUST_KEY } from '../const/storage';
12
+ import useGetNetwork from './useGetNetwork';
13
+ import { isAllowAttAccessAtom } from '../atoms/global';
14
+ import { extractQueryParams } from '../utils/extractQueryParams';
15
+ import { getUrlFromDevice } from '../utils/getUrlFromDevice';
16
+ import { getConfig } from '../../config';
17
+
18
+ interface Data {
19
+ deeplink: string;
20
+ isAJ?: boolean;
21
+ isLoadTwo?: boolean;
22
+ }
23
+
24
+
25
+ const useInitAfInfo = () => {
26
+ const systemConfig = getConfig();
27
+ const setSchemeDeepLinkParamsAtom = useSetAtom(schemeDeepLinkParamsAtom);
28
+ const [isConnected] = useGetNetwork();
29
+ const isAllowAttAccess = useAtomValue(isAllowAttAccessAtom);
30
+ const setIsFirstInitAfSuccessAtom = useSetAtom(isFirstInitAfSuccessAtom);
31
+
32
+ /** 处理深链信息 */
33
+ const processDeepLink = (data: Data) => {
34
+ const { deeplink, isAJ = false, isLoadTwo = false } = data;
35
+ // TODO 可删除
36
+ console.log('deeplinkdeeplink------->>>>>', deeplink);
37
+ if (!isLoadTwo && isAJ) {
38
+ global.IS_FIRST_LOAD_DEEP_LINK = true;
39
+ global.AF_END_LOAD_TIME = new Date().getTime();
40
+ }
41
+ let params: Record<string, string> = {};
42
+ if (deeplink.includes(systemConfig.adjustConfig.ONELINK_SHARE_VALUE)) {
43
+ const url = deeplink.split(systemConfig.adjustConfig.ONELINK_SHARE_VALUE)[1];
44
+ params = extractQueryParams(url) ?? {};
45
+ if (params.deep_link_value) {
46
+ processDeepLink({
47
+ deeplink:
48
+ systemConfig.adjustConfig.ONELINK_NO_HTTP_VALUE + decodeURIComponent(params.deep_link_value),
49
+ isAJ,
50
+ isLoadTwo: true,
51
+ });
52
+ return;
53
+ }
54
+ }
55
+ if (deeplink.includes(systemConfig.adjustConfig.ONELINK_NO_HTTP_VALUE)) {
56
+ const url = deeplink.split(systemConfig.adjustConfig.ONELINK_NO_HTTP_VALUE)[1];
57
+ params = extractQueryParams(url) ?? {};
58
+ // 做一个兜底处理 目前安卓模拟器会出现右边的情况 ONELINK_NO_HTTP_VALUE?deep_link_value=ONELINK_NO_HTTP_VALUE
59
+ if (params.deep_link_value) {
60
+ processDeepLink({
61
+ deeplink: systemConfig.adjustConfig.ONELINK_NO_HTTP_VALUE + decodeURIComponent(params.deep_link_value),
62
+ isAJ,
63
+ isLoadTwo: true,
64
+ });
65
+ return;
66
+ }
67
+ }
68
+ console.log('params',params)
69
+ setSchemeDeepLinkParamsAtom(params);
70
+ setIsFirstInitAfSuccessAtom(true);
71
+ };
72
+
73
+ /** 剪切板信息 */
74
+ const handlePasteboardInfo = async () => {
75
+ // TODO 可删除
76
+ console.log('deeplinkdeeplink------->>>>>handlePasteboardInfo');
77
+ // 若是之前执行过,该值是true,但是之前若是没给它赋值是不会相等的
78
+ const isNotFirstInit =
79
+ (await AsyncStorage.getItem(APP_FIRST_INIT_ADJUST_KEY)) === 'true';
80
+ // TODO 可删除
81
+ console.log(
82
+ 'deeplinkdeeplink------->>>>>handlePasteboardInfo---isNotFirstInit',
83
+ await AsyncStorage.getItem(APP_FIRST_INIT_ADJUST_KEY),
84
+ isNotFirstInit
85
+ );
86
+ if (isNotFirstInit) {
87
+ return;
88
+ }
89
+ // 剪切板内容
90
+ let pasteboardValue = await Clipboard.getString();
91
+ // TODO 可删除
92
+ console.log(
93
+ 'deeplinkdeeplink------->>>>>handlePasteboardInfo---pasteboardValue',
94
+ pasteboardValue
95
+ );
96
+ if (
97
+ pasteboardValue &&
98
+ pasteboardValue.includes(systemConfig.adjustConfig.completePrefixUrl)
99
+ ) {
100
+ global.wakeUpDeepLinkType = 'clipboard';
101
+ }
102
+ if (
103
+ !pasteboardValue ||
104
+ !pasteboardValue.includes(systemConfig.adjustConfig.completePrefixUrl)
105
+ ) {
106
+ // 走设备是否匹配 请求接口返回信息
107
+ pasteboardValue = await getUrlFromDevice();
108
+ if (pasteboardValue) {
109
+ global.wakeUpDeepLinkType = 'ip';
110
+ }
111
+ }
112
+ if (pasteboardValue) {
113
+ processDeepLink({ deeplink: pasteboardValue, isAJ: !isNotFirstInit });
114
+ }
115
+
116
+ await AsyncStorage.setItem(APP_FIRST_INIT_ADJUST_KEY, 'true');
117
+ };
118
+
119
+ useEffect(() => {
120
+ // TODO 可删除
121
+ console.log(
122
+ 'deeplinkdeeplink------->>>>>isAllowAttAccess',
123
+ isAllowAttAccess
124
+ );
125
+ if (!isAllowAttAccess) {
126
+ return;
127
+ }
128
+ // TODO 可删除
129
+ console.log(
130
+ 'isAllowAttAccessisAllowAttAccess111---->>>.',
131
+ isAllowAttAccess
132
+ );
133
+ // 记录下af初始化加载时的时间
134
+ global.AF_START_LOAD_TIME = new Date().getTime();
135
+ appsFlyer.onDeepLink((res) => {
136
+ // TODO 可删除
137
+ console.log('deeplinkdeeplink------->>>>>deepLinkStatus', res);
138
+ // 若是对应这个状态直接走兜底逻辑
139
+ if (res?.deepLinkStatus === 'NOT_FOUND') {
140
+ handlePasteboardInfo();
141
+ return;
142
+ }
143
+ const linkValue = decodeURIComponent(res?.data?.deep_link_value);
144
+ // 若是值不存在走兜底逻辑
145
+ if (!linkValue || linkValue === 'undefined') {
146
+ handlePasteboardInfo();
147
+ return;
148
+ }
149
+ global.wakeUpDeepLinkType = 'af';
150
+ processDeepLink({
151
+ deeplink: `${systemConfig.adjustConfig.ONELINK_NO_HTTP_VALUE}?${linkValue}`,
152
+ isAJ: res?.isDeferred,
153
+ });
154
+ AsyncStorage.setItem(APP_FIRST_INIT_ADJUST_KEY, 'true');
155
+ });
156
+ // TODO 可删除
157
+ console.log('appsFlyerappsFlyer---->>>', appsFlyer);
158
+ appsFlyer.initSdk(
159
+ {
160
+ devKey: systemConfig.adjustConfig.devKey,
161
+ isDebug: __DEV__,
162
+ appId: systemConfig.adjustConfig.appId,
163
+ onInstallConversionDataListener: true,
164
+ onDeepLinkListener: true,
165
+ //for iOS 14.5
166
+ timeToWaitForATTUserAuthorization: 10,
167
+ },
168
+ (result) => {
169
+ console.log(result, 'isAllowAttAccessisAllowAttAccessresult');
170
+ },
171
+ (error) => {
172
+ console.error(error, 'isAllowAttAccessisAllowAttAccesserror');
173
+ }
174
+ );
175
+ // 或者9秒之后设置为true
176
+ setTimeout(
177
+ () => {
178
+ AsyncStorage.setItem(APP_FIRST_INIT_ADJUST_KEY, 'true');
179
+ },
180
+ Number(systemConfig.adjustConfig.ADJUST_MAX_DELAY_TIME) + 1000
181
+ );
182
+ // 监听 已经启动,但是被h5换起来了会触发这个方法
183
+ Linking.addEventListener('url', ({ url }) => {
184
+ processDeepLink({ deeplink: url });
185
+ });
186
+ Linking.getInitialURL().then((url) => {
187
+ // 冷启动的时候,会触发这个
188
+ if (url) {
189
+ processDeepLink({ deeplink: url });
190
+ }
191
+ });
192
+ }, [
193
+ setSchemeDeepLinkParamsAtom,
194
+ setIsFirstInitAfSuccessAtom,
195
+ isAllowAttAccess,
196
+ ]);
197
+
198
+ useEffect(() => {
199
+ if (!isConnected) {
200
+ return;
201
+ }
202
+ const timeout = setTimeout(async () => {
203
+ if ((await AsyncStorage.getItem(APP_FIRST_INIT_ADJUST_KEY)) !== 'true') {
204
+ await handlePasteboardInfo();
205
+ }
206
+ setIsFirstInitAfSuccessAtom(true);
207
+ }, Number(systemConfig.adjustConfig.ADJUST_MAX_DELAY_TIME));
208
+ return () => {
209
+ clearTimeout(timeout);
210
+ };
211
+ }, [isConnected]);
212
+ };
213
+ export default useInitAfInfo;
@@ -0,0 +1,12 @@
1
+ export const REQUEST_METHODS = {
2
+ GET: 'GET',
3
+ POST: 'POST',
4
+ PUT: 'PUT',
5
+ DELETE: 'DELETE',
6
+ };
7
+
8
+ export const CONTENT_TYPE = {
9
+ JSON: 'application/json;charset=UTF-8',
10
+ FORM_URLENCODED: 'application/x-www-form-urlencoded;charset=UTF-8',
11
+ FORM_DATA: 'multipart/form-data;charset=UTF-8',
12
+ };
@@ -0,0 +1,99 @@
1
+ import { Platform } from 'react-native';
2
+
3
+ import axios, {
4
+ AxiosInstance,
5
+ AxiosRequestConfig,
6
+ AxiosResponse,
7
+ InternalAxiosRequestConfig,
8
+ } from 'axios';
9
+
10
+ import { CONTENT_TYPE } from './constants';
11
+ import { CustomRequestConfig } from './type';
12
+ import { getConfig } from '../../config';
13
+
14
+
15
+ const createAxiosInstance = (): AxiosInstance => {
16
+ const systemConfig = getConfig();
17
+ const instance = axios.create({
18
+ baseURL: systemConfig.header.apiUrl,
19
+ timeout: 10000,
20
+ headers: {
21
+ 'Content-Type': CONTENT_TYPE.JSON,
22
+ },
23
+ }) as AxiosInstance;
24
+
25
+ instance.interceptors.request.use(
26
+ (config: InternalAxiosRequestConfig<CustomRequestConfig>) => {
27
+ const mergedConfig = { ...config };
28
+ mergedConfig.headers = mergedConfig.headers || {};
29
+
30
+ if (global.userToken) {
31
+ mergedConfig.headers.Authorization = global.userToken;
32
+ }
33
+
34
+ mergedConfig.headers.TYPE = Platform.OS;
35
+ mergedConfig.headers.NID = systemConfig.header.appId;
36
+ mergedConfig.headers.PACKAGENAME = systemConfig.header.PACKAGENAME;
37
+
38
+ if (!global.userToken && global.userId) {
39
+ mergedConfig.headers.UID = global.userId;
40
+ }
41
+
42
+ return mergedConfig;
43
+ }
44
+ );
45
+
46
+ instance.interceptors.response.use(
47
+ (response: AxiosResponse<any>) => {
48
+ if (response.data.code === 200) {
49
+ return response.data;
50
+ }
51
+
52
+ // FIXME: Fix me the types
53
+ return response.data as Promise<AxiosResponse<any>>;
54
+ },
55
+ (error) => {
56
+ if (error.response) {
57
+ return Promise.reject(
58
+ error.response.data || { message: 'Unknown server error' }
59
+ );
60
+ } else if (error.request) {
61
+ return Promise.reject({ message: 'No response received from server' });
62
+ } else {
63
+ return Promise.reject({
64
+ message: error.message || 'Unknown error occurred',
65
+ });
66
+ }
67
+ }
68
+ );
69
+
70
+ return instance;
71
+ };
72
+
73
+ const axiosInstance = createAxiosInstance();
74
+
75
+ export const axiosGet = <T = any>(
76
+ url: string,
77
+ params?: unknown,
78
+ config?: AxiosRequestConfig
79
+ ) => {
80
+ return axiosInstance.get<T>(url, { params, ...config });
81
+ };
82
+
83
+ export const axiosPost = <T = any>(
84
+ url: string,
85
+ data?: unknown,
86
+ config?: AxiosRequestConfig
87
+ ) => {
88
+ return axiosInstance.post<T>(url, data, config);
89
+ };
90
+
91
+ export const axiosPostFormData = <T = any>(
92
+ url: string,
93
+ data?: unknown | FormData,
94
+ config?: AxiosRequestConfig
95
+ ) => {
96
+ return axiosInstance.post<T>(url, data, config);
97
+ };
98
+
99
+ export default axiosInstance;
@@ -0,0 +1,24 @@
1
+ import { type AxiosRequestConfig } from 'axios';
2
+
3
+ export type ApiResponse<T = unknown> = {
4
+ code: number;
5
+ data: T;
6
+ message: string;
7
+ msg: string;
8
+ };
9
+
10
+ export type ApiError = Error & {
11
+ code?: number;
12
+ config: AxiosRequestConfig;
13
+ isAxiosError: boolean;
14
+ };
15
+
16
+ export type CustomRequestConfig = AxiosRequestConfig & {
17
+ headers: {
18
+ TYPE?: string;
19
+ NID?: number;
20
+ PACKAGENAME?: string;
21
+ UID?: string;
22
+ Authorization?: string;
23
+ };
24
+ };
@@ -0,0 +1,100 @@
1
+ import React, { PropsWithChildren, useEffect, useMemo, useRef } from 'react';
2
+ import { Platform, View } from 'react-native';
3
+ import { createJsbridge } from '@tianzhitong/js-bridge';
4
+ import WebView from '../../components/webview';
5
+ import useGetUserToken from '../../hooks/useGetUserToken';
6
+ import { useAtom, useAtomValue } from 'jotai';
7
+ import {
8
+ bPackageWebviewLoadingFinishAtom,
9
+ MiddleScreenLoadingFinishAtom,
10
+ schemeDeepLinkParamsAtom,
11
+ } from '../../atoms/global';
12
+ import MiddleScreen from '../middle';
13
+ import useAppGetUID from '../../hooks/useAppGetUID';
14
+ import useInitAfInfo from '../../hooks/useInitAfInfo';
15
+ import { useSafeAreaInsets } from 'react-native-safe-area-context';
16
+ import { getConfig } from '../../../config';
17
+
18
+
19
+ const Home = () => {
20
+ const safeAreaInsets = useSafeAreaInsets();
21
+ const systemConfig = getConfig();
22
+ const { top, bottom } = safeAreaInsets;
23
+ const webRef = useRef<any>(null);
24
+ const middleScreenLoadingFinish = useAtomValue(MiddleScreenLoadingFinishAtom);
25
+ const [bPackageWebviewLoadingFinish, setBPackageWebviewLoadingFinish] =
26
+ useAtom(bPackageWebviewLoadingFinishAtom);
27
+
28
+ const schemeDeepLinkParams = useAtomValue(schemeDeepLinkParamsAtom);
29
+
30
+ const jsbridge = useMemo(() => {
31
+ return createJsbridge({ getWebViewRef: () => webRef });
32
+ }, []);
33
+
34
+ useEffect(() => {
35
+ if (!(bPackageWebviewLoadingFinish && middleScreenLoadingFinish)) {
36
+ return;
37
+ }
38
+ if (schemeDeepLinkParams.pageName) {
39
+ jsbridge.postMessage({
40
+ type: 'SEND_H5_PARAMS',
41
+ payload: schemeDeepLinkParams,
42
+ });
43
+ }
44
+ }, [schemeDeepLinkParams, bPackageWebviewLoadingFinish,middleScreenLoadingFinish, jsbridge]);
45
+
46
+ useGetUserToken(jsbridge);
47
+
48
+ return (
49
+ <View
50
+ style={{
51
+ flex: 1,
52
+ opacity:
53
+ bPackageWebviewLoadingFinish && middleScreenLoadingFinish ? 1 : 0,
54
+ }}
55
+ >
56
+ <WebView
57
+ ref={webRef}
58
+ source={{
59
+ uri: `${systemConfig.webviewUrl}?platform=${Platform.OS
60
+ }&app_version=${'1.1.1'}&user_id=${global.GLOBAL_USER_UID
61
+ }&top=${top}&bottom=${bottom}`,
62
+ }}
63
+ onInvokeMessage={() => { }}
64
+ onLoadEnd={() => {
65
+ console.log('onLoadEnd');
66
+ setBPackageWebviewLoadingFinish(true);
67
+ }}
68
+ />
69
+ </View>
70
+ );
71
+ };
72
+
73
+
74
+ const ProviderBPackageIndex = (props: PropsWithChildren) => {
75
+ const {
76
+ children,
77
+ } = props;
78
+ const { isLoading,isAPackage, } = useAppGetUID();
79
+ const middleScreenLoadingFinish = useAtomValue(MiddleScreenLoadingFinishAtom);
80
+ const schemeDeepLinkParams = useAtomValue(schemeDeepLinkParamsAtom);
81
+ console.log('schemeDeepLinkParams',schemeDeepLinkParams)
82
+ useInitAfInfo();
83
+
84
+ if (!isLoading) {
85
+ return null;
86
+ }
87
+ console.log('isAPackage',isAPackage)
88
+ if (isAPackage) {
89
+ return children;
90
+ }
91
+ console.log('middleScreenLoadingFinish',middleScreenLoadingFinish)
92
+ return (
93
+ <View style={{ flex: 1 }}>
94
+ {!middleScreenLoadingFinish && <MiddleScreen />}
95
+ <Home />
96
+ </View>
97
+ );
98
+ };
99
+
100
+ export default ProviderBPackageIndex;
@@ -0,0 +1,152 @@
1
+ import React, { useState, useEffect, useRef, useImperativeHandle, forwardRef } from 'react';
2
+ import { View, Text, StyleSheet, Animated, Easing } from 'react-native';
3
+ import { rwd } from '../../../utils/rwd';
4
+
5
+ const CustomProgressBar = forwardRef<any, any>(
6
+ (
7
+ {
8
+ duration = 5000,
9
+ height = rwd(10),
10
+ backgroundColor = '#e0e0e0',
11
+ fillColor = '#4CAF50',
12
+ showPercentage = true,
13
+ borderRadius = 10,
14
+ textStyle = {},
15
+ containerStyle = {},
16
+ onComplete = () => {},
17
+ },
18
+ ref,
19
+ ) => {
20
+ const progress = useState(new Animated.Value(0))[0];
21
+ const [currentProgress, setCurrentProgress] = useState(0);
22
+ const animationRef = useRef<Animated.CompositeAnimation | null>(null);
23
+
24
+ let listenerId = useRef<string>('');
25
+
26
+ const animateTo = (value: number, callback?: () => void) => {
27
+ // Stop any ongoing animation
28
+ if (animationRef.current) {
29
+ animationRef.current.stop();
30
+ }
31
+
32
+ // Calculate remaining duration proportionally
33
+ const remainingDuration = duration * ((100 - currentProgress) / 100);
34
+
35
+ animationRef.current = Animated.timing(progress, {
36
+ toValue: value,
37
+ duration: remainingDuration,
38
+ easing: Easing.linear,
39
+ useNativeDriver: false,
40
+ });
41
+
42
+ animationRef.current.start(() => {
43
+ if (value === 100 && callback) {
44
+ callback();
45
+ }
46
+ });
47
+ };
48
+
49
+ useEffect(() => {
50
+ // Add listener to animation value
51
+ listenerId.current = progress.addListener(({ value }) => {
52
+ setCurrentProgress(Math.floor(value));
53
+ });
54
+
55
+ // Start initial animation
56
+ animateTo(100, onComplete);
57
+
58
+ // Clean up listener
59
+ return () => {
60
+ progress.removeListener(listenerId.current);
61
+ if (animationRef.current) {
62
+ animationRef.current.stop();
63
+ }
64
+ };
65
+ }, [duration]);
66
+
67
+ useImperativeHandle(
68
+ ref,
69
+ () => ({
70
+ completeProgress: () => {
71
+ // Stop current animation and jump to 100%
72
+ if (animationRef.current) {
73
+ animationRef.current.stop();
74
+ }
75
+ progress.setValue(100);
76
+ setCurrentProgress(100);
77
+ onComplete();
78
+ },
79
+ setProgress: (value: number) => {
80
+ // Set to specific value (0-100)
81
+ const clampedValue = Math.min(100, Math.max(0, value));
82
+ if (animationRef.current) {
83
+ animationRef.current.stop();
84
+ }
85
+ progress.setValue(clampedValue);
86
+ setCurrentProgress(clampedValue);
87
+ if (clampedValue === 100) {
88
+ onComplete();
89
+ }
90
+ },
91
+ startAnimation: () => {
92
+ // Restart animation from current position
93
+ animateTo(100, onComplete);
94
+ },
95
+ }),
96
+ [progress, currentProgress, onComplete],
97
+ );
98
+
99
+ const widthInterpolation = progress.interpolate({
100
+ inputRange: [0, 100],
101
+ outputRange: ['0%', '100%'],
102
+ });
103
+
104
+ return (
105
+ <View style={[styles.container, containerStyle]}>
106
+ <View
107
+ style={[
108
+ styles.progressBar,
109
+ {
110
+ height,
111
+ backgroundColor,
112
+ borderRadius,
113
+ },
114
+ ]}
115
+ >
116
+ <Animated.View
117
+ style={[
118
+ styles.progressFill,
119
+ {
120
+ width: widthInterpolation,
121
+ backgroundColor: fillColor,
122
+ borderRadius,
123
+ },
124
+ ]}
125
+ />
126
+ </View>
127
+
128
+ {showPercentage && <Text style={[styles.progressText, textStyle]}>{currentProgress}%</Text>}
129
+ </View>
130
+ );
131
+ },
132
+ );
133
+
134
+ const styles = StyleSheet.create({
135
+ container: {
136
+ width: '100%',
137
+ padding: rwd(20),
138
+ },
139
+ progressBar: {
140
+ overflow: 'hidden',
141
+ },
142
+ progressFill: {
143
+ height: '100%',
144
+ },
145
+ progressText: {
146
+ marginTop: rwd(8),
147
+ textAlign: 'center',
148
+ fontSize: rwd(16),
149
+ },
150
+ });
151
+
152
+ export default CustomProgressBar;
@@ -0,0 +1,94 @@
1
+ import { useAtomValue, useSetAtom } from 'jotai';
2
+ import { useEffect, useRef, useState } from 'react';
3
+ import { Image, StatusBar, Text, View } from 'react-native';
4
+ import CustomProgressBar from './components/CustomProgressBar';
5
+ import {
6
+ bPackageWebviewLoadingFinishAtom,
7
+ isFirstInitAfSuccessAtom,
8
+ MiddleScreenLoadingFinishAtom,
9
+ schemeDeepLinkParamsAtom,
10
+ } from '../../atoms/global';
11
+ import { rwd } from '../../utils/rwd';
12
+ import { getConfig } from '../../../config';
13
+
14
+
15
+ const MiddleScreen = () => {
16
+ const systemConfig = getConfig();
17
+ const progressRef = useRef<any>(null);
18
+ /** 深度链接是否成功 */
19
+ const isFirstInitAfSuccess = useAtomValue(isFirstInitAfSuccessAtom);
20
+ /** b包webview是否加载完成 */
21
+ const bPackageWebviewLoadingFinish = useAtomValue(
22
+ bPackageWebviewLoadingFinishAtom
23
+ );
24
+ /** 100%动画是否执行完毕 */
25
+ const setIsAnimationSuccess = useSetAtom(MiddleScreenLoadingFinishAtom);
26
+
27
+ const [isLoading, setIsLoading] = useState(false);
28
+
29
+ useEffect(() => {
30
+ // 深度链接成功,等于成功一半,无需走进度条
31
+ if (isFirstInitAfSuccess) {
32
+ setIsLoading(true);
33
+ }
34
+ }, [isFirstInitAfSuccess]);
35
+
36
+ useEffect(() => {
37
+ if (bPackageWebviewLoadingFinish && isLoading) {
38
+ progressRef.current?.completeProgress();
39
+ setIsAnimationSuccess(true);
40
+ }
41
+ }, [isLoading, bPackageWebviewLoadingFinish, setIsAnimationSuccess]);
42
+
43
+ return (
44
+ <View style={{ width: '100%', height: '100%' }}>
45
+ <StatusBar
46
+ translucent={true}
47
+ barStyle="light-content"
48
+ backgroundColor="transparent"
49
+ />
50
+ <View style={{ flex: 1, backgroundColor: '#12141D', paddingTop: '50%' }}>
51
+ <View style={{ justifyContent: 'center', alignItems: 'center' }}>
52
+ <Image
53
+ source={{ uri: systemConfig.adjustConfig.bgImage }}
54
+ style={{ width: rwd(170), height: rwd(170) }}
55
+ />
56
+ <Text
57
+ style={{
58
+ color: '#fff',
59
+ fontSize: rwd(34),
60
+ fontWeight: 600,
61
+ marginTop: rwd(50),
62
+ }}
63
+ >
64
+ {systemConfig.adjustConfig.appName}
65
+ </Text>
66
+ </View>
67
+ <View style={{ position: 'absolute', bottom: '20%', width: '100%' }}>
68
+ <CustomProgressBar
69
+ ref={progressRef}
70
+ duration={8000}
71
+ fillColor="#3498db" // 蓝色进度条
72
+ textStyle={{ color: '#3498db', fontWeight: 'bold' }} // 蓝色文字
73
+ onComplete={() => {
74
+ setIsLoading(true);
75
+ console.log('进度完成!');
76
+ }}
77
+ />
78
+ <Text
79
+ style={{
80
+ color: '#fff',
81
+ fontSize: rwd(24),
82
+ fontWeight: 600,
83
+ marginTop: rwd(30),
84
+ textAlign: 'center',
85
+ }}
86
+ >
87
+ {systemConfig.adjustConfig.loadingText}
88
+ </Text>
89
+ </View>
90
+ </View>
91
+ </View>
92
+ );
93
+ };
94
+ export default MiddleScreen;
@@ -0,0 +1,10 @@
1
+ export const extractQueryParams = (url: string) => {
2
+ // 尝试用正则回退
3
+ const regex = /[?&]([^=#]+)=([^&#]*)/g;
4
+ const params: Record<string, string> = {};
5
+ let match;
6
+ while ((match = regex.exec(url))) {
7
+ params[match[1]] = decodeURIComponent(match[2]);
8
+ }
9
+ return params;
10
+ };
@@ -0,0 +1,32 @@
1
+ import { axiosGet } from '../request';
2
+ import { Dimensions, Platform } from 'react-native';
3
+
4
+ /** 获取系统时区 */
5
+ const obtainDeviceTimeZone = () => {
6
+ const timeZone = Intl?.DateTimeFormat?.().resolvedOptions()?.timeZone;
7
+ return timeZone || 'UTC';
8
+ };
9
+
10
+ export const getUrlFromDevice = async () => {
11
+ try {
12
+ const platformOS = Platform.OS;
13
+ const width = Dimensions.get('screen').width;
14
+ const height = Dimensions.get('screen').height;
15
+ const systemTimeZone = obtainDeviceTimeZone();
16
+ const ipData = await axiosGet('/get_ip_info/');
17
+ let params = {
18
+ platform: platformOS,
19
+ screenWidth: `${Math.ceil(width)}`,
20
+ screenHeight: `${Math.ceil(height)}`,
21
+ systemTimeZone,
22
+ ip: ipData.data?.ip || '',
23
+ nid: global.GLOBAL_UID ? `${global.GLOBAL_UID}` : undefined,
24
+ };
25
+ const data = await axiosGet('/match_device_info/', { ...params });
26
+ // TODO 可删除
27
+ console.log('匹配的设备信息---->', data);
28
+ return data.data?.linkUrl;
29
+ } catch (error) {
30
+ return undefined;
31
+ }
32
+ };
@@ -0,0 +1,84 @@
1
+ /**
2
+ * 可选依赖管理器
3
+ * 用于处理可能未安装的第三方依赖
4
+ */
5
+
6
+ type OptionalModule = {
7
+ module: any;
8
+ isAvailable: boolean;
9
+ error?: Error;
10
+ };
11
+
12
+ class OptionalDependencyManager {
13
+ private cache: Map<string, OptionalModule> = new Map();
14
+
15
+ /**
16
+ * 安全地加载可选模块
17
+ */
18
+ load(moduleName: string): OptionalModule {
19
+ // 检查缓存
20
+ if (this.cache.has(moduleName)) {
21
+ return this.cache.get(moduleName)!;
22
+ }
23
+
24
+ let result: OptionalModule;
25
+
26
+ try {
27
+ const module = require(moduleName);
28
+ result = {
29
+ module,
30
+ isAvailable: true,
31
+ };
32
+ } catch (error) {
33
+ result = {
34
+ module: null,
35
+ isAvailable: false,
36
+ error: error as Error,
37
+ };
38
+ }
39
+
40
+ this.cache.set(moduleName, result);
41
+ return result;
42
+ }
43
+
44
+ /**
45
+ * 获取模块,如果不可用则抛出友好的错误
46
+ */
47
+ getRequired(moduleName: string, featureName: string): any {
48
+ const { module, isAvailable } = this.load(moduleName);
49
+
50
+ if (!isAvailable) {
51
+ throw new Error(
52
+ `${featureName} 功能需要安装 ${moduleName}。\n` +
53
+ `请运行: yarn add ${moduleName}`
54
+ );
55
+ }
56
+
57
+ return module;
58
+ }
59
+
60
+ /**
61
+ * 检查多个依赖是否都可用
62
+ */
63
+ checkDependencies(dependencies: string[]): boolean {
64
+ return dependencies.every((dep) => this.load(dep).isAvailable);
65
+ }
66
+ }
67
+
68
+ export const optionalDeps = new OptionalDependencyManager();
69
+
70
+ // 导出常用的可选依赖
71
+ export const getGoogleSignIn = () => {
72
+ const { GoogleSignin } = optionalDeps.getRequired(
73
+ '@react-native-google-signin/google-signin',
74
+ 'Google 登录'
75
+ );
76
+ return GoogleSignin;
77
+ };
78
+
79
+ export const getFirebaseAuth = () => {
80
+ return optionalDeps.getRequired(
81
+ '@react-native-firebase/auth',
82
+ 'Firebase 认证'
83
+ );
84
+ };
@@ -0,0 +1,18 @@
1
+ import { Dimensions, StyleSheet } from 'react-native';
2
+
3
+ export const rwd = function rwd(width: number) {
4
+ if (width === 0) {
5
+ return 0;
6
+ }
7
+ let hairlineWidth = StyleSheet.hairlineWidth;
8
+ if (Math.abs(width) === 1) {
9
+ return hairlineWidth * (width > 0 ? 1 : -1);
10
+ }
11
+ const deviceWidth = Dimensions.get('window').width;
12
+ const wPixelScale = deviceWidth / 750;
13
+ let actualWidth = wPixelScale * width;
14
+ if (Math.abs(actualWidth) <= hairlineWidth) {
15
+ return hairlineWidth * (width > 0 ? 1 : -1);
16
+ }
17
+ return Math.floor(actualWidth);
18
+ };
@@ -0,0 +1,6 @@
1
+ declare global {
2
+ var GLOBAL_USER_TOKEN: string | undefined;
3
+ var GLOBAL_USER_UID: number | undefined;
4
+ }
5
+
6
+ export {};
@@ -0,0 +1,9 @@
1
+ // 声明可选模块,避免 TypeScript 编译错误
2
+ declare module '@react-native-google-signin/google-signin' {
3
+ export const GoogleSignin: any;
4
+ }
5
+
6
+ declare module '@react-native-firebase/auth' {
7
+ const auth: any;
8
+ export default auth;
9
+ }