Merge branch 'up/feat/multi-link-downloader' into chore/all-my-stuffs

This commit is contained in:
ShareVB committed 2024-11-20 22:55:57 +01:00
commit c5791b13e9
7 files changed
+3398 -7942

No files matched your search

+4
View File
@@ -435,3 +435,7 @@ tools:
json-to-object:
title: JSON to object
description: Parse and convert JSON to object.
multi-link-downloader:
title: Multi link downloader
description: Asynchronously downloads from multiple links into a zip file while a single link downloads directly. (Requires an internet connection)
+1
View File
@@ -153,6 +153,7 @@
"json-editor-vue": "^0.16.0",
"json2csharp": "^1.0.3",
"json5": "^2.2.3",
"jszip": "^3.10.1",
"jsonar-mod": "^1.9.0",
"jsonlint-mod": "^1.7.6",
"jsonpath": "^1.1.1",
+3219 -7942
View File
File diff suppressed because it is too large. Load diff
+2
View File
@@ -1,6 +1,7 @@
import { tool as base64FileConverter } from './base64-file-converter';
import { tool as base64StringConverter } from './base64-string-converter';
import { tool as basicAuthGenerator } from './basic-auth-generator';
import { tool as multiLinkDownloader } from './multi-link-downloader';
import { tool as aspectRatioCalculator } from './aspect-ratio-calculator';
import { tool as extractTextFromHtml } from './extract-text-from-html';
import { tool as propertiesToYaml } from './properties-to-yaml';
@@ -542,6 +543,7 @@ export const toolsByCategory: ToolCategory[] = [
luhnValidator,
vatValidator,
isbnValidatorAndParser,
multiLinkDownloader,
],
},
];
+12
View File
@@ -0,0 +1,12 @@
import { IconFileDownload } from '@tabler/icons-vue';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'Multi link downloader',
path: '/multi-link-downloader',
description: '',
keywords: ['multi', 'link', 'downloader'],
component: () => import('./multi-link-downloader.vue'),
icon: IconFileDownload,
createdAt: new Date('2024-10-18'),
});
@@ -0,0 +1,108 @@
import JSZip from 'jszip';
export async function downloadLinks(links: string): Promise<void> {
// Split links by newline and filter out empty ones
const linksArray: string[] = links.split('\n').filter(link => link.trim() !== '');
// Helper function to handle duplicate filenames
function getUniqueFileName(existingNames: Set<string>, originalName: string): string {
let fileName = originalName;
let fileExtension = '';
// Split filename and extension (if any)
const lastDotIndex = originalName.lastIndexOf('.');
if (lastDotIndex !== -1) {
fileName = originalName.substring(0, lastDotIndex);
fileExtension = originalName.substring(lastDotIndex);
}
let counter = 1;
let uniqueName = originalName;
// Append a counter to the filename if it already exists in the map
while (existingNames.has(uniqueName)) {
uniqueName = `${fileName} (${counter})${fileExtension}`;
counter++;
}
existingNames.add(uniqueName);
return uniqueName;
}
if (linksArray.length === 1) {
// Single link: download directly
const linkUrl: string = linksArray[0];
try {
const response: Response = await fetch(linkUrl);
if (!response.ok) {
throw new Error(`Failed to fetch ${linkUrl}`);
}
// Get file as blob
const blob: Blob = await response.blob();
// Extract filename from URL
const fileName: string = linkUrl.split('/').pop() || 'downloaded_file';
// Trigger download
const a: HTMLAnchorElement = document.createElement('a');
const downloadUrl: string = window.URL.createObjectURL(blob);
a.href = downloadUrl;
a.download = fileName;
document.body.appendChild(a);
a.click();
// Clean up
document.body.removeChild(a);
window.URL.revokeObjectURL(downloadUrl);
}
catch (error) {
console.error('Error downloading the file:', error);
}
}
else if (linksArray.length > 1) {
// Multiple links: create a zip file
const zip = new JSZip();
const fileNamesSet = new Set<string>(); // To track file names for duplicates
await Promise.all(
linksArray.map(async (linkUrl: string) => {
try {
const response: Response = await fetch(linkUrl);
if (!response.ok) {
throw new Error(`Failed to fetch ${linkUrl}`);
}
const blob: Blob = await response.blob();
// Extract filename from URL
let fileName: string = linkUrl.split('/').pop() || 'file';
// Get unique filename if duplicate exists
fileName = getUniqueFileName(fileNamesSet, fileName);
// Add file to the zip
zip.file(fileName, blob);
}
catch (error) {
console.error(`Error downloading file from ${linkUrl}:`, error);
}
}),
);
// Generate the zip file and trigger download
zip.generateAsync({ type: 'blob' }).then((zipBlob: Blob) => {
const downloadUrl: string = window.URL.createObjectURL(zipBlob);
// Trigger download of the zip file
const a: HTMLAnchorElement = document.createElement('a');
a.href = downloadUrl;
a.download = 'downloaded_files.zip';
document.body.appendChild(a);
a.click();
// Clean up
document.body.removeChild(a);
window.URL.revokeObjectURL(downloadUrl);
});
}
}
@@ -0,0 +1,52 @@
<script lang="ts">
import { defineComponent, ref } from 'vue';
import { downloadLinks } from './multi-link-downloader.service';
export default defineComponent({
setup() {
const links = ref<string>('');
const downloadMultiLinks = () => {
if (links.value) {
downloadLinks(links.value);
}
};
const clearInput = () => {
links.value = '';
};
return {
links,
downloadMultiLinks,
clearInput,
};
},
});
</script>
<template>
<c-card>
<div class="mb-4 flex justify-between">
<c-button
class="mr-2"
:disabled="!links"
@click="downloadMultiLinks"
>
Start Download
</c-button>
<c-button
class="ml-2"
@click="clearInput"
>
Clear
</c-button>
</div>
<c-input-text
v-model:value="links"
placeholder="Add links separated by new lines..."
multiline
:rows="20"
/>
</c-card>
</template>