diff --git a/README.md b/README.md index 34dfbd608..e40f99e0c 100644 --- a/README.md +++ b/README.md @@ -59,4 +59,3 @@ We using the monorepo structure with [yarn workspaces](https://classic.yarnpkg.c [![img](https://user-images.githubusercontent.com/34012548/172031316-60d858c7-8401-42f3-9c73-0b75e80c8292.png)](https://discord.gg/PKNVJwAZnR) [![img](https://media.discordapp.net/attachments/978783095463501834/984317776544014416/ytbutton.png)](https://youtube.com/channel/UCg9WsNAHdOpo8SyM8JHGuZQ) - diff --git a/api/package.json b/api/package.json index b126b6809..73421392b 100644 --- a/api/package.json +++ b/api/package.json @@ -48,7 +48,7 @@ "serialize-error": "^8.1.0", "serverless-http": "^3.0.1", "source-map-support": "^0.5.19", - "teledrive-client": "^2.8.2", + "telegram": "^2.15.5", "uuid-random": "^1.3.2" }, "devDependencies": { diff --git a/api/src/Types.ts b/api/src/Types.ts index d586628bd..caaf11672 100644 --- a/api/src/Types.ts +++ b/api/src/Types.ts @@ -1,5 +1,5 @@ import { users } from '@prisma/client' -import { TelegramClient } from 'teledrive-client' +import { TelegramClient } from 'telegram' declare module 'http' { interface IncomingMessage { diff --git a/api/src/api/middlewares/Auth.ts b/api/src/api/middlewares/Auth.ts index a5a0a9c92..aaecbf285 100644 --- a/api/src/api/middlewares/Auth.ts +++ b/api/src/api/middlewares/Auth.ts @@ -1,8 +1,8 @@ import { NextFunction, Request, Response } from 'express' import { verify } from 'jsonwebtoken' -import { Logger, TelegramClient } from 'teledrive-client' -import { LogLevel } from 'teledrive-client/extensions/Logger' -import { StringSession } from 'teledrive-client/sessions' +import { Logger, TelegramClient } from 'telegram' +import { LogLevel } from 'telegram/extensions/Logger' +import { StringSession } from 'telegram/sessions' import { prisma } from '../../model' import { Redis } from '../../service/Cache' import { API_JWT_SECRET, CONNECTION_RETRIES, TG_CREDS } from '../../utils/Constant' diff --git a/api/src/api/middlewares/TGClient.ts b/api/src/api/middlewares/TGClient.ts index b97cbba0c..58806002c 100644 --- a/api/src/api/middlewares/TGClient.ts +++ b/api/src/api/middlewares/TGClient.ts @@ -1,6 +1,6 @@ -import { Logger, TelegramClient } from 'teledrive-client' -import { LogLevel } from 'teledrive-client/extensions/Logger' -import { StringSession } from 'teledrive-client/sessions' +import { Logger, TelegramClient } from 'telegram' +import { LogLevel } from 'telegram/extensions/Logger' +import { StringSession } from 'telegram/sessions' import { NextFunction, Request, Response } from 'express' import { CONNECTION_RETRIES, TG_CREDS } from '../../utils/Constant' diff --git a/api/src/api/middlewares/TGSessionAuth.ts b/api/src/api/middlewares/TGSessionAuth.ts index 678542666..672d03a3d 100644 --- a/api/src/api/middlewares/TGSessionAuth.ts +++ b/api/src/api/middlewares/TGSessionAuth.ts @@ -1,8 +1,8 @@ import { NextFunction, Request, Response } from 'express' import { verify } from 'jsonwebtoken' -import { Logger, TelegramClient } from 'teledrive-client' -import { LogLevel } from 'teledrive-client/extensions/Logger' -import { StringSession } from 'teledrive-client/sessions' +import { Logger, TelegramClient } from 'telegram' +import { LogLevel } from 'telegram/extensions/Logger' +import { StringSession } from 'telegram/sessions' import { API_JWT_SECRET, CONNECTION_RETRIES, TG_CREDS } from '../../utils/Constant' export async function TGSessionAuth(req: Request, _: Response, next: NextFunction): Promise { diff --git a/api/src/api/v1/Auth.ts b/api/src/api/v1/Auth.ts index 031cb9b82..68b3aa4d3 100644 --- a/api/src/api/v1/Auth.ts +++ b/api/src/api/v1/Auth.ts @@ -2,11 +2,11 @@ import { AES } from 'crypto-js' import { Request, Response } from 'express' import { sign, verify } from 'jsonwebtoken' import { serializeError } from 'serialize-error' -import { Api, Logger, TelegramClient } from 'teledrive-client' -import { LogLevel } from 'teledrive-client/extensions/Logger' -import { generateRandomBytes } from 'teledrive-client/Helpers' -import { computeCheck } from 'teledrive-client/Password' -import { StringSession } from 'teledrive-client/sessions' +import { Api, Logger, TelegramClient } from 'telegram' +import { LogLevel } from 'telegram/extensions/Logger' +import { generateRandomBytes } from 'telegram/Helpers' +import { computeCheck } from 'telegram/Password' +import { StringSession } from 'telegram/sessions' import { prisma } from '../../model' import { Redis } from '../../service/Cache' import { API_JWT_SECRET, CONNECTION_RETRIES, COOKIE_AGE, FILES_JWT_SECRET, TG_CREDS } from '../../utils/Constant' diff --git a/api/src/api/v1/Dialogs.ts b/api/src/api/v1/Dialogs.ts index a47f5f4c7..0dee99c03 100644 --- a/api/src/api/v1/Dialogs.ts +++ b/api/src/api/v1/Dialogs.ts @@ -1,4 +1,4 @@ -import { Api } from 'teledrive-client' +import { Api } from 'telegram' import bigInt from 'big-integer' import { Request, Response } from 'express' import { Redis } from '../../service/Cache' diff --git a/api/src/api/v1/Files.ts b/api/src/api/v1/Files.ts index bb6aa2b1b..32a9b5b85 100644 --- a/api/src/api/v1/Files.ts +++ b/api/src/api/v1/Files.ts @@ -8,9 +8,9 @@ import { Request, Response } from 'express' import { appendFileSync, createReadStream, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'fs' import moment from 'moment' import multer from 'multer' -import { Api, Logger, TelegramClient } from 'teledrive-client' -import { LogLevel } from 'teledrive-client/extensions/Logger' -import { StringSession } from 'teledrive-client/sessions' +import { Api, Logger, TelegramClient } from 'telegram' +import { LogLevel } from 'telegram/extensions/Logger' +import { StringSession } from 'telegram/sessions' import { prisma } from '../../model' import { Redis } from '../../service/Cache' import { CACHE_FILES_LIMIT, CONNECTION_RETRIES, FILES_JWT_SECRET, TG_CREDS } from '../../utils/Constant' @@ -115,6 +115,11 @@ export class Files { .split(',') } } } + if (/\.like$/.test(k)) { + obj = { [k.replace(/\.like$/, '')]: { + startsWith: filters[k].toString() + } } + } return [...res, obj] }, []), ...excludeParts === 'true' || excludeParts === '1' ? [ @@ -153,7 +158,7 @@ export class Files { take: Number(limit) || 10, orderBy: buildSort(sort as string) }), - await prisma.files.count({ where }) + await prisma.files.count({ where: whereQuery }) ] } @@ -263,13 +268,14 @@ export class Files { @Endpoint.POST({ middlewares: [Auth] }) public async addFolder(req: Request, res: Response): Promise { const { file: data } = req.body - const count = data?.name ? null : await prisma.files.count({ + const count = await prisma.files.count({ where: { AND: [ { type: 'folder' }, { user_id: req.user.id }, - { name: { startsWith: 'New Folder' } }, - { parent_id: data?.parent_id || null } + { name: { startsWith: data?.name || 'New Folder' } }, + { parent_id: data?.parent_id || null }, + { link_id: data?.link_id || null } ] } }) @@ -279,11 +285,12 @@ export class Files { return res.send({ file: await prisma.files.create({ data: { - name: data?.name || `New Folder${count ? ` (${count})` : ''}`, + name: (data?.name || 'New Folder') + `${count ? ` (${count})` : ''}`, mime_type: 'teledrive/folder', user_id: req.user.id, type: 'folder', uploaded_at: new Date(), + link_id: data?.link_id, ...parent ? { parent_id: parent.id, sharing_options: parent.sharing_options, @@ -293,6 +300,95 @@ export class Files { }) }) } + @Endpoint.POST({ middlewares: [Auth] }) + public async cloneFile(req: Request, res: Response): Promise { + const { file: body } = req.body + const source = await prisma.files.findUnique({ where: { id: body.key } }) + const files = await prisma.files.findMany({ + where: { + AND: [ + { + name: { + startsWith: body.name.replace(/\.part0*\d+$/, '') + } + }, + { + user_id: req.user?.id + }, + { + parent_id: source.parent_id + }, + ] + } + }) + + delete body.key + let countFiles = 0 + for (const file of files) { + const { forward_info: forwardInfo, message_id: messageId, mime_type: mimeType } = file + let peerFrom: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat + let peerTo: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat + const [type, peerId, _id, accessHash] = forwardInfo?.split('/') ?? [] + if (forwardInfo && forwardInfo.match(/^channel\//gi)) { + if (type === 'channel') { + peerFrom = new Api.InputPeerChannel({ + channelId: bigInt(peerId), + accessHash: accessHash ? bigInt(accessHash as string) : null }) + } else if (type === 'user') { + peerFrom = new Api.InputPeerUser({ + userId: bigInt(peerId), + accessHash: bigInt(accessHash as string) }) + } else if (type === 'chat') { + peerFrom = new Api.InputPeerChat({ + chatId: bigInt(peerId) }) + } + } + if ((req.user.settings as Prisma.JsonObject)?.saved_location) { + const [type, peerId, _, accessHash] = ((req.user.settings as Prisma.JsonObject).saved_location as string).split('/') + if (type === 'channel') { + peerTo = new Api.InputPeerChannel({ + channelId: bigInt(peerId), + accessHash: accessHash ? bigInt(accessHash as string) : null }) + } else if (type === 'user') { + peerTo = new Api.InputPeerUser({ + userId: bigInt(peerId), + accessHash: bigInt(accessHash as string) }) + } else if (type === 'chat') { + peerTo = new Api.InputPeerChat({ + chatId: bigInt(peerId) }) + } + } + + const chat = await req.tg.invoke(new Api.messages.ForwardMessages({ + fromPeer: peerFrom || 'me', + id: [Number(messageId)], + toPeer: peerTo || 'me', + randomId: [bigInt.randBetween('-1e100', '1e100')], + silent: true, + dropAuthor: true + })) as any + + const newForwardInfo = forwardInfo ? `${type}/${peerId}/${chat.updates[0].id.toString()}/${accessHash}` : null + const message = { + size: Number(file.size), + message_id: chat.updates[0].id.toString(), + mime_type: mimeType, + forward_info: newForwardInfo, + uploaded_at: new Date(chat.date * 1000) + } + + const response = await prisma.files.create({ + data: { + ...body, + name: files.length == 1 ? body.name : body.name.replace(/\.part0*\d+$/, '')+`.part${String(countFiles + 1).padStart(3, '0')}`, + ...message + } + }) + if (countFiles++ == 0) + res.send({ file: response }) + } + } + @Endpoint.GET('/:id', { middlewares: [AuthMaybe] }) public async retrieve(req: Request, res: Response): Promise { const { id } = req.params @@ -982,7 +1078,7 @@ export class Files { name, message_id: file.id.toString(), mime_type: mimeType, - size, + size: size.value, user_id: req.user.id, uploaded_at: new Date(file.date * 1000), type, @@ -1147,6 +1243,7 @@ export class Files { // ignore } + let countFiles = 1 for (const file of files) { let chat: any if (file.forward_info && file.forward_info.match(/^channel\//gi)) { @@ -1176,7 +1273,7 @@ export class Files { if (cancel) { throw { status: 422, body: { error: 'canceled' } } } else { - console.log(`${chat['messages'][0].id} ${downloaded}/${chat['messages'][0].media.document.size} (${downloaded/Number(chat['messages'][0].media.document.size)})`) + console.log(`${chat['messages'][0].id} ${downloaded}/${chat['messages'][0].media.document.size.value} (${downloaded/Number(totalFileSize)*100+'%'})`) try { appendFileSync(filename('process-'), buffer) } catch (error) { @@ -1186,18 +1283,20 @@ export class Files { } }, close: () => { - console.log(`${chat['messages'][0].id} ${downloaded}/${chat['messages'][0].media.document.size} (${downloaded/Number(chat['messages'][0].media.document.size)})`, '-end-') - try { - const { size } = statSync(filename('process-')) - if (totalFileSize.gt(bigInt(size))) { - rmSync(filename('process-')) - } else { - renameSync(filename('process-'), filename()) + console.log(`${chat['messages'][0].id} ${downloaded}/${chat['messages'][0].media.document.size.value} (${downloaded/Number(totalFileSize)*100+'%'})`, '-end-') + if (countFiles++ >= files.length) { + try { + const { size } = statSync(filename('process-')) + if (totalFileSize.gt(bigInt(size))) { + rmSync(filename('process-')) + } else { + renameSync(filename('process-'), filename()) + } + } catch (error) { + // ignore } - } catch (error) { - // ignore + res.end() } - res.end() } } }) diff --git a/api/src/api/v1/Messages.ts b/api/src/api/v1/Messages.ts index 426d2763e..a82dc9033 100644 --- a/api/src/api/v1/Messages.ts +++ b/api/src/api/v1/Messages.ts @@ -1,4 +1,4 @@ -import { Api } from 'teledrive-client' +import { Api } from 'telegram' import bigInt from 'big-integer' import { Request, Response } from 'express' import { Redis } from '../../service/Cache' diff --git a/api/src/api/v1/Users.ts b/api/src/api/v1/Users.ts index 87591ccb2..40c7002fc 100644 --- a/api/src/api/v1/Users.ts +++ b/api/src/api/v1/Users.ts @@ -2,7 +2,7 @@ import { Prisma } from '@prisma/client' import axios from 'axios' import { Request, Response } from 'express' import moment from 'moment' -import { Api } from 'teledrive-client' +import { Api } from 'telegram' import { prisma } from '../../model' import { Redis } from '../../service/Cache' import { buildSort } from '../../utils/FilterQuery' diff --git a/install.docker.sh b/install.docker.sh index 52a1b887d..4f54b48a3 100755 --- a/install.docker.sh +++ b/install.docker.sh @@ -2,9 +2,10 @@ set -e -echo "Node Version: $(git --version)" -echo "cURL Version: $(docker -v)" -echo "cURL Version: $(docker-compose -v)" +echo "Node Version: $(node -v)" +echo "cURL Version: $(curl --version | head -n 1)" +echo "Docker Version: $(docker -v)" +echo "Docker Compose Version: $(docker-compose -v)" if [ ! -f docker/.env ] then @@ -31,9 +32,10 @@ then echo "DB_PASSWORD=$DB_PASSWORD" >> docker/.env cd docker + docker-compose build teledrive docker-compose up -d sleep 2 - docker-compose up -d + docker-compose exec teledrive yarn workspace api prisma migrate deploy else git reset --hard git clean -f @@ -46,6 +48,6 @@ else docker-compose up --build --force-recreate -d sleep 2 docker-compose up -d - + docker-compose exec teledrive yarn workspace api prisma migrate deploy docker image prune -f fi diff --git a/web/package.json b/web/package.json index dd975204f..bf6228280 100644 --- a/web/package.json +++ b/web/package.json @@ -44,7 +44,7 @@ "streamsaver": "^2.0.5", "sw-precache-cra": "^1.0.0", "swr": "^1.0.0", - "teledrive-client": "^2.8.2", + "telegram": "^2.15.5", "through2": "^4.0.2", "typescript": "^4.0.3", "use-debounce": "^7.0.1", diff --git a/web/src/pages/Login.tsx b/web/src/pages/Login.tsx index 010988a8b..961ca8e84 100644 --- a/web/src/pages/Login.tsx +++ b/web/src/pages/Login.tsx @@ -10,9 +10,9 @@ import OtpInput from 'react-otp-input' import QRCode from 'react-qr-code' import { useHistory } from 'react-router' import useSWRImmutable from 'swr/immutable' -import { Api } from 'teledrive-client' -import { generateRandomBytes } from 'teledrive-client/Helpers' -import { computeCheck } from 'teledrive-client/Password' +import { Api } from 'telegram' +import { generateRandomBytes } from 'telegram/Helpers' +import { computeCheck } from 'telegram/Password' import en from 'world_countries_lists/data/countries/en/world.json' import { fetcher, req } from '../utils/Fetcher' import { anonymousTelegramClient, telegramClient } from '../utils/Telegram' diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsx index c7bafe716..4213e0003 100644 --- a/web/src/pages/Settings.tsx +++ b/web/src/pages/Settings.tsx @@ -50,7 +50,7 @@ import React, { useEffect, useState } from 'react' import { useThemeSwitcher } from 'react-css-theme-switcher' import { useHistory } from 'react-router-dom' import useSWR from 'swr' -import { Api } from 'teledrive-client' +import { Api } from 'telegram' import * as serviceWorkerRegistration from '../serviceWorkerRegistration' import { VERSION } from '../utils/Constant' import { apiUrl, fetcher, req } from '../utils/Fetcher' diff --git a/web/src/pages/dashboard/components/TableFiles.tsx b/web/src/pages/dashboard/components/TableFiles.tsx index e5e521a59..b0a40b210 100644 --- a/web/src/pages/dashboard/components/TableFiles.tsx +++ b/web/src/pages/dashboard/components/TableFiles.tsx @@ -68,7 +68,7 @@ const TableFiles: React.FC = ({ const [popup, setPopup] = useState<{ visible: boolean, x?: number, y?: number, row?: any }>() const [showDetails, setShowDetails] = useState() const { data: user } = useSWR(showDetails ? `/users/${showDetails.user_id}` : null, fetcher) - const { data: filesParts } = useSWR(showDetails ? `/files?name.match=${encodeURIComponent('\.part0*[0-9]+$')}&name.like=${showDetails.name.replace(/\.part0*\d+$/, '')}%&user_id=${showDetails.user_id}&parent_id${showDetails.parent_id ? `=${showDetails.parent_id}` : '.is=null'}${tab === 'shared' ? '&shared=1' : ''}` : null, fetcher) + const { data: filesParts } = useSWR(showDetails ? `/files?name.like=${showDetails.name.replace(/\.part0*\d+$/, '')}&user_id=${showDetails.user_id}&parent_id${showDetails.parent_id ? `=${showDetails.parent_id}` : '=null'}${tab === 'shared' ? '&shared=1' : ''}` : null, fetcher) const pasteEnabled = useRef(null) useEffect(() => { diff --git a/web/src/pages/dashboard/components/Upload.tsx b/web/src/pages/dashboard/components/Upload.tsx index 81b7bcc8e..d7b93aa01 100644 --- a/web/src/pages/dashboard/components/Upload.tsx +++ b/web/src/pages/dashboard/components/Upload.tsx @@ -2,7 +2,7 @@ import { CloudUploadOutlined } from '@ant-design/icons' import { notification, Typography, Upload as BaseUpload } from 'antd' import mime from 'mime-types' import React, { useEffect, useRef } from 'react' -import { Api } from 'teledrive-client' +import { Api } from 'telegram' import { CHUNK_SIZE, MAX_UPLOAD_SIZE, RETRY_COUNT } from '../../../utils/Constant' import { req } from '../../../utils/Fetcher' import { telegramClient } from '../../../utils/Telegram' diff --git a/web/src/pages/dashboard/index.tsx b/web/src/pages/dashboard/index.tsx index 7b3d73c47..9adb5167b 100644 --- a/web/src/pages/dashboard/index.tsx +++ b/web/src/pages/dashboard/index.tsx @@ -270,10 +270,10 @@ const Dashboard: React.FC = ({ match }) await Promise.all(rows?.map(async row => { if (row.type === 'folder') { const name = `Link of ${row.name}` - await req.post('/files', { file: { ...row, name, link_id: row.id, parent_id: p?.link_id || p?.id, id: undefined } }) + await req.post('/files/addFolder', { file: { ...row, name, link_id: row.id, parent_id: p?.link_id || p?.id, id: undefined } }) } else { const name = data?.find(datum => datum.name === row.name) ? `Copy of ${row.name}` : row.name - await req.post('/files', { file: { ...row, name, parent_id: p?.link_id || p?.id, id: undefined } }) + await req.post('/files/cloneFile', { file: { ...row, name, parent_id: p?.link_id || p?.id, id: undefined } }) } })) } else if ((act || action) === 'cut') { diff --git a/web/src/pages/view/components/TableFiles.tsx b/web/src/pages/view/components/TableFiles.tsx index d19863be5..e0d03ae74 100644 --- a/web/src/pages/view/components/TableFiles.tsx +++ b/web/src/pages/view/components/TableFiles.tsx @@ -40,7 +40,7 @@ const TableFiles: React.FC = ({ me, data }) => { const [params, setParams] = useState() const [loading, setLoading] = useState(false) const [showDetails, setShowDetails] = useState() - const { data: filesParts } = useSWR(showDetails ? `/files?name.match=${encodeURIComponent('\.part0*[0-9]+$')}&name.like=${showDetails.name.replace(/\.part0*\d+$/, '')}%&user_id=${showDetails.user_id}${me?.user.id !== showDetails.user_id ? '&shared=1' : ''}&parent_id${showDetails.parent_id ? `=${showDetails.parent_id}` : '.is=null'}` : null, fetcher) + const { data: filesParts } = useSWR(showDetails ? `/files?name.like=${showDetails.name.replace(/\.part0*\d+$/, '')}&user_id=${showDetails.user_id}${me?.user.id !== showDetails.user_id ? '&shared=1' : ''}&parent_id${showDetails.parent_id ? `=${showDetails.parent_id}` : '=null'}` : null, fetcher) const [popup, setPopup] = useState<{ visible: boolean, x?: number, y?: number, row?: any }>() const { data: files, mutate: _refetch } = useSWR(data?.file.type === 'folder' && data?.file.sharing_options?.includes('*') && params ? `/files?exclude_parts=1&${QueryString.stringify(params)}` : null, fetcher, { onSuccess: files => { setLoading(false) diff --git a/web/src/pages/view/components/Viewer.tsx b/web/src/pages/view/components/Viewer.tsx index 5180e17ee..1056dfbde 100644 --- a/web/src/pages/view/components/Viewer.tsx +++ b/web/src/pages/view/components/Viewer.tsx @@ -48,7 +48,7 @@ const Viewer: React.FC = ({ data, me, error, mutate, pageParams, isInDraw const history = useHistory() const [collapsed, setCollapsed] = useState() const { data: user } = useSWRImmutable(data?.file ? `/users/${data.file.user_id}` : null, fetcher) - const { data: datafilesParts } = useSWR(data?.file.name && /\.part0*\d+$/.test(data.file.name) ? `/files?name.match=${encodeURIComponent('\.part0*[0-9]+$')}&name.like=${data.file.name.replace(/\.part0*\d+$/, '')}%&user_id=${data.file.user_id}${me?.user.id !== data.file.user_id ? '&shared=1' : ''}&parent_id${data.file.parent_id ? `=${data.file.parent_id}` : '.is=null'}` : null, fetcher) + const { data: datafilesParts } = useSWR(data?.file.name && /\.part0*\d+$/.test(data.file.name) ? `/files?name.like=${data.file.name.replace(/\.part0*\d+$/, '')}&user_id=${data.file.user_id}${me?.user.id !== data.file.user_id ? '&shared=1' : ''}&parent_id${data.file.parent_id ? `=${data.file.parent_id}` : '=null'}` : null, fetcher) const [links, setLinks] = useState<{ raw: string, download: string, share: string }>() const [showContent] = useDebounce(collapsed, 250) const [contentStyle, setContentStyle] = useState<{ display: string } | undefined>() diff --git a/web/src/utils/Download.ts b/web/src/utils/Download.ts index 773625b6c..a4c5107dd 100644 --- a/web/src/utils/Download.ts +++ b/web/src/utils/Download.ts @@ -1,5 +1,5 @@ import streamSaver from 'streamsaver' -import { Api } from 'teledrive-client' +import { Api } from 'telegram' import { req } from './Fetcher' import { telegramClient } from './Telegram' @@ -13,8 +13,13 @@ export async function download(id: string): Promise { const readableStream = new ReadableStream({ - start(controller: ReadableStreamDefaultController) { + start(_controller: ReadableStreamDefaultController) { + }, + async pull(controller: ReadableStreamDefaultController) { + let countFiles = 1 + + start(controller: ReadableStreamDefaultController) { console.log('start downloading:', response.files) response.files.forEach(async file => { @@ -55,6 +60,29 @@ export async function download(id: string): Promise { } + + const getData = async () => await client.downloadMedia(chat['messages'][0].media, { + outputFile: { + write: (chunk: Buffer) => { + if (cancel) return false + return controller.enqueue(chunk) + }, + close: () => { + if (countFiles++ >= Number(response.files.length)) + controller.close() + } + }, + progressCallback: (received, total) => { + console.log('progress: ', (Number(received)/Number(total)*100).toFixed(2), '%') + } + }) + try { + await getData() + } catch (error) { + console.log(error) + } + } + const getData = async () => { try { diff --git a/web/src/utils/Telegram.ts b/web/src/utils/Telegram.ts index f6a35d1ba..f4b8eee7c 100644 --- a/web/src/utils/Telegram.ts +++ b/web/src/utils/Telegram.ts @@ -1,5 +1,5 @@ -import { TelegramClient } from 'teledrive-client' -import { StringSession } from 'teledrive-client/sessions' +import { TelegramClient } from 'telegram' +import { StringSession } from 'telegram/sessions' import { notification } from 'antd' export const telegramClient = { diff --git a/yarn.lock b/yarn.lock index 52700e1f3..5701b024a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -13078,6 +13078,11 @@ readline2@^1.0.1: is-fullwidth-code-point "^1.0.0" mute-stream "0.0.5" +real-cancellable-promise@^1.1.1: + version "1.1.2" + resolved "https://registry.yarnpkg.com/real-cancellable-promise/-/real-cancellable-promise-1.1.2.tgz#af9f7b68ae6828f71af5346132cf427eb859745a" + integrity sha512-eq/nAAVW+hj29x292W6yOkeEJ2F/pABnYC5cUfivOsIvSvF/Z0V2tWiyPK73+ay9DZ27CKp7Q+JkCwzmbwE75Q== + recursive-readdir@2.2.2: version "2.2.2" resolved "https://registry.yarnpkg.com/recursive-readdir/-/recursive-readdir-2.2.2.tgz#9946fb3274e1628de6e36b2f6714953b4845094f" @@ -14192,10 +14197,10 @@ static-extend@^0.1.1: resolved "https://registry.yarnpkg.com/statuses/-/statuses-1.5.0.tgz#161c7dac177659fd9811f43771fa99381478628c" integrity sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow= -store2@^2.12.0: - version "2.12.0" - resolved "https://registry.yarnpkg.com/store2/-/store2-2.12.0.tgz#e1f1b7e1a59b6083b2596a8d067f6ee88fd4d3cf" - integrity sha512-7t+/wpKLanLzSnQPX8WAcuLCCeuSHoWdQuh9SB3xD0kNOM38DNf+0Oa+wmvxmYueRzkmh6IcdKFtvTa+ecgPDw== +store2@^2.13.0: + version "2.14.2" + resolved "https://registry.yarnpkg.com/store2/-/store2-2.14.2.tgz#56138d200f9fe5f582ad63bc2704dbc0e4a45068" + integrity sha512-siT1RiqlfQnGqgT/YzXVUNsom9S0H1OX+dpdGN1xkyYATo4I6sep5NmsRD/40s3IIOvlCq6akxkqG82urIZW1w== stream-browserify@^2.0.1: version "2.0.2" @@ -14663,10 +14668,10 @@ tar@^6.0.2: mkdirp "^1.0.3" yallist "^4.0.0" -teledrive-client@^2.8.2: - version "2.8.2" - resolved "https://registry.yarnpkg.com/teledrive-client/-/teledrive-client-2.8.2.tgz#825ff5353a5a8f05460665a440068ed3d06d3e58" - integrity sha512-tsbrqFEHurYepyvBCw3fh3/lXzTT1PDy2jcyqr8b4wh6QHbfgRYAJw9J2r/DLRSzL9wahcLlgyn3WYXczxfmCQ== +telegram@^2.15.5: + version "2.15.5" + resolved "https://registry.yarnpkg.com/telegram/-/telegram-2.15.5.tgz#0eeba38366320922201404ae5d86f306b197b6fd" + integrity sha512-8xYhZ5FpdvGaGijhiV5wEcxNbiWa0NykBCC7/rhcjbQI91WYwkSFMQFBEoQTn24+w9jBA2Fzi0kNzX8N5Zs3Mw== dependencies: "@cryptography/aes" "^0.1.1" async-mutex "^0.3.0" @@ -14677,8 +14682,9 @@ teledrive-client@^2.8.2: node-localstorage "^2.2.1" pako "^2.0.3" path-browserify "^1.0.1" + real-cancellable-promise "^1.1.1" socks "^2.6.2" - store2 "^2.12.0" + store2 "^2.13.0" ts-custom-error "^3.2.0" websocket "^1.0.34" optionalDependencies: