從零開始-文件資源管理器-26-Next.js 對(duì)接 QBittorrent web api

為后續(xù)實(shí)現(xiàn)自定義訂閱下載前置功能。使用 Next.js 對(duì)接 qBittorrent web api。實(shí)現(xiàn) torrent 列表的呈現(xiàn)。

開發(fā)

主要使用 @ctrl/qbittorrent 這個(gè)依賴對(duì)接 qBittorrent 服務(wù)。由 Next.js 與 antd 實(shí)現(xiàn) UI 的呈現(xiàn)。

基本用法很簡(jiǎn)單

import { QBittorrent } from '@ctrl/qbittorrent';

const client = new QBittorrent({
  baseUrl: 'http://localhost:8080/',
  username: 'admin',
  password: 'adminadmin',
});

async function main() {
  const res = await qbittorrent.getAllData();
  console.log(res);
}

開發(fā)時(shí),將 username 與 password 通過環(huán)境變量讀取。本地開發(fā)使用 .env.local 控制。生產(chǎn)環(huán)境通過 explorer.docker-compose.yml 進(jìn)行控制。

qBittorrent UI 呈現(xiàn)

封裝一個(gè) q-bittorrent-client.ts 方法。

import { QBittorrent } from '@ctrl/qbittorrent'

export const client = new QBittorrent({
  baseUrl: 'http://192.168.31.17:8080/',
  username: process.env.Q_BITTORRENT_USERNAME,
  password: process.env.Q_BITTORRENT_PASSWORD,
})

通過環(huán)境變量的 Q_BITTORRENT_USERNAME 與 Q_BITTORRENT_PASSWORD 獲取到對(duì)應(yīng)的 username 與 password。

創(chuàng)建一個(gè) .env.local 文件并輸入下面的內(nèi)容。

explorer/.env.local

Q_BITTORRENT_USERNAME=admin
Q_BITTORRENT_PASSWORD=adminadmin

有些 qBittorrent 默認(rèn)的用戶名與密碼為 admin adminadmin

創(chuàng)建頂部 layout 組件。實(shí)現(xiàn) Card 組件內(nèi)部滾動(dòng)。

explorer/src/app/q-bittorrent/layout.tsx

import React from 'react'
import { Card, Space } from 'antd'
import ChangeThemeDropdown from '@/components/change-theme/change-theme-dropdown'
import type { Metadata } from 'next'
import LayoutFooter from '@/app/q-bittorrent/layout-footer'

export const metadata: Metadata = {
  title: '從零開始-文件資源管理器-qBittorrent',
  description: '從零開始-文件資源管理器-qBittorrent',
}

const layout: React.FC<React.PropsWithChildren> = ({ children }) => {
  return (
    <>
      <Card
        title={<>qBittorrent</>}
        style={{ height: 'calc(100vh - 40px)', display: 'flex', flexDirection: 'column' }}
        bodyStyle={{
          flex: 1,
          overflow: 'scroll',
          overscrollBehavior: 'contain',
        }}
        extra={
          <Space>
            <ChangeThemeDropdown />
          </Space>
        }
      >
        {children}
      </Card>
      <LayoutFooter />
    </>
  )
}

export default layout

使用 listTorrents 方法獲取 qBittorrent 內(nèi)的 torrent 列表。并將內(nèi)容插入 QBittorrentContext 上下文內(nèi)。

explorer/src/app/q-bittorrent/page.tsx

import React from 'react'
import { client } from '@/app/q-bittorrent/q-bittorrent-client'
import { QBittorrentProvider } from '@/app/q-bittorrent/q-bittorrent-context'
import TorrentTable from '@/app/q-bittorrent/torrent-table'

const Page: React.FC = async () => {
  const data = await client.listTorrents()

  return (
    <QBittorrentProvider value={data}>
      <TorrentTable />
    </QBittorrentProvider>
  )
}

export default Page

上下文文件

explorer/src/app/q-bittorrent/q-bittorrent-context.tsx

'use client'
import createCtx from '@/lib/create-ctx'
import React from 'react'
import type { Torrent } from '@ctrl/qbittorrent/dist/src/types'

export const QBittorrentContext = createCtx<Torrent[]>()

export const QBittorrentProvider: React.FC<React.ProviderProps<Torrent[]>> = ({ children, value }) => {
  return <QBittorrentContext.ContextProvider value={value}>{children}</QBittorrentContext.ContextProvider>
}

使用 antd Table 組件簡(jiǎn)單處理下 torrent 列表。并關(guān)閉 Table 組件的分頁配置。

explorer/src/app/q-bittorrent/torrent-table.tsx

'use client'
import React from 'react'
import { Table } from 'antd'
import { QBittorrentContext } from '@/app/q-bittorrent/q-bittorrent-context'
import DateFormat from '@/components/date-format'
import Bit from '@/components/bit'

const TorrentTable: React.FC = () => {
  const data = QBittorrentContext.useStore()

  return (
    <Table
      rowKey="hash"
      pagination={false}
      dataSource={data}
      columns={[
        { key: 'name', title: 'name', dataIndex: 'name', width: '30%' },
        { key: 'save_path', title: '保存路徑', dataIndex: 'save_path', width: '20%' },
        { key: 'progress', title: '進(jìn)度', dataIndex: 'progress' },
        { key: 'size', title: '大小', dataIndex: 'size', render: (size) => <Bit>{size}</Bit> },
        { key: 'completed', title: '完成大小', dataIndex: 'completed', render: (size) => <Bit>{size}</Bit> },
        {
          key: 'added_on',
          title: '添加時(shí)間',
          dataIndex: 'added_on',
          sorter: (a, b) => a.added_on - b.added_on,
          render: (time) => <DateFormat>{time * 1000}</DateFormat>,
        },
        {
          key: 'completion_on',
          title: '完成時(shí)間',
          dataIndex: 'completion_on',
          sorter: (a, b) => a.completion_on - b.completion_on,
          render: (time) => <DateFormat>{time * 1000}</DateFormat>,
        },
      ]}
    />
  )
}

export default TorrentTable

創(chuàng)建一個(gè) actions 文件。用于存放 server action。

explorer/src/app/q-bittorrent/actions.tsx

添加一個(gè) getTransferInfo 方法,用于獲取當(dāng)前下載速度與上傳速度信息。依賴組件沒有提供對(duì)應(yīng)方法,需要自行調(diào)用接口獲取。參考接口文檔

使用依賴提供的 request 方法,加上對(duì)應(yīng)的 path 即可獲取到對(duì)應(yīng)的接口信息。

'use server'
import { client } from '@/app/q-bittorrent/q-bittorrent-client'

/**
 * https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-(qBittorrent-4.1)#get-global-transfer-info
 */
type Info = {
  connection_status: 'connected' | 'firewalled' | 'disconnected'
  dht_nodes: number
  dl_info_data: number
  dl_info_speed: number
  dl_rate_limit: number
  up_info_data: number
  up_info_speed: number
  up_rate_limit: number
}
export const getTransferInfo = () => client.request<Info>('/transfer/info', 'GET')

通過上面的方法即可獲取到“當(dāng)前下載速度與上傳速度信息”。

創(chuàng)建一個(gè) use-transfer-info hooks 文件。用于輪詢獲取當(dāng)前下載速度與上傳速度。

explorer/src/app/q-bittorrent/use-transfer-info.tsx

'use client'
import { useRequest } from 'ahooks'
import { getTransferInfo } from '@/app/q-bittorrent/actions'

export const useGetTransferInfo = () => {
  const { data } = useRequest(() => getTransferInfo(), {
    pollingInterval: 1000,
  })

  return { data }
}

這里使用了 useRequest 提供的輪詢參數(shù)。每秒輪詢獲取接口信息。

創(chuàng)建一個(gè)呈現(xiàn)上傳于下載信息的組件

explorer/src/app/q-bittorrent/global-torrent-speed.tsx

'use client'
import React from 'react'
import { Space } from 'antd'
import { useGetTransferInfo } from '@/app/q-bittorrent/use-transfer-info'
import Bit from '@/components/bit'

const GlobalTorrentSpeed: React.FC = () => {
  const { data } = useGetTransferInfo()

  return (
    <Space split=" | ">
      <Space>
        <span>DHT</span>
        <span>{data?.dht_nodes}</span>
      </Space>
      <Space>
        <span>下載</span>
        <Bit
          after={
            <>
              /s(<Bit>{data?.dl_info_data}</Bit>)
            </>
          }
        >
          {data?.dl_info_speed}
        </Bit>
      </Space>
      <Space>
        <span>上傳</span>
        <Bit
          after={
            <>
              /s(<Bit>{data?.up_info_data}</Bit>)
            </>
          }
        >
          {data?.up_info_speed}
        </Bit>
      </Space>
    </Space>
  )
}

export default GlobalTorrentSpeed

配置好 layout-footer 組件

explorer/src/app/q-bittorrent/layout-footer

'use client'
import React from 'react'
import { Flex } from 'antd'
import GlobalTorrentSpeed from '@/app/q-bittorrent/global-torrent-speed'

const LayoutFooter: React.FC = () => {
  return (
    <Flex style={{ height: 40, padding: '0 20px' }} justify="flex-end" align="center">
      <GlobalTorrentSpeed />
    </Flex>
  )
}

export default LayoutFooter

到此,簡(jiǎn)單完成了 Next.js 對(duì)接 qBittorrent。并簡(jiǎn)單將 qBittorrent 的 torrent 列表渲染出來,間隔 1 秒輪詢獲取當(dāng)前下載速度、上傳信息。

這里只是簡(jiǎn)單的列出 torrent 列表等信息,并不是當(dāng)做一個(gè)可操作 qBittorrent 的 web ui。更多的功能還是在 qBittorrent 主界面進(jìn)行操作與配置。

如有需要,后續(xù)還會(huì)在這個(gè)界面的基礎(chǔ)上面添加一些簡(jiǎn)單的“增刪改查”功能。

效果

截屏2024-01-04 15.50.02.png

git-repo

yangWs29/share-explorer

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容