Skip to content

Commit

Permalink
feat: (#25, #31) custom web path
Browse files Browse the repository at this point in the history
  • Loading branch information
7Sageer committed Sep 15, 2024
1 parent 0cdb6f4 commit 619456e
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 30 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ Sublink Worker 是一个可部署在 Cloudflare Worker 上轻量级的订阅转

## 最近更新

- 2024-09-13
- [#27](https://github.com/7Sageer/sublink-worker/issues/27) 优化了出站选择排布
- 2024-09-15
- [#31](https://github.com/7Sageer/sublink-worker/issues/31),[#25](https://github.com/7Sageer/sublink-worker/issues/25) 现在可以自定义短链接路径

[查看更新日志](/doc/update-log.md)

Expand Down
4 changes: 4 additions & 0 deletions doc/update-log.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# 更新日志

## 2024-09-15

- ([#31](https://github.com/7Sageer/sublink-worker/issues/31),[#25](https://github.com/7Sageer/sublink-worker/issues/25)) 现在可以自定义短链接路径

## 2024-09-13

- ([#27](https://github.com/7Sageer/sublink-worker/issues/27)) 优化了出站选择排布
Expand Down
57 changes: 30 additions & 27 deletions src/htmlBuilder.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { UNIFIED_RULES, PREDEFINED_RULE_SETS } from './config.js';

export function generateHtml(xrayUrl, singboxUrl, clashUrl) {
export function generateHtml(xrayUrl, singboxUrl, clashUrl, baseUrl) {
return `
<!DOCTYPE html>
<html lang="en">
${generateHead()}
${generateBody(xrayUrl, singboxUrl, clashUrl)}
${generateBody(xrayUrl, singboxUrl, clashUrl, baseUrl)}
</html>
`;
}
Expand Down Expand Up @@ -369,7 +369,7 @@ const generateStyles = () => `
`;

const generateBody = (xrayUrl, singboxUrl, clashUrl) => `
const generateBody = (xrayUrl, singboxUrl, clashUrl, baseUrl) => `
<body>
${generateDarkModeToggle()}
${generateGithubLink()}
Expand All @@ -378,7 +378,7 @@ const generateBody = (xrayUrl, singboxUrl, clashUrl) => `
${generateCardHeader()}
<div class="card-body">
${generateForm()}
${generateSubscribeLinks(xrayUrl, singboxUrl, clashUrl)}
${generateSubscribeLinks(xrayUrl, singboxUrl, clashUrl, baseUrl)}
</div>
</div>
</div>
Expand Down Expand Up @@ -417,25 +417,30 @@ const generateForm = () => `
<div id="advancedOptions">
${generateRuleSetSelection()}
</div>
<div class="d-grid mt-4">
<button type="submit" class="btn btn-primary btn-lg">
<i class="fas fa-sync-alt me-2"></i>Convert
</button>
</div>
<div class="d-grid mt-2">
<button type="button" class="btn btn-secondary btn-lg" id="clearFormBtn">
<i class="fas fa-trash-alt me-2"></i>Clear Form
</button>
</div>
<div class="d-flex mt-4">
<button type="submit" class="btn btn-primary btn-lg me-2" style="flex: 6;">
<i class="fas fa-sync-alt me-2"></i>Convert
</button>
<button type="button" class="btn btn-secondary btn-lg" id="clearFormBtn" style="flex: 4;">
<i class="fas fa-trash-alt me-2"></i>Clear Form
</button>
</div>
</form>
`;

const generateSubscribeLinks = (xrayUrl, singboxUrl, clashUrl) => `
const generateSubscribeLinks = (xrayUrl, singboxUrl, clashUrl, baseUrl) => `
<div class="mt-5">
<h2 class="mb-4">Your subscribe links:</h2>
${generateLinkInput('Xray Link:', 'xrayLink', xrayUrl)}
${generateLinkInput('SingBox Link:', 'singboxLink', singboxUrl)}
${generateLinkInput('Clash Link:', 'clashLink', clashUrl)}
<div class="mb-3">
<label for="customShortCode" class="form-label">Custom Path (optional):</label>
<div class="input-group">
<span class="input-group-text" id="basic-addon3">${baseUrl}/s/</span>
<input type="text" class="form-control" id="customShortCode" placeholder="Enter custom short code">
</div>
</div>
<div class="d-grid">
<button class="btn btn-primary btn-lg" type="button" onclick="shortenAllUrls()">
<i class="fas fa-compress-alt me-2"></i>Shorten Links
Expand Down Expand Up @@ -505,11 +510,11 @@ const copyToClipboardFunction = () => `
`;

const shortenAllUrlsFunction = () => `
async function shortenUrl(url) {
const response = await fetch(\`/shorten?url=\${encodeURIComponent(url)}\`);
async function shortenUrl(url, customShortCode) {
const response = await fetch(\`/shorten-v2?url=\${encodeURIComponent(url)}&shortCode=\${encodeURIComponent(customShortCode || '')}\`);
if (response.ok) {
const data = await response.json();
return data.shortUrl;
const data = await response.text();
return data;
}
throw new Error('Failed to shorten URL');
}
Expand All @@ -523,18 +528,16 @@ const shortenAllUrlsFunction = () => `
const xrayLink = document.getElementById('xrayLink');
const singboxLink = document.getElementById('singboxLink');
const clashLink = document.getElementById('clashLink');
const customShortCode = document.getElementById('customShortCode').value;
const [xrayShortUrl, singboxShortUrl, clashShortUrl] = await Promise.all([
shortenUrl(xrayLink.value),
shortenUrl(singboxLink.value),
shortenUrl(clashLink.value)
]);
const shortCode = await shortenUrl(singboxLink.value, customShortCode);
xrayLink.value = xrayShortUrl;
singboxLink.value = singboxShortUrl;
clashLink.value = clashShortUrl;
xrayLink.value = window.location.origin + '/x/' + shortCode;
singboxLink.value = window.location.origin + '/b/' + shortCode;
clashLink.value = window.location.origin + '/c/' + shortCode;
} catch (error) {
console.error('Error:', error);
alert('Failed to shorten URLs. Please try again.');
} finally {
shortenButton.disabled = false;
shortenButton.innerHTML = '<i class="fas fa-compress-alt me-2"></i>Shorten Links';
Expand Down
49 changes: 48 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ async function handleRequest(request) {

if (request.method === 'GET' && url.pathname === '/') {
// Return the HTML form for GET requests
return new Response(generateHtml('', '', ''), {
return new Response(generateHtml('', '', '', url.origin), {
headers: { 'Content-Type': 'text/html' }
});
} else if (request.method === 'POST' && url.pathname === '/') {
Expand Down Expand Up @@ -49,6 +49,8 @@ async function handleRequest(request) {
let selectedRules = url.searchParams.get('selectedRules');
let customRules = url.searchParams.get('customRules');

console.log(customRules);

if (!inputString) {
return new Response('Missing config parameter', { status: 400 });
}
Expand Down Expand Up @@ -106,6 +108,31 @@ async function handleRequest(request) {
return new Response(JSON.stringify({ shortUrl }), {
headers: { 'Content-Type': 'application/json' }
});

} else if (url.pathname === '/shorten-v2'){
const originalUrl = url.searchParams.get('url');
let shortCode = url.searchParams.get('shortCode');

if (!originalUrl) {
return new Response('Missing URL parameter', { status: 400 });
}

// 创建一个 URL 对象来正确解析原始 URL
const parsedUrl = new URL(originalUrl);
const queryString = parsedUrl.search;

if (!shortCode) {
shortCode = GenerateWebPath();
}

await SUBLINK_KV.put(shortCode, queryString);

console.log(JSON.stringify(shortCode));

return new Response(shortCode, {
headers: { 'Content-Type': 'text/plain' }
});

} else if (url.pathname.startsWith('/s/')) {
const shortCode = url.pathname.split('/')[2];
const originalUrl = await SUBLINK_KV.get(shortCode);
Expand All @@ -114,6 +141,26 @@ async function handleRequest(request) {
return new Response('Short URL not found', { status: 404 });
}

return Response.redirect(originalUrl, 302);
} else if (url.pathname.startsWith('/b/') || url.pathname.startsWith('/c/') || url.pathname.startsWith('/x/')) {
const shortCode = url.pathname.split('/')[2];
const originalParam = await SUBLINK_KV.get(shortCode);
let originalUrl;

if (url.pathname.startsWith('/b/')) {
originalUrl = `${url.origin}/singbox${originalParam}`;
} else if (url.pathname.startsWith('/c/')) {
originalUrl = `${url.origin}/clash${originalParam}`;
} else if (url.pathname.startsWith('/x/')) {
originalUrl = `${url.origin}/xray${originalParam}`;
}

console.log(originalUrl);

if (originalUrl === null) {
return new Response('Short URL not found', { status: 404 });
}

return Response.redirect(originalUrl, 302);
} else if (url.pathname.startsWith('/xray')) {
// Handle Xray config requests
Expand Down

0 comments on commit 619456e

Please sign in to comment.