server.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. package httpfile
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "log"
  7. "net/http"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "ftp-server/config"
  12. )
  13. // Server represents the HTTP file server
  14. type Server struct {
  15. config *config.Config
  16. }
  17. // NewServer creates a new HTTP file server
  18. func NewServer(cfg *config.Config) *Server {
  19. return &Server{config: cfg}
  20. }
  21. // Start starts the HTTP file server
  22. func (s *Server) Start() error {
  23. if !s.config.HTTPFile.Enable {
  24. return nil
  25. }
  26. rootDir := s.config.HTTPFile.RootDir
  27. if err := os.MkdirAll(rootDir, 0755); err != nil {
  28. return fmt.Errorf("failed to create root directory: %v", err)
  29. }
  30. mux := http.NewServeMux()
  31. // Serve HTML page
  32. mux.HandleFunc("/", s.handleFileBrowser)
  33. // API endpoints
  34. mux.HandleFunc("/api/list", s.apiListDir)
  35. if s.config.HTTPFile.Upload {
  36. mux.HandleFunc("/api/upload", s.apiUpload)
  37. mux.HandleFunc("/api/create-folder", s.apiCreateFolder)
  38. }
  39. mux.HandleFunc("/api/download", s.apiDownload)
  40. mux.HandleFunc("/api/delete", s.apiDelete)
  41. addr := fmt.Sprintf("%s:%d", s.config.HTTPFile.Host, s.config.HTTPFile.Port)
  42. log.Printf("HTTP file server listening on http://%s", addr)
  43. return http.ListenAndServe(addr, mux)
  44. }
  45. func (s *Server) handleFileBrowser(w http.ResponseWriter, r *http.Request) {
  46. if r.URL.Path != "/" {
  47. http.NotFound(w, r)
  48. return
  49. }
  50. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  51. w.Write([]byte(fileBrowserHTML))
  52. }
  53. func (s *Server) apiListDir(w http.ResponseWriter, r *http.Request) {
  54. dir := r.URL.Query().Get("path")
  55. if dir == "" {
  56. dir = "/"
  57. }
  58. realPath := s.toRealPath(dir)
  59. entries, err := os.ReadDir(realPath)
  60. if err != nil {
  61. http.Error(w, `{"error":"Cannot read directory"}`, http.StatusInternalServerError)
  62. return
  63. }
  64. var files []map[string]interface{}
  65. for _, entry := range entries {
  66. info, _ := entry.Info()
  67. modTime := info.ModTime().Format("2006-01-02 15:04:05")
  68. size := info.Size()
  69. file := map[string]interface{}{
  70. "name": entry.Name(),
  71. "modTime": modTime,
  72. "size": formatSize(size),
  73. "isDir": entry.IsDir(),
  74. }
  75. if !entry.IsDir() {
  76. file["ext"] = strings.ToLower(filepath.Ext(entry.Name()))
  77. }
  78. files = append(files, file)
  79. }
  80. w.Header().Set("Content-Type", "application/json")
  81. json.NewEncoder(w).Encode(map[string]interface{}{
  82. "files": files,
  83. })
  84. }
  85. func (s *Server) apiDownload(w http.ResponseWriter, r *http.Request) {
  86. file := r.URL.Query().Get("file")
  87. if file == "" {
  88. http.Error(w, "Missing file parameter", http.StatusBadRequest)
  89. return
  90. }
  91. realPath := s.toRealPath(file)
  92. if info, err := os.Stat(realPath); err != nil || info.IsDir() {
  93. http.Error(w, "File not found", http.StatusNotFound)
  94. return
  95. }
  96. http.ServeFile(w, r, realPath)
  97. log.Printf("HTTP download: %s from %s", file, r.RemoteAddr)
  98. }
  99. func (s *Server) apiUpload(w http.ResponseWriter, r *http.Request) {
  100. if r.Method != http.MethodPost {
  101. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  102. return
  103. }
  104. // Parse multipart form (max 500MB)
  105. err := r.ParseMultipartForm(500 << 20)
  106. if err != nil {
  107. http.Error(w, `{"error":"Failed to parse upload"}`, http.StatusBadRequest)
  108. return
  109. }
  110. dir := r.FormValue("path")
  111. if dir == "" {
  112. dir = "/"
  113. }
  114. files := r.MultipartForm.File["files"]
  115. if len(files) == 0 {
  116. http.Error(w, `{"error":"No files uploaded"}`, http.StatusBadRequest)
  117. return
  118. }
  119. realDir := s.toRealPath(dir)
  120. for _, fileHeader := range files {
  121. file, err := fileHeader.Open()
  122. if err != nil {
  123. continue
  124. }
  125. destPath := filepath.Join(realDir, fileHeader.Filename)
  126. destFile, err := os.Create(destPath)
  127. if err != nil {
  128. file.Close()
  129. continue
  130. }
  131. io.Copy(destFile, file)
  132. destFile.Close()
  133. file.Close()
  134. log.Printf("HTTP upload: %s (%d bytes) from %s", fileHeader.Filename, fileHeader.Size, r.RemoteAddr)
  135. }
  136. w.Header().Set("Content-Type", "application/json")
  137. json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
  138. }
  139. func (s *Server) apiCreateFolder(w http.ResponseWriter, r *http.Request) {
  140. if r.Method != http.MethodPost {
  141. http.Error(w, `{"error":"Method not allowed"}`, http.StatusMethodNotAllowed)
  142. return
  143. }
  144. var req struct {
  145. Path string `json:"path"`
  146. Name string `json:"name"`
  147. }
  148. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  149. http.Error(w, `{"error":"Invalid request"}`, http.StatusBadRequest)
  150. return
  151. }
  152. if req.Name == "" {
  153. http.Error(w, `{"error":"Folder name required"}`, http.StatusBadRequest)
  154. return
  155. }
  156. realPath := filepath.Join(s.toRealPath(req.Path), req.Name)
  157. if err := os.MkdirAll(realPath, 0755); err != nil {
  158. http.Error(w, `{"error":"Failed to create folder"}`, http.StatusInternalServerError)
  159. return
  160. }
  161. w.Header().Set("Content-Type", "application/json")
  162. json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
  163. }
  164. func (s *Server) apiDelete(w http.ResponseWriter, r *http.Request) {
  165. if r.Method != http.MethodPost {
  166. http.Error(w, `{"error":"Method not allowed"}`, http.StatusMethodNotAllowed)
  167. return
  168. }
  169. var req struct {
  170. Path string `json:"path"`
  171. }
  172. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  173. http.Error(w, `{"error":"Invalid request"}`, http.StatusBadRequest)
  174. return
  175. }
  176. realPath := s.toRealPath(req.Path)
  177. if err := os.RemoveAll(realPath); err != nil {
  178. http.Error(w, `{"error":"Delete failed"}`, http.StatusInternalServerError)
  179. return
  180. }
  181. w.Header().Set("Content-Type", "application/json")
  182. json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
  183. }
  184. func (s *Server) toRealPath(httpPath string) string {
  185. rootDir := s.config.HTTPFile.RootDir
  186. cleanPath := strings.TrimPrefix(httpPath, "/")
  187. return filepath.Join(rootDir, cleanPath)
  188. }
  189. func formatSize(size int64) string {
  190. switch {
  191. case size < 1024:
  192. return fmt.Sprintf("%d B", size)
  193. case size < 1024*1024:
  194. return fmt.Sprintf("%.1f KB", float64(size)/1024)
  195. case size < 1024*1024*1024:
  196. return fmt.Sprintf("%.1f MB", float64(size)/(1024*1024))
  197. default:
  198. return fmt.Sprintf("%.1f GB", float64(size)/(1024*1024*1024))
  199. }
  200. }
  201. // fileBrowserHTML is the embedded HTML page
  202. const fileBrowserHTML = `<!DOCTYPE html>
  203. <html lang="zh-CN">
  204. <head>
  205. <meta charset="UTF-8">
  206. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  207. <title>HTTP 文件服务器</title>
  208. <style>
  209. * { margin: 0; padding: 0; box-sizing: border-box; }
  210. body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; }
  211. .container { max-width: 1200px; margin: 0 auto; padding: 20px; }
  212. .header { background: white; border-radius: 12px; padding: 24px; margin-bottom: 20px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); }
  213. .header h1 { font-size: 28px; color: #333; margin-bottom: 8px; }
  214. .header p { color: #888; font-size: 14px; }
  215. .breadcrumb { background: white; border-radius: 12px; padding: 16px 24px; margin-bottom: 20px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
  216. .breadcrumb a { color: #667eea; text-decoration: none; font-weight: 500; padding: 4px 8px; border-radius: 6px; transition: background 0.2s; }
  217. .breadcrumb a:hover { background: #f0f4ff; }
  218. .breadcrumb span { color: #999; font-size: 20px; }
  219. .actions { background: white; border-radius: 12px; padding: 16px 24px; margin-bottom: 20px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
  220. .btn { padding: 10px 20px; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 600; transition: all 0.3s; display: inline-flex; align-items: center; gap: 6px; }
  221. .btn-primary { background: linear-gradient(135deg, #667eea, #764ba2); color: white; }
  222. .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 4px 15px rgba(102,126,234,0.4); }
  223. .btn-success { background: #28a745; color: white; }
  224. .btn-success:hover { background: #218838; }
  225. .btn-danger { background: #dc3545; color: white; }
  226. .btn-danger:hover { background: #c82333; }
  227. .btn-sm { padding: 6px 12px; font-size: 12px; }
  228. .file-list { background: white; border-radius: 12px; padding: 24px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); }
  229. table { width: 100%; border-collapse: collapse; }
  230. th, td { padding: 12px 16px; text-align: left; border-bottom: 1px solid #f0f0f0; font-size: 14px; }
  231. th { background: #fafafa; font-weight: 600; color: #555; }
  232. tr:hover { background: #f8f9ff; }
  233. .file-name { display: flex; align-items: center; gap: 8px; }
  234. .file-icon { width: 32px; height: 32px; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 18px; }
  235. .folder-icon { background: #ffeaa7; }
  236. .file-icon-doc { background: #74b9ff; }
  237. .file-icon-img { background: #ff7675; }
  238. .file-icon-zip { background: #a29bfe; }
  239. .file-icon-code { background: #55efc4; }
  240. .file-icon-other { background: #dfe6e9; }
  241. .file-link { color: #667eea; text-decoration: none; font-weight: 500; }
  242. .file-link:hover { text-decoration: underline; }
  243. .actions-cell { display: flex; gap: 8px; }
  244. .toast { position: fixed; top: 80px; right: 30px; padding: 14px 24px; border-radius: 8px; color: white; font-size: 14px; font-weight: 500; z-index: 2000; animation: slideIn 0.3s ease; }
  245. .toast-success { background: #28a745; }
  246. .toast-error { background: #dc3545; }
  247. @keyframes slideIn { from { transform: translateX(100px); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
  248. .modal-overlay { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 1000; justify-content: center; align-items: center; }
  249. .modal-overlay.show { display: flex; }
  250. .modal { background: white; border-radius: 12px; padding: 30px; width: 480px; max-width: 90%; }
  251. .modal h2 { margin-bottom: 24px; font-size: 20px; }
  252. .modal-actions { display: flex; justify-content: flex-end; gap: 12px; margin-top: 24px; }
  253. .form-group { margin-bottom: 16px; }
  254. .form-group label { display: block; margin-bottom: 6px; font-weight: 600; color: #555; font-size: 14px; }
  255. .form-group input { width: 100%; padding: 10px 14px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; }
  256. .form-group input:focus { outline: none; border-color: #667eea; }
  257. .drop-zone { border: 2px dashed #667eea; border-radius: 8px; padding: 40px 20px; text-align: center; background: #f8f9ff; transition: all 0.3s; cursor: pointer; margin-bottom: 16px; }
  258. .drop-zone:hover, .drop-zone.dragover { background: #e8ebff; border-color: #764ba2; }
  259. .progress-bar { width: 100%; height: 8px; background: #f0f0f0; border-radius: 4px; overflow: hidden; margin-top: 12px; display: none; }
  260. .progress-bar.show { display: block; }
  261. .progress-fill { height: 100%; background: linear-gradient(135deg, #667eea, #764ba2); transition: width 0.3s; width: 0%; }
  262. .empty-state { text-align: center; padding: 60px 20px; color: #999; }
  263. .empty-state .icon { font-size: 64px; margin-bottom: 16px; }
  264. </style>
  265. </head>
  266. <body>
  267. <div class="container">
  268. <div class="header">
  269. <h1>&#128193; HTTP 文件服务器</h1>
  270. <p>在线浏览、下载、上传文件</p>
  271. </div>
  272. <div class="breadcrumb" id="breadcrumb">
  273. </div>
  274. <div class="actions">
  275. <button class="btn btn-primary" onclick="document.getElementById('uploadInput').click()">
  276. &#128229; 上传文件
  277. </button>
  278. <input type="file" id="uploadInput" multiple style="display:none" onchange="uploadFiles(this.files)">
  279. <button class="btn btn-success" onclick="showNewFolderModal()">
  280. &#128193; 新建文件夹
  281. </button>
  282. <button class="btn btn-danger" onclick="refresh()">
  283. &#128260; 刷新
  284. </button>
  285. </div>
  286. <div class="file-list">
  287. <table id="fileTable">
  288. <thead>
  289. <tr><th>名称</th><th>大小</th><th>修改时间</th><th>操作</th></tr>
  290. </thead>
  291. <tbody id="fileTableBody">
  292. </tbody>
  293. </table>
  294. <div class="empty-state" id="emptyState" style="display:none">
  295. <div class="icon">&#128193;</div>
  296. <div>目录为空</div>
  297. </div>
  298. </div>
  299. </div>
  300. <!-- New Folder Modal -->
  301. <div class="modal-overlay" id="folderModal">
  302. <div class="modal">
  303. <h2>&#128193; 新建文件夹</h2>
  304. <div class="form-group">
  305. <label>文件夹名称</label>
  306. <input type="text" id="folderName" placeholder="输入文件夹名称" onkeypress="if(event.key==='Enter')createFolder()">
  307. </div>
  308. <div class="modal-actions">
  309. <button class="btn" style="background:#eee" onclick="closeFolderModal()">取消</button>
  310. <button class="btn btn-primary" onclick="createFolder()">创建</button>
  311. </div>
  312. </div>
  313. </div>
  314. <!-- Upload Progress -->
  315. <div class="modal-overlay" id="uploadModal">
  316. <div class="modal">
  317. <h2>&#128229; 上传进度</h2>
  318. <div id="uploadStatus" style="margin-bottom:12px; font-size:14px; color:#666;"></div>
  319. <div class="progress-bar show"><div class="progress-fill" id="progressFill"></div></div>
  320. </div>
  321. </div>
  322. <script>
  323. let currentPath = '/';
  324. function init() {
  325. loadFiles();
  326. }
  327. function loadFiles() {
  328. fetch('/api/list?path=' + encodeURIComponent(currentPath))
  329. .then(r => r.json())
  330. .then(data => {
  331. const tbody = document.getElementById('fileTableBody');
  332. tbody.innerHTML = '';
  333. if (!data.files || data.files.length === 0) {
  334. document.getElementById('emptyState').style.display = 'block';
  335. document.getElementById('fileTable').style.display = 'none';
  336. return;
  337. }
  338. document.getElementById('emptyState').style.display = 'none';
  339. document.getElementById('fileTable').style.display = 'table';
  340. data.files.forEach(f => {
  341. const tr = document.createElement('tr');
  342. const icon = f.isDir ? '📁' : getFileIcon(f.name);
  343. const iconClass = f.isDir ? 'folder-icon' : 'file-icon-' + getFileType(f.name);
  344. tr.innerHTML = '<td><div class="file-name"><div class="file-icon ' + iconClass + '">' + icon + '</div>' +
  345. (f.isDir ? '<a class="file-link" href="#" onclick="enterFolder(\\'' + escapeStr(f.name) + '\\');return false;">' + f.name + '</a>' : '<span>' + f.name + '</span>') +
  346. '</div></td><td>' + (f.isDir ? '-' : f.size) + '</td><td>' + f.modTime + '</td><td class="actions-cell">' +
  347. (f.isDir ? '<button class="btn btn-sm btn-primary" onclick="enterFolder(\\'' + escapeStr(f.name) + '\\')">打开</button>' : '<a href="/api/download?file=' + encodeURIComponent(currentPath + f.name) + '" class="btn btn-sm btn-success">下载</a>') +
  348. '<button class="btn btn-sm btn-danger" onclick="deleteItem(\\'' + escapeStr(f.name) + '\\', ' + f.isDir + ')">删除</button></td></tr>';
  349. tbody.appendChild(tr);
  350. });
  351. updateBreadcrumb();
  352. });
  353. }
  354. function escapeStr(s) {
  355. return s.replace(/\\/g, '\\\\\\\\').replace(/'/g, "\\\\'");
  356. }
  357. function enterFolder(name) {
  358. currentPath = currentPath === '/' ? '/' + name + '/' : currentPath + name + '/';
  359. loadFiles();
  360. }
  361. function updateBreadcrumb() {
  362. const bc = document.getElementById('breadcrumb');
  363. bc.innerHTML = '<a href="#" onclick="goTo(\'/\');return false;">根目录</a>';
  364. const parts = currentPath.split('/').filter(p => p);
  365. let path = '';
  366. parts.forEach(p => {
  367. path += p + '/';
  368. bc.innerHTML += '<span>/</span><a href="#" onclick="goTo(\\'' + path + '\\');return false;">' + p + '</a>';
  369. });
  370. }
  371. function goTo(path) {
  372. currentPath = path;
  373. loadFiles();
  374. }
  375. function refresh() {
  376. loadFiles();
  377. showToast('已刷新');
  378. }
  379. function showNewFolderModal() {
  380. document.getElementById('folderName').value = '';
  381. document.getElementById('folderModal').classList.add('show');
  382. document.getElementById('folderName').focus();
  383. }
  384. function closeFolderModal() {
  385. document.getElementById('folderModal').classList.remove('show');
  386. }
  387. function createFolder() {
  388. const name = document.getElementById('folderName').value.trim();
  389. if (!name) { showToast('请输入文件夹名称', 'error'); return; }
  390. fetch('/api/create-folder', {
  391. method: 'POST',
  392. headers: { 'Content-Type': 'application/json' },
  393. body: JSON.stringify({ path: currentPath, name: name })
  394. }).then(r => r.json()).then(data => {
  395. if (data.status === 'ok') {
  396. showToast('文件夹已创建');
  397. closeFolderModal();
  398. loadFiles();
  399. } else {
  400. showToast(data.error || '创建失败', 'error');
  401. }
  402. });
  403. }
  404. function uploadFiles(files) {
  405. if (!files || files.length === 0) return;
  406. document.getElementById('uploadModal').classList.add('show');
  407. document.getElementById('uploadStatus').textContent = '正在上传 ' + files.length + ' 个文件...';
  408. document.getElementById('progressFill').style.width = '0%';
  409. const formData = new FormData();
  410. formData.append('path', currentPath);
  411. for (let i = 0; i < files.length; i++) {
  412. formData.append('files', files[i]);
  413. }
  414. const xhr = new XMLHttpRequest();
  415. xhr.open('POST', '/api/upload');
  416. xhr.upload.onprogress = function(e) {
  417. if (e.lengthComputable) {
  418. const percent = (e.loaded / e.total * 100).toFixed(1);
  419. document.getElementById('progressFill').style.width = percent + '%';
  420. }
  421. };
  422. xhr.onload = function() {
  423. setTimeout(() => {
  424. document.getElementById('uploadModal').classList.remove('show');
  425. if (xhr.status === 200) {
  426. showToast('上传成功');
  427. loadFiles();
  428. } else {
  429. showToast('上传失败', 'error');
  430. }
  431. }, 500);
  432. };
  433. xhr.send(formData);
  434. document.getElementById('uploadInput').value = '';
  435. }
  436. function deleteItem(name, isDir) {
  437. const confirmMsg = isDir ? '确定要删除文件夹 "' + name + '" 及其所有内容吗?' : '确定要删除文件 "' + name + '" 吗?';
  438. if (!confirm(confirmMsg)) return;
  439. fetch('/api/delete', {
  440. method: 'POST',
  441. headers: { 'Content-Type': 'application/json' },
  442. body: JSON.stringify({ path: currentPath + name })
  443. }).then(r => r.json()).then(data => {
  444. if (data.status === 'ok') {
  445. showToast('已删除');
  446. loadFiles();
  447. } else {
  448. showToast(data.error || '删除失败', 'error');
  449. }
  450. });
  451. }
  452. function getFileIcon(name) {
  453. const ext = name.split('.').pop().toLowerCase();
  454. const icons = {
  455. 'doc': '📄', 'docx': '📄', 'pdf': '📄', 'txt': '📄',
  456. 'xls': '📊', 'xlsx': '📊', 'csv': '📊',
  457. 'jpg': '🖼️', 'jpeg': '🖼️', 'png': '🖼️', 'gif': '🖼️', 'bmp': '🖼️',
  458. 'mp3': '🎵', 'wav': '🎵', 'flac': '🎵',
  459. 'mp4': '🎬', 'avi': '🎬', 'mkv': '🎬', 'mov': '🎬',
  460. 'zip': '📦', 'rar': '📦', '7z': '📦', 'tar': '📦', 'gz': '📦',
  461. 'js': '💻', 'ts': '💻', 'py': '💻', 'go': '💻', 'java': '💻', 'c': '💻', 'cpp': '💻', 'html': '💻', 'css': '💻', 'json': '💻', 'xml': '💻', 'yml': '💻', 'yaml': '💻',
  462. };
  463. return icons[ext] || '📄';
  464. }
  465. function getFileType(name) {
  466. const ext = name.split('.').pop().toLowerCase();
  467. if (['jpg','jpeg','png','gif','bmp','svg'].includes(ext)) return 'img';
  468. if (['zip','rar','7z','tar','gz'].includes(ext)) return 'zip';
  469. if (['js','ts','py','go','java','c','cpp','html','css','json','xml','yml','yaml'].includes(ext)) return 'code';
  470. return 'doc';
  471. }
  472. function showToast(msg, type) {
  473. const toast = document.createElement('div');
  474. toast.className = 'toast ' + (type === 'error' ? 'toast-error' : 'toast-success');
  475. toast.textContent = msg;
  476. document.body.appendChild(toast);
  477. setTimeout(() => toast.remove(), 3000);
  478. }
  479. // Drag and drop support
  480. document.addEventListener('DOMContentLoaded', function() {
  481. document.addEventListener('dragover', function(e) { e.preventDefault(); });
  482. document.addEventListener('drop', function(e) {
  483. e.preventDefault();
  484. if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
  485. uploadFiles(e.dataTransfer.files);
  486. }
  487. });
  488. });
  489. init();
  490. </script>
  491. </body>
  492. </html>
  493. `