You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Global-sales/src/components/Shorturlchange.jsx

95 lines
2.9 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import { useCallback } from 'react';
import { notification } from 'antd';
const useShortUrlChange = () => {
const apiPrefix = {
"japanhighlights.com": "https://www.japanhighlights.com/index.php",
"chinahighlights.com": "https://www.chinahighlights.com/guide-use.php",
"highlightstravel.com": "https://www.highlightstravel.com/index.php",
"asiahighlights.com": "https://www.asiahighlights.com/index.php",
"globalhighlights.com": "https://www.globalhighlights.com/index.php",
};
const fetchNowConversationsitems = async (base64Url, apiUrl) => {
try {
const formData = new FormData();
formData.append('url', base64Url);
formData.append('type', 'info');
const response = await fetch(`${apiUrl}/apps/short_link/index/create`, {
method: 'POST',
body: formData,
});
const data = await response.json();
if (data[0].name == 'ok') {
return data[0].value;
}
return null;
} catch (error) {
console.error('获取短链接转换内容失败:', error);
return null;
}
};
const urlBase64 = (longUrl) => {
try {
const extracted1 = longUrl.match(/^https?:\/\/[^\/]*/)?.[0] || '';
const extracted2 = longUrl.match(/https:\/\/www\.([^\/]+)/)?.[1] || '';
const encoder = new TextEncoder();
const utf8Bytes = encoder.encode(longUrl);
const base64Url = btoa(String.fromCharCode(...utf8Bytes));
return { base64Url, extracted1, extracted2 };
} catch (error) {
notification.error({
message: '错误',
description: '转换失败请检查输入的URL是否正确',
});
console.error('URL转换错误:', error);
return { base64Url: '', extracted1: '', extracted2: '' };
}
};
const convertUrl = useCallback(async (longUrl) => {
if (!longUrl.trim()) {
notification.error({
message: '错误',
description: '不是有效的长链接',
});
return null;
}
const { base64Url, extracted1, extracted2 } = urlBase64(longUrl);
if (base64Url && extracted1) {
const apiUrl = apiPrefix[extracted2] || apiPrefix["chinahighlights.com"];
const data = await fetchNowConversationsitems(base64Url, apiUrl);
if (data) {
const resultShortUrl = extracted1 + data.isl_link;
notification.success({
message: '成功',
description: '转换成功!',
});
return resultShortUrl;
} else {
notification.error({
message: '错误',
description: '转换失败请检查输入的URL是否正确',
});
return null;
}
} else {
notification.error({
message: '错误',
description: 'URL格式不正确请输入完整的URL',
});
return null;
}
}, []);
return { convertUrl };
};
export default useShortUrlChange;