Browse Source

addDom.js

jihuaqiang 2 years ago
parent
commit
95efac1092
3 changed files with 210 additions and 58 deletions
  1. 4 1
      src/pages/screens/redpack.tsx
  2. 83 9
      src/pages/screens/twitter.tsx
  3. 123 48
      src/utils/contentInTwitterJS/addDom.js

+ 4 - 1
src/pages/screens/redpack.tsx

@@ -23,7 +23,10 @@ class Redpack extends Component<Props> {
 	render() {
 		return (
 			<View style={{ flex: 1 }}>
-				<Text>redpack page: {this.props.route.params.tweet_Id}</Text>
+				<Text>tweet_Id: {this.props.route.params.tweet_Id}</Text>
+				<Text>post_Id: {this.props.route.params.post_Id}</Text>
+				<Text>invite_code: {this.props.route.params.invite_code}</Text>
+				<Text>ct0: {this.props.route.params.ct0}</Text>
 				<Button
 					onPress={this.favoriteTweet}
 					title="FavoriteTweet"

+ 83 - 9
src/pages/screens/twitter.tsx

@@ -2,7 +2,7 @@
 import React, { Component } from 'react';
 import { View, DeviceEventEmitter } from 'react-native';
 import { DenetWebview } from '@/components/webview';
-import { addDom } from '../../utils/contentInTwitterJS/addDom';
+import { addDom, addDataToStorge } from '../../utils/contentInTwitterJS/addDom';
 // import EventEmitter from 'react-native-eventemitter';
 
 interface Props {
@@ -12,13 +12,74 @@ class Twitter extends Component<Props> {
 	webref: any;
 	packUrl: any;
 
-	openRedpack = (props: any) => {
-		console.log(props.nativeEvent.data);
-		const { tweet_Id, ct0 } = JSON.parse(props.nativeEvent.data);
-		this.props.navigation.navigate('Redpack', {
-			tweet_Id,
-			ct0,
-		});
+	getPostIdByType = (post_Id: string) => {
+		let result: any = { post_Id };
+		if (post_Id.includes('nft/')) {
+			result.post_Id = post_Id.replace('nft/', '');
+			result.page_type = 'NFT';
+		} else if (post_Id.includes('nft_group/')) {
+			result.post_Id = post_Id.replace('nft_group/', '');
+			result.page_type = 'nft_group';
+		} else if (post_Id.includes('luckdraw/')) {
+			result.post_Id = post_Id.replace('luckdraw/', '');
+			result.page_type = '抽奖';
+		} else if (post_Id.includes('toolbox/')) {
+			result.post_Id = post_Id.split('toolbox/')[1] || '';
+			result.page_type = 'toolbox';
+		} else if (!post_Id.includes('/')) {
+			result.post_Id = post_Id;
+			result.page_type = '红包';
+		} else if (post_Id.includes('treasure/')) {
+			if (post_Id.includes('invite/')) {
+				post_Id = post_Id.replace('/undefined', '');
+				let arr = post_Id.split('/');
+				let index;
+				for (let i in arr) {
+					index = Number(i) + 1;
+					if (arr[i] == 'invite' && arr.length >= index) {
+						result.invite_code = arr[index];
+						if (arr.length > index + 1) {
+							result.invite_channel = arr[index + 1];
+						} else {
+							result.invite_channel = '';
+						}
+						break;
+					}
+				}
+
+				result.page_type = '邀请链接';
+				if (result.invite_code) {
+					result.post_Id = '';
+				}
+			} else {
+				// 原始链接
+				result.page_type = '原始链接';
+				result.post_Id = result.post_Id.split('treasure/')[1] || '';
+			}
+		}
+		return result;
+	};
+
+	onMessageHandle = async (messageData: any) => {
+		let { actionType, data } =
+			(messageData.nativeEvent.data &&
+				JSON.parse(messageData.nativeEvent.data)) ||
+			{};
+		switch (actionType) {
+			case 'goDetailPage':
+				// const { tweet_Id, ct0, post_Id, invite_code } = data;
+				this.props.navigation.navigate('Redpack', data);
+				break;
+			case 'fetchPostId':
+				const postId = await this.getPostId(data.short_url);
+				const postIdData = this.getPostIdByType(postId);
+				data = { ...data, ...postIdData };
+				this.webref.injectJavaScript(`
+				(${addDataToStorge})(${JSON.stringify(data)});
+				true;
+				`);
+				break;
+		}
 	};
 	handleWebViewNavigationStateChange = (newNavState: { url: any }) => {
 		const { url } = newNavState;
@@ -44,6 +105,19 @@ class Twitter extends Component<Props> {
     `);
 	};
 
+	getPostId(shortUrl: RequestInfo) {
+		return fetch(shortUrl) // 返回一个Promise对象
+			.then(res => {
+				return res.text(); // res.text()是一个Promise对象
+			})
+			.then(res => {
+				res = res.toString();
+				let str_arr = res.match(/denetme.net\/([\s\S]*?)"/) || [];
+				let post_Id = str_arr[1] || '';
+				return post_Id;
+			});
+	}
+
 	async componentDidMount() {
 		DeviceEventEmitter.addListener('FavoriteTweet', (data: any) => {
 			this.FavoriteTweet(data);
@@ -56,7 +130,7 @@ class Twitter extends Component<Props> {
 				<DenetWebview
 					onLoadEndHandle={this.injectJavaScript}
 					refHandle={r => (this.webref = r)}
-					onMessageHandle={this.openRedpack}
+					onMessageHandle={this.onMessageHandle}
 					handleWebViewNavigationStateChange={
 						this.handleWebViewNavigationStateChange
 					}

+ 123 - 48
src/utils/contentInTwitterJS/addDom.js

@@ -1,4 +1,34 @@
-import { parseAllDeNetCardParmas, getCardParmas } from './ParseCard';
+const addDataToStorge = data => {
+	function getStorage(key) {
+		const item = window.localStorage.getItem(key);
+		try {
+			return item ? JSON.parse(item) : [];
+		} catch (e) {
+			return item;
+		}
+	}
+
+	function setStorage(key, value) {
+		return window.localStorage.setItem(key, JSON.stringify(value) || '');
+	}
+
+	try {
+		let allData = getStorage('denetCardData');
+		if (
+			data.short_url &&
+			(data.post_Id || data.invite_code) &&
+			!allData.find(item => item.short_url === data.short_url)
+		) {
+			allData.push(data);
+			console.log('addDataToStorge', allData);
+			setStorage('denetCardData', allData);
+			return true;
+		}
+	} catch (error) {
+		console.log('error', error);
+	}
+};
+
 const addDom = () => {
 	window.denetJS = {};
 	window.denetJS.parseAllDeNetCard = () => {
@@ -48,7 +78,7 @@ const addDom = () => {
 		}
 		return { tweet_Id, short_url, dom_card };
 	};
-	window.denetJS.parseAllDeNetCardParmas = () => {
+	function parseAllDeNetCardParmas() {
 		let json_data = [];
 		window.denetJS.parseAllDeNetCard().forEach(item => {
 			let _obj = window.denetJS.parseCardParmas(item.dom);
@@ -58,13 +88,15 @@ const addDom = () => {
 			}
 		});
 		return json_data;
-	};
-	window.denetJS.toRedpackPage = ({ post_Id, tweet_Id }) => {
+	}
+	window.denetJS.toRedpackPage = item => {
 		window.ReactNativeWebView.postMessage(
 			JSON.stringify({
-				post_Id,
-				tweet_Id,
-				ct0: window.denetJS.getCookie('ct0'),
+				actionType: 'goDetailPage',
+				data: {
+					...item,
+					ct0: window.denetJS.getCookie('ct0'),
+				},
 			}),
 		);
 		window.event.stopPropagation();
@@ -127,78 +159,121 @@ const addDom = () => {
 			obj.style[atr] = css[atr];
 		}
 	}
-	function replaceDOMRedPacket({
-		dom_card,
-		tweet_Id,
-		post_Id,
-		time,
-		short_url,
-		page_type = '',
-	}) {
+	function replaceDOMRedPacket(item) {
+		const {
+			dom_card,
+			tweet_Id,
+			post_Id,
+			time,
+			short_url,
+			page_type = '',
+			invite_code,
+		} = item;
 		if (!dom_card || !dom_card.parentElement) {
 			return;
 		}
 		let type;
 		let dom = dom_card.querySelector('div[aria-labelledby]');
 		dom.style.position = 'relative';
-		// if (dom) {
-		// 	type = 'card';
-		// 	for (let i = 0; i < dom.childNodes.length; i++) {
-		// 		if (
-		// 			dom.childNodes[i].dataset &&
-		// 			dom.childNodes[i].dataset.testid &&
-		// 			dom.childNodes[i].dataset.testid == 'card.wrapper'
-		// 		) {
-		// 			dom.children[i].style.position = 'relative';
-		// 		}
-		// 	}
-		// } else {
-		// 	type = 'txt';
-		// 	dom = dom_card.querySelector('div[lang][dir=auto]').parentElement;
-		// }
-
-		// dom.style = 'min-height:500px';
+		if (dom) {
+			for (let i = 0; i < dom.childNodes.length; i++) {
+				if (
+					dom.childNodes[i].id &&
+					dom.childNodes[i].id == 'denet-card'
+				) {
+					return;
+				}
+			}
+		}
 		if (dom) {
 			// debugger mode
 			let div = document.createElement('div');
 			div.addEventListener('click', () => {
-				window.denetJS.toRedpackPage({ post_Id, tweet_Id });
+				window.denetJS.toRedpackPage({
+					tweet_Id,
+					post_Id,
+					time,
+					short_url,
+					page_type,
+					invite_code,
+				});
 			});
 			div.id = 'denet-card';
 			setStyle(div, {
 				position: 'absolute',
 				width: '100%',
 				height: '100%',
+				background: 'rgba(0,0,0,.3)',
 				'z-index': 1,
+				'text-align': 'center',
+				color: '#fff',
+				'font-size': '30px',
 			});
-			// div.innerHTML = `
-			// 	<h2>这里是自定义插入的内容</h2>
-			//     tweet_Id:${tweet_Id} ,
-			//     post_Id:${post_Id}
-			//     获取dom时间:${time}
-			//     短链接:${short_url}<img onclick="toRedpackPage()" src="https://pbs.twimg.com/card_img/1559498011880804353/yV6kTKyQ?format=jpg&name=small" style="width: 100%"/>
-			//     渲染时长:${(new Date().getTime() - time) / 1000}s
-			//     `;
+			div.innerText = 'OPEN IT';
 			dom.appendChild(div);
-			// window.TwitterLikeAPI(1559235463868710917);
+		}
+	}
 
-			// dom.appendChild(this.createIframe({post_Id, tweet_Id, page_type}));
+	function setStorage(key, value) {
+		return window.localStorage.setItem(key, JSON.stringify(value) || '');
+	}
+
+	function getStorage(key) {
+		const item = window.localStorage.getItem(key);
+		try {
+			return item ? JSON.parse(item) : '';
+		} catch (e) {
+			return item;
 		}
 	}
 
+	function getCardFromStorge(query) {
+		return new Promise((res, rej) => {
+			const denetCardData = getStorage('denetCardData') || [];
+			const thisCardData = denetCardData.find(
+				item => item.short_url === query.short_url,
+			);
+			if (thisCardData) {
+				res(thisCardData);
+			} else {
+				window.ReactNativeWebView.postMessage(
+					JSON.stringify({
+						actionType: 'fetchPostId',
+						data: {
+							// dom_card: query.dom_card,
+							short_url: query.short_url,
+							time: query.time,
+							tweet_Id: query.tweet_Id,
+						},
+					}),
+				);
+				res(null);
+			}
+		});
+	}
+
 	try {
 		let timer = setInterval(() => {
-			let card_json_data = window.denetJS.parseAllDeNetCardParmas();
+			let card_json_data = parseAllDeNetCardParmas();
 			if (card_json_data.length) {
-				// clearInterval(timer);
 				for (let i = 0; i < card_json_data.length; i++) {
-					replaceDOMRedPacket(card_json_data[i]);
+					getCardFromStorge(card_json_data[i]).then(thisCardData => {
+						if (
+							thisCardData &&
+							(thisCardData.post_Id || thisCardData.invite_code)
+						) {
+							replaceDOMRedPacket({
+								...card_json_data[i],
+								...thisCardData,
+							});
+						}
+					});
 				}
 			}
-		}, 1000);
+		}, 3000);
 	} catch (error) {
 		console.log(error);
 	}
 };
 
-export { addDom };
+export { addDom, addDataToStorge };