File size: 10,361 Bytes
8820bb8
 
 
 
 
 
 
859f406
8820bb8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
859f406
8820bb8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import { useEffect, useMemo, useState } from "react";
import {
  App as AntdApp,
  Button,
  Form,
  Input,
  Layout,
  message,
  Modal,
  Progress,
  Space,
  Table,
  Tabs,
  Tag,
  Typography,
  Upload,
} from "antd";
import { api, clearToken, getToken, setToken } from "../api/client";

const { Header, Content } = Layout;
const { Text } = Typography;

const taskColor = {
  queued: "default",
  running: "processing",
  success: "success",
  failed: "error",
};

export function App() {
  const [token, setTokenState] = useState(getToken());
  const [pwd, setPwd] = useState("");
  const [currentPath, setCurrentPath] = useState(".");
  const [entries, setEntries] = useState([]);
  const [tasks, setTasks] = useState([]);
  const [loading, setLoading] = useState(false);
  const [downloadOpen, setDownloadOpen] = useState(false);
  const [extractOpen, setExtractOpen] = useState(false);
  const [apiMsg, contextHolder] = message.useMessage();

  async function loadFiles(path = currentPath) {
    setLoading(true);
    try {
      const data = await api(`/api/fs/list?path=${encodeURIComponent(path)}`);
      setEntries(data.entries || []);
      setCurrentPath(path);
    } catch (err) {
      apiMsg.error(String(err.message || err));
    } finally {
      setLoading(false);
    }
  }

  async function loadTasks() {
    try {
      const data = await api("/api/tasks?limit=100");
      setTasks(data.tasks || []);
    } catch (err) {
      if (String(err.message || "").includes("401")) {
        clearToken();
        setTokenState("");
      }
    }
  }

  useEffect(() => {
    if (!token) return;
    loadFiles(".");
    loadTasks();
    const timer = setInterval(loadTasks, 2000);
    return () => clearInterval(timer);
  }, [token]);

  const columns = useMemo(
    () => [
      {
        title: "Name",
        dataIndex: "name",
        render: (_, row) =>
          row.isDir ? (
            <a onClick={() => loadFiles(row.path)}>{row.name}</a>
          ) : (
            <span>{row.name}</span>
          ),
      },
      {
        title: "Type",
        dataIndex: "isDir",
        render: (v) => (v ? "Directory" : "File"),
      },
      {
        title: "Size",
        dataIndex: "size",
      },
      {
        title: "Action",
        render: (_, row) => (
          <Space>
            <Button
              danger
              size="small"
              onClick={async () => {
                await api("/api/fs/delete", {
                  method: "POST",
                  body: JSON.stringify({ path: row.path }),
                });
                apiMsg.success("Deleted");
                loadFiles(currentPath);
              }}
            >
              Delete
            </Button>
            {!row.isDir && (
              <Button
                size="small"
                onClick={() =>
                  window.open(
                    `/api/fs/download?path=${encodeURIComponent(row.path)}`,
                    "_blank"
                  )
                }
              >
                Download
              </Button>
            )}
          </Space>
        ),
      },
    ],
    [currentPath]
  );

  if (!token) {
    return (
      <AntdApp>
        {contextHolder}
        <div className="center-card">
          <h2>FastFileViewer Login</h2>
          <Space.Compact style={{ width: "100%" }}>
            <Input.Password
              placeholder="Admin password"
              value={pwd}
              onChange={(e) => setPwd(e.target.value)}
              onPressEnter={async () => {
                try {
                  const data = await api("/api/login", {
                    method: "POST",
                    body: JSON.stringify({ password: pwd }),
                  });
                  setToken(data.token);
                  setTokenState(data.token);
                  setPwd("");
                } catch (err) {
                  apiMsg.error("Login failed");
                }
              }}
            />
            <Button
              type="primary"
              onClick={async () => {
                try {
                  const data = await api("/api/login", {
                    method: "POST",
                    body: JSON.stringify({ password: pwd }),
                  });
                  setToken(data.token);
                  setTokenState(data.token);
                  setPwd("");
                } catch (err) {
                  apiMsg.error("Login failed");
                }
              }}
            >
              Login
            </Button>
          </Space.Compact>
        </div>
      </AntdApp>
    );
  }

  return (
    <AntdApp>
      {contextHolder}
      <Layout style={{ minHeight: "100vh" }}>
        <Header className="header">
          <Text strong style={{ color: "#fff" }}>
            FastFileViewer
          </Text>
          <Button
            onClick={() => {
              clearToken();
              setTokenState("");
            }}
          >
            Logout
          </Button>
        </Header>
        <Content className="content">
          <Tabs
            items={[
              {
                key: "files",
                label: "Files",
                children: (
                  <>
                    <Space style={{ marginBottom: 12 }}>
                      <Text>Current: {currentPath}</Text>
                      <Button onClick={() => loadFiles(".")}>Root</Button>
                      <Button onClick={() => loadFiles(currentPath)}>Refresh</Button>
                      <Button onClick={() => setDownloadOpen(true)}>
                        URL Download
                      </Button>
                      <Button onClick={() => setExtractOpen(true)}>Extract</Button>
                      <Upload
                        showUploadList={false}
                        customRequest={async ({ file, onSuccess, onError }) => {
                          try {
                            const form = new FormData();
                            form.append("dir", currentPath);
                            form.append("file", file);
                            await api("/api/fs/upload", {
                              method: "POST",
                              body: form,
                            });
                            onSuccess?.("ok");
                            loadFiles(currentPath);
                          } catch (err) {
                            onError?.(err);
                          }
                        }}
                      >
                        <Button>Upload</Button>
                      </Upload>
                    </Space>
                    <Table
                      rowKey={(row) => row.path}
                      columns={columns}
                      dataSource={entries}
                      loading={loading}
                      pagination={false}
                    />
                  </>
                ),
              },
              {
                key: "tasks",
                label: "Tasks",
                children: (
                  <Table
                    rowKey={(row) => row.id}
                    dataSource={tasks}
                    pagination={false}
                    columns={[
                      { title: "ID", dataIndex: "id" },
                      { title: "Type", dataIndex: "type" },
                      {
                        title: "Status",
                        dataIndex: "status",
                        render: (v) => <Tag color={taskColor[v]}>{v}</Tag>,
                      },
                      {
                        title: "Progress",
                        dataIndex: "progress",
                        render: (v) => <Progress percent={v} size="small" />,
                      },
                      { title: "Source", dataIndex: "source" },
                      { title: "Target", dataIndex: "targetPath" },
                      { title: "Error", dataIndex: "error" },
                    ]}
                  />
                ),
              },
            ]}
          />
        </Content>
      </Layout>

      <Modal
        open={downloadOpen}
        title="Create Download Task"
        onCancel={() => setDownloadOpen(false)}
        footer={null}
      >
        <Form
          layout="vertical"
          onFinish={async (values) => {
            await api("/api/tasks/download", {
              method: "POST",
              body: JSON.stringify(values),
            });
            setDownloadOpen(false);
            loadTasks();
          }}
        >
          <Form.Item
            label="URL"
            name="url"
            rules={[{ required: true, message: "Please input URL" }]}
          >
            <Input placeholder="https://example.com/file.zip" />
          </Form.Item>
          <Form.Item
            label="Target Path"
            name="targetPath"
            initialValue={`${currentPath}/download.bin`}
            rules={[{ required: true, message: "Please input target path" }]}
          >
            <Input />
          </Form.Item>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </Form>
      </Modal>

      <Modal
        open={extractOpen}
        title="Create Extract Task"
        onCancel={() => setExtractOpen(false)}
        footer={null}
      >
        <Form
          layout="vertical"
          onFinish={async (values) => {
            await api("/api/tasks/extract", {
              method: "POST",
              body: JSON.stringify(values),
            });
            setExtractOpen(false);
            loadTasks();
          }}
        >
          <Form.Item
            label="Archive Path"
            name="sourcePath"
            rules={[{ required: true, message: "Please input archive path" }]}
          >
            <Input placeholder="path/to/file.zip" />
          </Form.Item>
          <Form.Item
            label="Target Dir"
            name="targetPath"
            initialValue={currentPath}
            rules={[{ required: true, message: "Please input target dir" }]}
          >
            <Input />
          </Form.Item>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </Form>
      </Modal>
    </AntdApp>
  );
}