terabox-upload-tool 1.0.0 → 1.2.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025,
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,20 +1,23 @@
1
1
  # Terabox Upload Tool
2
2
 
3
- A simple and efficient Node.js library for uploading files to [TeraBox](https://www.terabox.com/wap) storage. This tool streamlines the process of file uploads while offering customization options such as directory selection.
3
+ A simple and efficient Node.js library for uploading files and fetching file list from [TeraBox](https://www.terabox.com/wap) storage. This tool streamlines the process of file uploads while offering customization options such as directory selection.
4
4
 
5
5
  ## Features
6
6
 
7
7
  * File Upload: Easily upload files to Terabox storage.
8
8
  * Custom Directory Support: Specify the directory where the file should be uploaded.
9
9
  * Progress Tracking: Monitor the upload progress in real-time.
10
-
10
+ * Fetch File List: Fetch file list from any directory.
11
+ * Get direct file download link
11
12
 
12
13
  ## Coming Soon (Open for Collaboration)
13
14
 
14
- * Fetch Files: Retrieve the files stored in your Terabox account.
15
+ * Fetch Files: Retrieve the resources download URL and add URL Path in JSON object returned by existing [fetchFileList() ](./lib/index.js)method . ✅
15
16
  * Delete Files: Remove files from your Terabox storage directly using this library.
16
-
17
-
17
+ * Video Streaming: Support for streaming videos.
18
+ * Fetch Upload History
19
+ * Fetch Download History
20
+ * Restructure code and files
18
21
 
19
22
  ## Installation
20
23
 
@@ -22,7 +25,6 @@ Install the package using npm:
22
25
 
23
26
  ```bash
24
27
  npm install terabox-upload-tool
25
-
26
28
  ```
27
29
 
28
30
  ## Getting Started
@@ -39,7 +41,9 @@ const credentials = {
39
41
  };
40
42
 
41
43
  ```
44
+
42
45
  ### Uploading a File
46
+
43
47
  To upload a file, create an instance of TeraboxUploader and specify the file path.
44
48
 
45
49
  #### Example: Save File to a Specific Directory
@@ -47,44 +51,52 @@ To upload a file, create an instance of TeraboxUploader and specify the file pat
47
51
  ```javascript
48
52
  const uploader = new TeraboxUploader(credentials);
49
53
 
50
- const filePath = './path/to/your/file.jpg';
54
+ async function uploadFile() {
55
+ try {
56
+ const result = await uploader.uploadFile(filePath, showProgress, '/myUploads');
57
+ if (result.success) {
58
+ console.log('File uploaded successfully!');
59
+ console.log('File details:', result.fileDetails);
60
+ } else {
61
+ console.log('Upload failed:', result.message);
62
+ }
63
+ } catch (error) {
64
+ console.log('An error occurred during the upload:', error.message);
65
+ }
66
+ }
51
67
 
52
- // Uploads to '/my-uploads'
53
- uploader.uploadFile(filePath, (uploaded, total) => {
54
- console.log(`Progress: ${(uploaded / total * 100).toFixed(2)}%`);
55
- }, '/my-uploads');
56
68
  ```
57
69
 
58
- #### Example: Save File to Root Directly
70
+ #### Example: Fetch a list of files from Terabox
59
71
 
60
72
  ```javascript
61
-
62
- // Uploads to '/'
63
- uploader.uploadFile(filePath, (uploaded, total) => {
64
- console.log(`Progress: ${(uploaded / total * 100).toFixed(2)}%`);
65
- }, '/my-uploads');
73
+ async function fetchFileList() {
74
+ try {
75
+ const fileList=await uploader.fetchFileList('/myUploads');
76
+ console.log('Files in your directory:', fileList);
77
+ } catch (error) {
78
+ console.log('Error fetching file list:', error.message);
79
+ }
80
+ }
66
81
  ```
67
82
 
68
- ## Future Enhancements (Open Collaboration)
69
- We are actively seeking contributors to add the following features:
83
+ Future Enhancements (Open Collaboration)
70
84
 
71
- 1. Fetch Files:
72
- * Implement functionality to list files stored in Terabox directories.
73
- * Provide options to filter by file types, size, or date modified.
85
+ We are actively seeking contributors to add the following features:
74
86
 
75
- 2. Delete Files:
76
- * Enable users to delete specific files or directories from their Terabox storage.
77
- * Include safeguards like confirmation prompts before deletion.
87
+ 1. Delete Files:
78
88
 
79
- 3. Error Handling Enhancements:
80
- * Improve error messages for easier debugging and user guidance.
89
+ * Enable users to delete specific files or directories from their Terabox storage.
90
+ * Include safeguards like confirmation prompts before deletion.
91
+ 2. Error Handling Enhancements:
81
92
 
82
- 4. Automated Tests:
83
- * Add test cases to ensure reliability and robustness.
93
+ * Improve error messages for easier debugging and user guidance.
94
+ 3. Automated Tests:
84
95
 
85
- 5. Documentation Updates:
96
+ * Add test cases to ensure reliability and robustness.
97
+ 4. Documentation Updates:
86
98
 
87
- * Expand guides with screenshots and example workflows.
99
+ * Expand guides with screenshots and example workflows.
88
100
 
89
101
  ## Contribution Guidelines
90
102
 
@@ -96,10 +108,10 @@ We welcome contributions from the community! Here’s how you can get started:
96
108
  4. Feel free to open issues for feature requests or bug reports.
97
109
 
98
110
  ## Resources for Developers
111
+
99
112
  * [Node.js File System Documentation](https://nodejs.org/api/fs.html)
100
113
  * [Chrome Dev-Tools (Networks)](https://developer.chrome.com/docs/devtools/network)
101
114
 
102
-
103
115
  <br>
104
116
 
105
117
  Terabox Node.js Library
@@ -146,12 +158,8 @@ Get the 'ndus' from cookies in the header section
146
158
  <br>
147
159
  <br>
148
160
 
149
-
150
-
151
-
152
161
  ## Licence
153
162
 
154
- This project is licensed under the [MIT License.]()
155
-
156
-
163
+ This project is licensed under the [MIT License.](./LICENSE)
157
164
 
165
+ [Github](https://github.com/Pahadi10/terabox-upload-tool)
@@ -0,0 +1,118 @@
1
+ // syscfg APIへのリクエスト
2
+ async function getSysCfg() {
3
+ const url = 'https://www.terabox.com/api/getsyscfg';
4
+ const params = {
5
+ app_id: '250528',
6
+ web: '1',
7
+ channel: 'dubox',
8
+ clienttype: '0',
9
+ jsToken: 'BDFC7E99221F980D72CA17B19C98F23E35D1C43EBD1B76F2CE493F27A1C2E7C71D7F637156999EF9A71106D82A4836DE040DA96397B95B7F95DDE4836EA0766B',
10
+ 'dp-logid': '18397400250736220038',
11
+ cfg_category_keys: '[{"cfg_category_key":"web_download_to_pc_exp_flow_new","cfg_version":1},{"cfg_category_key":"web_download_to_pc","cfg_version":1}]',
12
+ version: '0',
13
+ language_type: 'ja'
14
+ };
15
+
16
+ const response = await fetch(`${url}?${new URLSearchParams(params)}`, {
17
+ method: 'GET',
18
+ headers: {
19
+ 'Content-Type': 'application/json'
20
+ }
21
+ });
22
+
23
+ const data = await response.json();
24
+ return data;
25
+ }
26
+
27
+ // home info APIへのリクエスト
28
+ async function getHomeInfo() {
29
+ const url = 'https://www.terabox.com/api/home/info';
30
+ const params = {
31
+ app_id: '250528',
32
+ web: '1',
33
+ channel: 'dubox',
34
+ clienttype: '0',
35
+ jsToken: 'BDFC7E99221F980D72CA17B19C98F23E35D1C43EBD1B76F2CE493F27A1C2E7C71D7F637156999EF9A71106D82A4836DE040DA96397B95B7F95DDE4836EA0766B',
36
+ 'dp-logid': '18397400250736220039'
37
+ };
38
+
39
+ const response = await fetch(`${url}?${new URLSearchParams(params)}`, {
40
+ method: 'GET',
41
+ headers: {
42
+ 'Content-Type': 'application/json'
43
+ }
44
+ });
45
+
46
+ const data = await response.json();
47
+ return data;
48
+ }
49
+
50
+ // ダウンロードURL取得のための関数
51
+ async function getDownloadUrl(fidlist) {
52
+ const sysCfg = await getSysCfg();
53
+ const homeInfo = await getHomeInfo();
54
+
55
+ console.log('System Configuration:', sysCfg);
56
+ console.log('Home Info:', homeInfo);
57
+
58
+ const downloadUrl = 'https://www.terabox.com/api/download';
59
+
60
+ // ダウンロードパラメータの設定
61
+ const params = {
62
+ app_id: '250528',
63
+ web: '1',
64
+ channel: 'dubox',
65
+ clienttype: '0',
66
+ jsToken: 'BDFC7E99221F980D72CA17B19C98F23E35D1C43EBD1B76F2CE493F27A1C2E7C71D7F637156999EF9A71106D82A4836DE040DA96397B95B7F95DDE4836EA0766B',
67
+ 'dp-logid': '18397400250736220040',
68
+ fidlist: JSON.stringify(fidlist), // fidlistを渡す
69
+ type: 'dlink',
70
+ vip: '2',
71
+ sign: 'VeJPxoh1ryXIWRvdcBXzMXJvl9iJMry0sUyKk7FrD5ohO4wghBmZ7w==',
72
+ timestamp: '1737845700',
73
+ need_speed: '0',
74
+ bdstoken: 'bbc878665ecd53f583ce583d16deddd9'
75
+ };
76
+
77
+ // ダウンロードリクエスト送信
78
+ const response = await fetch(`${downloadUrl}?${new URLSearchParams(params)}`, {
79
+ method: 'GET',
80
+ headers: {
81
+ 'Content-Type': 'application/json'
82
+ }
83
+ });
84
+
85
+ const data = await response.json();
86
+
87
+ // ダウンロードリンクが存在する場合、リンクを返す
88
+ if (data.dlink && data.dlink.length > 0) {
89
+ return data.dlink[0].dlink;
90
+ } else {
91
+ throw new Error('Download link not found.');
92
+ }
93
+ }
94
+
95
+ // `dlFiles` 関数: ダウンロードリンクを返す
96
+ async function dlFiles(fidlist) {
97
+ try {
98
+ const downloadLink = await getDownloadUrl(fidlist);
99
+ return downloadLink;
100
+ } catch (error) {
101
+ console.error('Error:', error);
102
+ throw error; // エラーがあった場合は再度投げる
103
+ }
104
+ }
105
+
106
+ // 使用例
107
+ (async () => {
108
+ try {
109
+ const fidlist = [546136331131393]; // ダウンロード対象のファイルIDリスト
110
+ const downloadLink = await dlFiles(fidlist);
111
+ console.log('Download Link:', downloadLink);
112
+
113
+ // ダウンロードリンクが取得できたら、URLを返す
114
+ return downloadLink;
115
+ } catch (error) {
116
+ console.error('Error:', error);
117
+ }
118
+ })();
@@ -1,24 +1,57 @@
1
- const TeraboxUploader = require('terabox-upload-tool');
1
+ // Import the TeraboxUploader class from your library
2
+ const TeraboxUploader = require('./index'); // Make sure to use the correct path to your module
2
3
 
3
- // Set up credentials for your account
4
+ // Step 1: Set up your Terabox credentials
4
5
  const credentials = {
5
- ndus: 'valid_ndus',
6
- appId: 'valid_appId',
7
- uploadId: 'valid_uploadId'
6
+ ndus: 'your-ndus-token', // Replace with your actual ndus token
7
+ appId: 'your-app-id', // Replace with your actual appId
8
+ uploadId: 'your-upload-id', // Replace with your actual uploadId
8
9
  };
9
10
 
11
+ // Step 2: Create a new instance of the TeraboxUploader with your credentials
10
12
  const uploader = new TeraboxUploader(credentials);
11
13
 
12
- // Upload a file
13
- const filePath = './path/to/your/file.jpg';
14
+ // Step 3: Define the file you want to upload (replace with the path to your file)
15
+ const filePath = './path/to/your/file.txt'; // Example: './myDocuments/photo.jpg'
14
16
 
17
+ // Step 4: (Optional) Track upload progress with a simple callback function
18
+ // This will show how much of the file has been uploaded
19
+ const showProgress = (loaded, total) => {
20
+ const percentage = ((loaded / total) * 100).toFixed(2);
21
+ console.log(`Uploading... ${percentage}% complete`);
22
+ };
23
+
24
+ // Step 5: Upload the file
25
+ async function uploadFile() {
26
+ try {
27
+ // Upload the file to Terabox, specify a directory (optional)
28
+ const result = await uploader.uploadFile(filePath, showProgress, '/myUploads'); // Change '/myUploads' to your desired directory
29
+
30
+ // Check if the upload was successful
31
+ if (result.success) {
32
+ console.log('File uploaded successfully!');
33
+ console.log('File details:', result.fileDetails); // Show details of the uploaded file
34
+ } else {
35
+ console.log('Upload failed:', result.message); // Show error message
36
+ }
37
+ } catch (error) {
38
+ console.log('An error occurred during the upload:', error.message); // Handle any errors
39
+ }
40
+ }
41
+
42
+ // Step 6: Fetch a list of files from Terabox (optional)
43
+ async function fetchFileList() {
44
+ try {
45
+ // Get a list of files from your Terabox account
46
+ const fileList = await uploader.fetchFileList('/myUploads'); // Specify the directory to list files
47
+ console.log('Files in your directory:', fileList); // Show the list of files
48
+ } catch (error) {
49
+ console.log('Error fetching file list:', error.message); // Handle any errors
50
+ }
51
+ }
52
+
53
+ // Step 7: Call the functions to upload the file and/or fetch the file list
15
54
 
16
- // Save file in a specific directory, e.g., '/my-uploads'
17
- uploader.uploadFile(filePath, (uploaded, total) => {
18
- console.log(`Progress: ${(uploaded / total * 100).toFixed(2)}%`);
19
- }, '/my-uploads');
55
+ // uploadFile(); // Upload the file
20
56
 
21
- // Save file in the root directory (default behavior)
22
- uploader.uploadFile(filePath, (uploaded, total) => {
23
- console.log(`Progress: ${(uploaded / total * 100).toFixed(2)}%`);
24
- });
57
+ fetchFileList(); //Fetch files
@@ -0,0 +1,41 @@
1
+ const { generateSign, fetchHomeInfo, generateDownload } = require('./downloadHelper');
2
+
3
+ /**
4
+ * Generates a direct download link for a file from Terabox.
5
+ * @param {string} ndus - User authentication token.
6
+ * @param {string} fid - File ID of the file to be downloaded.
7
+ * @returns {Promise<{success: boolean, message: string, downloadLink?: string}>} - A promise that resolves to an object containing success status, message, and the direct download link if successful.
8
+ */
9
+ async function getDownloadLink(ndus, fid) {
10
+ try {
11
+ // Fetch home information to retrieve necessary parameters for signing
12
+ const homeInfo = await fetchHomeInfo(ndus);
13
+
14
+ if (!homeInfo || !homeInfo.data.sign3 || !homeInfo.data.sign1 || !homeInfo.data.timestamp) {
15
+ return { success: false, message: "Invalid home information received." };
16
+ }
17
+
18
+ const sign1 = homeInfo.data.sign3;
19
+ const sign2 = homeInfo.data.sign1;
20
+ const timestamp = homeInfo.data.timestamp;
21
+
22
+ // Generate the required sign using sign1 and sign2
23
+ const sign = generateSign(sign1, sign2);
24
+ if (!sign) {
25
+ return { success: false, message: "Failed to generate sign." };
26
+ }
27
+
28
+ // Fetch the download link
29
+ const responseDownload = await generateDownload(sign, fid, timestamp, ndus);
30
+ if (!responseDownload || !responseDownload.downloadLink[0]?.dlink) {
31
+ return { success: false, message: "Failed to retrieve download link." };
32
+ }
33
+
34
+ return { success: true, message: "Download link retrieved successfully.", downloadLink: responseDownload.downloadLink[0].dlink};
35
+ } catch (error) {
36
+ console.error("Error getting download link:", error);
37
+ return { success: false, message: error.message || "Unknown error occurred while fetching download link." };
38
+ }
39
+ }
40
+
41
+ module.exports = getDownloadLink;
@@ -0,0 +1,131 @@
1
+ const axios = require('axios');
2
+
3
+ /**
4
+ * Generates a cryptographic sign using RC4-like encryption.
5
+ * @param {string} s1 - First input string (key).
6
+ * @param {string} s2 - Second input string (data).
7
+ * @returns {string} - Base64 encoded signed string.
8
+ */
9
+ function generateSign(s1, s2) {
10
+ try {
11
+ if (!s1 || !s2) {
12
+ return { success: false, message: "Provide both the signs" };
13
+ }
14
+
15
+ const p = new Uint8Array(256);
16
+ const a = new Uint8Array(256);
17
+ const result = [];
18
+
19
+ for (let i = 0; i < 256; i++) {
20
+ a[i] = s1.charCodeAt(i % s1.length);
21
+ p[i] = i;
22
+ }
23
+
24
+ let j = 0;
25
+ for (let i = 0; i < 256; i++) {
26
+ j = (j + p[i] + a[i]) % 256;
27
+ [p[i], p[j]] = [p[j], p[i]];
28
+ }
29
+
30
+ let i = 0;
31
+ j = 0;
32
+ for (let q = 0; q < s2.length; q++) {
33
+ i = (i + 1) % 256;
34
+ j = (j + p[i]) % 256;
35
+ [p[i], p[j]] = [p[j], p[i]];
36
+ const k = p[(p[i] + p[j]) % 256];
37
+ result.push(s2.charCodeAt(q) ^ k);
38
+ }
39
+
40
+ return Buffer.from(result).toString('base64');
41
+ } catch (error) {
42
+ console.error("Error generating sign:", error.message);
43
+ return null;
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Fetches home information from Terabox API.
49
+ * @param {string} ndus - User authentication token.
50
+ * @returns {Promise<{success: boolean, message: string, data?: object}>} - The response data from the API.
51
+ */
52
+ async function fetchHomeInfo(ndus) {
53
+ const url = "https://www.1024terabox.com/api/home/info";
54
+
55
+ try {
56
+ if (!ndus) {
57
+ return { success: false, message: "User authentication token (ndus) is required" };
58
+ }
59
+
60
+ const response = await axios.get(url, {
61
+ params: {
62
+ app_id: "250528",
63
+ web: "1",
64
+ channel: "dubox",
65
+ clienttype: "0",
66
+ },
67
+ headers: {
68
+ "User-Agent": "Mozilla/5.0",
69
+ "Accept": "application/json",
70
+ "Cookie": `ndus=${ndus}`,
71
+ },
72
+ });
73
+ return { success: true, message: "Home info retrieved successfully.", data: response.data.data };
74
+ } catch (error) {
75
+ console.error("Error fetching home info:", error.response?.data || error.message);
76
+ return { success: false, message: error.message || "Failed to fetch home info." };
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Generates a download link for a file from Terabox.
82
+ * @param {string} sign - Encrypted sign generated using `generateSign`.
83
+ * @param {string} fid - File ID of the file to be downloaded.
84
+ * @param {number} timestamp - Timestamp of the request.
85
+ * @param {string} ndus - User authentication token.
86
+ * @returns {Promise<{success: boolean, message: string, downloadLink?: string}>}
87
+ */
88
+ async function generateDownload(sign, fid, timestamp, ndus) {
89
+ const url = "https://www.1024terabox.com/api/download";
90
+
91
+ try {
92
+ if (!sign || !fid || !timestamp || !ndus) {
93
+ return { success: false, message: "Missing required parameters for generating download link." };
94
+ }
95
+
96
+ const response = await axios.get(url, {
97
+ params: {
98
+ app_id: "250528",
99
+ web: "1",
100
+ channel: "dubox",
101
+ clienttype: "0",
102
+ fidlist: `[${fid}]`,
103
+ type: "dlink",
104
+ vip: "2",
105
+ sign,
106
+ timestamp,
107
+ need_speed: "0",
108
+ },
109
+ headers: {
110
+ "User-Agent": "Mozilla/5.0",
111
+ "Accept": "application/json",
112
+ "Cookie": `ndus=${ndus}`,
113
+ },
114
+ });
115
+
116
+ if (!response.data.dlink) {
117
+ return { success: false, message: "No download link received." };
118
+ }
119
+
120
+ return { success: true, message: "Download link generated successfully.", downloadLink: response.data.dlink };
121
+ } catch (error) {
122
+ console.error("Error generating download link:", error.response?.data || error.message);
123
+ return { success: false, message: error.message || "Failed to generate download link." };
124
+ }
125
+ }
126
+
127
+ module.exports = {
128
+ generateSign,
129
+ fetchHomeInfo,
130
+ generateDownload,
131
+ };
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Fetches file details from Terabox using a short URL.
3
+ * @param {string} shortUrl - The short URL of the file.
4
+ * @returns {Promise<object|null>} - A promise that resolves to an object containing file details, or null if retrieval fails.
5
+ */
6
+ async function getFileDetails(shortUrl) {
7
+ // API Endpoint
8
+ const apiUrl = `https://www.terabox.com/api/shorturlinfo?app_id=250528&shorturl=${shortUrl}&root=1`;
9
+
10
+ // Request Headers
11
+ const headers = {
12
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
13
+ "Referer": "https://www.terabox.com/",
14
+ "Accept": "application/json, text/javascript, */*; q=0.01",
15
+ "X-Requested-With": "XMLHttpRequest"
16
+ };
17
+
18
+ try {
19
+ // Send GET request to fetch file details
20
+ const response = await fetch(apiUrl, { method: "GET", headers: headers });
21
+ const data = await response.json();
22
+
23
+ // Validate response
24
+ if (!data || !data.sign) {
25
+ console.error("Failed to retrieve file details. Response:", data);
26
+ return null;
27
+ }
28
+
29
+ // Extract relevant file details
30
+ const fileDetails = {
31
+ status: "success",
32
+ sign: data.sign,
33
+ timestamp: data.timestamp,
34
+ shareid: data.shareid,
35
+ uk: data.uk,
36
+ list: data.list || []
37
+ };
38
+
39
+ return fileDetails;
40
+
41
+ } catch (error) {
42
+ console.error("Error fetching file details:", error);
43
+ return null;
44
+ }
45
+ }
46
+
47
+ module.exports = getFileDetails;
@@ -0,0 +1,52 @@
1
+ const axios = require('axios');
2
+
3
+ /**
4
+ * Generates a short URL for a file in Terabox.
5
+ * @param {string} ndus - User authentication token.
6
+ * @param {string} path - The file path in Terabox.
7
+ * @param {string} fid - The file ID.
8
+ * @returns {Promise<object|null>} - A promise that resolves to the API response containing the short URL or null if an error occurs.
9
+ */
10
+ const getShortUrl = async (ndus, path, fid) => {
11
+ try {
12
+ // API Endpoint
13
+ const url = 'https://www.1024terabox.com/share/pset';
14
+ const cookies = `ndus=${ndus}`;
15
+
16
+ // Form Data Parameters
17
+ const formData = new URLSearchParams({
18
+ app_id: '250528',
19
+ web: '1',
20
+ channel: 'dubox',
21
+ clienttype: '0',
22
+ app: 'universe',
23
+ schannel: '0',
24
+ channel_list: '[0]',
25
+ period: '0',
26
+ path_list: `["${path}"]`,
27
+ fid_list: `[${fid}]`,
28
+ pwd: '',
29
+ public: '1',
30
+ scene: ''
31
+ });
32
+
33
+ // Request Headers
34
+ const headers = {
35
+ 'Content-Type': 'application/x-www-form-urlencoded',
36
+ 'Cookie': cookies,
37
+ 'Referer': 'https://www.1024terabox.com/',
38
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
39
+ };
40
+
41
+ // Send POST request to generate a short URL
42
+ const response = await axios.post(url, formData.toString(), { headers });
43
+
44
+ // Return the API response containing the short URL
45
+ return response.data;
46
+ } catch (error) {
47
+ console.error('Error generating short link:', error);
48
+ return null;
49
+ }
50
+ };
51
+
52
+ module.exports = getShortUrl;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Builds the URL for uploading a file chunk.
3
+ * @param {string} fileName - The name of the file being uploaded
4
+ * @param {string} uploadId - The unique ID for the upload session (optional)
5
+ * @param {string} appId - The application ID (required)
6
+ * @returns {string} - The upload URL
7
+ */
8
+ function buildUploadUrl(fileName, uploadId, appId) {
9
+ return `https://c-jp.1024terabox.com/rest/2.0/pcs/superfile2?method=upload&app_id=${appId}&channel=dubox&clienttype=0&web=1&path=%2F${encodeURIComponent(fileName)}&uploadid=${uploadId}&uploadsign=0&partseq=0`;
10
+ }
11
+
12
+ /**
13
+ * Builds the URL for the final create call.
14
+ * @returns {string} - The create URL
15
+ */
16
+ function buildCreateUrl() {
17
+ return 'https://www.1024terabox.com/api/create';
18
+ }
19
+
20
+ /**
21
+ * Builds the URL for fetching the file list.
22
+ * @param {string} appId - The application ID
23
+ * @param {string} directory - The directory path to fetch the file list from
24
+ * @returns {string} - The file list URL
25
+ */
26
+ function buildListUrl(appId, directory) {
27
+ return `https://www.1024terabox.com/api/list?app_id=${appId}&web=1&channel=dubox&clienttype=0&order=time&desc=1&dir=${encodeURIComponent(directory)}&num=100&page=1&showempty=0`;
28
+ }
29
+
30
+
31
+ /**
32
+ * Builds the downloadable link for videos.
33
+ * @param {string} appId - The application ID
34
+ * @param {string} videoPath - The directory path to fetch the file list from
35
+ * @returns {string} - The file list URL
36
+ */
37
+ function buildVideoDownloadUrl(appId, videoPath) {
38
+ return `https://www.1024terabox.com/api/streaming?path=${encodeURIComponent(videoPath)}&app_id=${appId}&clienttype=0&type=M3U8_FLV_264_480&vip=1`;
39
+ }
40
+
41
+ module.exports = { buildUploadUrl, buildCreateUrl, buildListUrl, buildVideoDownloadUrl };
package/lib/index.js CHANGED
@@ -2,10 +2,11 @@ const axios = require('axios');
2
2
  const path = require('path');
3
3
  const fs = require('fs');
4
4
  const FormData = require('form-data');
5
- const { buildUploadUrl, buildCreateUrl } = require('./utils');
5
+ const { buildUploadUrl, buildCreateUrl, buildListUrl} = require('./helpers/utils');
6
+ const getDownloadLink = require('./helpers/download/download')
6
7
 
7
8
  /**
8
- * Class to handle Terabox file upload
9
+ * Class to handle Terabox file operations
9
10
  */
10
11
  class TeraboxUploader {
11
12
  constructor(credentials) {
@@ -26,6 +27,10 @@ class TeraboxUploader {
26
27
  * @param {string} filePath - Path to the file to be uploaded
27
28
  * @param {function} progressCallback - Optional callback to track upload progress
28
29
  * @param {string} [directory='/'] - Optional directory where the file will be saved on Terabox
30
+ * @returns {Promise<{success: boolean, message: string, fileDetails?: object}>} - A promise that resolves to an object indicating the result of the upload:
31
+ * - `success` (boolean): `true` if the upload was successful, `false` otherwise.
32
+ * - `message` (string): A message with the upload status (success or error).
33
+ * - `fileDetails` (optional object): The details of the file uploaded, returned only if the upload was successful.
29
34
  */
30
35
  async uploadFile(filePath, progressCallback, directory = '/') {
31
36
  try {
@@ -53,8 +58,6 @@ class TeraboxUploader {
53
58
  },
54
59
  });
55
60
 
56
- console.log('File chunk upload response:', postResponse.data);
57
-
58
61
  // Finalize the upload (Create call)
59
62
  const createUrl = buildCreateUrl();
60
63
  const createResponse = await axios.post(createUrl, new URLSearchParams({
@@ -71,9 +74,51 @@ class TeraboxUploader {
71
74
  },
72
75
  });
73
76
 
74
- console.log('Create response:', createResponse.data);
77
+ // Return success message
78
+ return {
79
+ success: true,
80
+ message: 'File uploaded successfully.',
81
+ fileDetails: createResponse.data,
82
+ };
83
+ } catch (error) {
84
+ console.error('Error during upload process:', error.response?.data || error.message || error);
85
+
86
+ // Return failure message
87
+ return {
88
+ success: false,
89
+ message: error.response?.data || error.message,
90
+ };
91
+ }
92
+ }
93
+
94
+
95
+ /**
96
+ * Fetches the file list from Terabox
97
+ * @param {string} directory - Directory to fetch the file list from (e.g., "/")
98
+ * @returns {Promise<object>} - JSON response with file details along with download link
99
+ */
100
+ async fetchFileList(directory = '/') {
101
+ try {
102
+ const listUrl = buildListUrl(this.credentials.appId, directory);
103
+
104
+ const response = await axios.get(listUrl, {
105
+ headers: {
106
+ Cookie: this.credentials.cookies,
107
+ },
108
+ });
109
+ const finalDataArray = response.data.list;
110
+ for (const file of finalDataArray) {
111
+ const fid = file.fs_id;
112
+ file.downloadLink = await getDownloadLink(this.credentials.ndus, fid);
113
+ }
114
+
115
+ return { success: true, message: 'File list retrieved successfully.', data: finalDataArray };
75
116
  } catch (error) {
76
- console.error('Error during upload process:', error.response?.data || error.message);
117
+ console.error('Error fetching file list:', error);
118
+ return {
119
+ success: false,
120
+ message: error.response?.data?.error || error.message || 'Failed to fetch file list.',
121
+ };
77
122
  }
78
123
  }
79
124
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "terabox-upload-tool",
3
- "version": "1.0.0",
4
- "description": "A Node.js library to upload files to Terabox",
3
+ "version": "1.2.0",
4
+ "description": "git add",
5
5
  "main": "lib/index.js",
6
6
  "scripts": {
7
7
  "test": "echo \"Error: no test specified\" && exit 1"
package/lib/utils.js DELETED
@@ -1,20 +0,0 @@
1
- /**
2
- * Builds the URL for uploading a file chunk.
3
- * @param {string} fileName - The name of the file being uploaded
4
- * @param {string} uploadId - The unique ID for the upload session (optional)
5
- * @param {string} appId - The application ID (required)
6
- * @returns {string} - The upload URL
7
- */
8
- function buildUploadUrl(fileName, uploadId, appId) {
9
- return `https://c-jp.1024terabox.com/rest/2.0/pcs/superfile2?method=upload&app_id=${appId}&channel=dubox&clienttype=0&web=1&path=%2F${encodeURIComponent(fileName)}&uploadid=${uploadId}&uploadsign=0&partseq=0`;
10
- }
11
-
12
- /**
13
- * Builds the URL for the final create call.
14
- * @returns {string} - The create URL
15
- */
16
- function buildCreateUrl() {
17
- return 'https://www.1024terabox.com/api/create';
18
- }
19
-
20
- module.exports = { buildUploadUrl, buildCreateUrl };