Quellcode durchsuchen

update 2024-06-03

junggilpark vor 1 Jahr
Ursprung
Commit
d3403b82ae

+ 3 - 3
appPackage/manifest.json

@@ -15,8 +15,8 @@
         "outline": "outline.png"
     },
     "name": {
-        "short": "share",
-        "full": "share"
+        "short": "share dev",
+        "full": "share dev"
     },
     "description": {
         "short": "Short description of share",
@@ -44,7 +44,7 @@
         "${{TAB_DOMAIN}}"
     ],
     "webApplicationInfo" : {
-        "id" : "${{TEAMS_APP_ID}}",
+        "id" : "677911c1-b334-4a22-9161-9eacebb2f68c",
         "resource" : "api://${{TAB_DOMAIN}}/${{TEAMS_APP_ID}}"
     }
 }

+ 1 - 1
env/.env.dev

@@ -13,4 +13,4 @@ RESOURCE_SUFFIX=
 TEAMS_APP_ID=0673c862-7edc-455d-9636-5559a0a8f2b9
 TAB_AZURE_STORAGE_RESOURCE_ID=
 TAB_ENDPOINT=https://localhost:53000
-TAB_DOMAIN=localhost:53000
+TAB_DOMAIN=localhost:53000

+ 4 - 2
env/.env.test

@@ -1,7 +1,9 @@
 CLOUD_INSTANCE="https://login.microsoftonline.com/" # cloud instance string should end with a trailing slash
 TENANT_ID="2e58414a-c6ae-43ff-aaf5-45ab8b78a404"
-CLIENT_ID="0673c862-7edc-455d-9636-5559a0a8f2b9"
-CLIENT_SECRET="xhZ8Q~9z1kuxKs~wt0EWbrtuG5FFlyS7WE8~~afa"
+#CLIENT_ID="0673c862-7edc-455d-9636-5559a0a8f2b9"
+CLIENT_ID="b802acc1-19bf-4a83-8e36-cca8d751978a"
+#CLIENT_SECRET="xhZ8Q~9z1kuxKs~wt0EWbrtuG5FFlyS7WE8~~afa"
+CLIENT_SECRET="IDv8Q~xA24gTMOydMvJlX7UGhRl46SCwG-BhLcPo"
 
 REDIRECT_URI="https://localhost:53000/redirect/"
 POST_LOGOUT_REDIRECT_URI="https://localhost:53000"

Datei-Diff unterdrückt, da er zu groß ist
+ 753 - 7
package-lock.json


+ 1 - 0
package.json

@@ -23,6 +23,7 @@
         "express-session": "^1.18.0",
         "fs": "^0.0.1-security",
         "jszip": "^3.10.1",
+        "mssql": "^10.0.2",
         "multer": "^1.4.5-lts.1",
         "path": "^0.12.7",
         "pptxgenjs": "^3.12.0",

+ 385 - 370
src/app.js

@@ -4,8 +4,9 @@ const fs = require("fs");
 const path = require("path");
 const express = require("express");
 const axios = require("axios");
+// const SERVER_PORT = process.env.port || process.env.PORT || 53000;
 const SERVER_PORT = process.env.port || process.env.PORT || 53000;
-const authProvider = require('./auth/AuthProvider');
+// const authProvider = require('./auth/AuthProvider');
 const {getFetch, updateFetch} = require('./fetch');
 const bodyParser = require('body-parser');
 const https = require('https');
@@ -16,8 +17,9 @@ const multer  = require('multer');
 const XLSX = require('xlsx');
 const pptxgen = require('pptxgenjs');
 const msal = require('@azure/msal-node');
+const {pool, sql} = require('./config/sql.js');
+const gateWayKey = process.env.GATE_WAY_KEY;
 
-require('dotenv').config({ path: './env/.env.test' });
 
 const msalConfig = {
   auth: {
@@ -26,7 +28,7 @@ const msalConfig = {
       clientSecret: process.env.TEAMS_APP_SECRET,
       knownAuthorities: [],
   },
-  cache: {
+  cache: { 
       // your implementation of caching
   },
   system: {
@@ -37,7 +39,9 @@ const msalConfig = {
 const cca = new msal.ConfidentialClientApplication(msalConfig);
 
 const {Document, Packer, Paragraph, TextRun} = require('docx');
+const messages = require('dote/src/messages.js');
 let WebSocketServer = require('websocket').server;
+// const redirectUri = 'https://localhost:53000/redirect';
 const redirectUri = 'https://localhost:53000/redirect';
 
 const storage =  multer.diskStorage({
@@ -68,8 +72,7 @@ serverApp.use(session({
 serverApp.set(express.json());
 serverApp.use(cookieParser());
 serverApp.use(express.urlencoded({ extended: false }));
-serverApp.use("/static",express.static(path.join(__dirname, 'static')));
-serverApp.use("/node_modules",express.static(path.join(__dirname, 'node_modules')));
+serverApp.use("/static", express.static(path.join(__dirname, 'static')));
 
 const options = {
   key: process.env.SSL_KEY_FILE ? fs.readFileSync(process.env.SSL_KEY_FILE) : undefined,
@@ -87,22 +90,11 @@ let wsServer = new WebSocketServer({
 wsServer.on('request', function(req) {
   var connection = req.accept();
   connection.on('message', function(message) {
-    // console.log(message);
     if (message && message.type === 'utf8') {
-      const {id, siteId, name, originSiteId, originId, totalCount, value, isFolder} = JSON.parse(message.utf8Data);
-      if (value && !isFolder) {
+      const { value } = JSON.parse(message.utf8Data);
+      if (value) {
         try {
-          const interval = setInterval(async ()=>{
-
-            const result = await axios.get(`${value}`);
-            if (result && result.data && result.data.percentageComplete >= 0) {
-              if (result.data.percentageComplete === 100) {
-                clearInterval(interval);
-              }
-              const percent = result.data.percentageComplete;
-              connection.sendUTF(percent);
-            }
-          }, 2000);
+          getPercentageComplete(value, connection);
         }
         catch (error) {
           // console.log(error);
@@ -117,6 +109,18 @@ wsServer.on('request', function(req) {
   })
 });
 
+async function getPercentageComplete(url, connection) {
+  const result = await axios.get(url);
+  if (result && result.data && result.data.percentageComplete >= 0) {
+    const percent = result.data.percentageComplete;
+    // console.log(result.data);
+    connection.sendUTF(Number(percent.toFixed(2)));
+    if (result.data.percentageComplete !== 100) {
+      setTimeout(()=>getPercentageComplete(url, connection), 1000);
+    }
+  }
+}
+
 const corsOption = {
   origin: "*",
 }
@@ -125,10 +129,6 @@ const corsOption = {
 serverApp.use(cors(corsOption));
 serverApp.use(bodyParser.json());
 
-server.listen(SERVER_PORT, function () {
-  console.log(`\n${serverApp.name} listening to ${SERVER_PORT}`);
-});
-
 serverApp.get("/tab", 
   // isAuthenticated, 
   async function (req, res, next) {
@@ -149,31 +149,37 @@ serverApp.post("/getProfileOnBehalfOf", async (req, res, next) => {
   req.session.auth = result;
   return res.send(result);
 })
-function isAuthenticated(req, res, next) {
-  if (!req.session.isAuthenticated) {
-    return res.redirect('/auth/signin'); // redirect to sign-in route
-  }
-  next();
-}; 
-
-function isAccessToken(req, res, next) {
-  if (!req.session.accessToken) {
-    return authProvider.acquireToken({
-      scopes: ['.default'],
-      redirectUri: redirectUri,
-      successRedirect: '/api-redirect'
-    })(req, res, next);
-  }
-  next();
-}
-
-serverApp.get("/auth/signin", authProvider.login({
-  scopes: ['.default'],
-  redirectUri: redirectUri,
-  successRedirect: '/tab'
-}))
-
-serverApp.post("/redirect", authProvider.handleRedirect());
+// function isAuthenticated(req, res, next) {
+//   if (!req.session.isAuthenticated) {
+//     return res.redirect('/auth/signin'); // redirect to sign-in route
+//   }
+//   next();
+// }; 
+
+// function isAccessToken(req, res, next) {
+//   if (!req.session.accessToken) { 
+//     return authProvider.acquireToken({
+//       scopes: ['.default'],
+//       redirectUri: redirectUri,
+//       successRedirect: '/api-redirect'
+//     })(req, res, next);
+//   }
+//   next();
+// }
+
+// serverApp.get("/auth/signin", authProvider.login({
+//   scopes: ['.default'],
+//   redirectUri: redirectUri,
+//   successRedirect: '/tab'
+// }))
+
+// serverApp.post("/redirect", authProvider.handleRedirect());
+serverApp.post("/redirect", (req, res, next)=>{
+  console.log(req);
+});
+serverApp.get("/redirect", (req, res, next)=>{
+  console.log(req);
+});
 
 serverApp.post("/api-get",   
   // isAuthenticated,
@@ -193,7 +199,7 @@ serverApp.post("/api-get",
 });
 
 serverApp.get("/api-redirect", 
-  isAuthenticated,
+  // isAuthenticated,
   async function (req, res, next) {
       const uri = req.session.apiUri;
       let param = {};
@@ -209,7 +215,7 @@ serverApp.get("/api-redirect",
 })
 
 serverApp.get("/post-redirect", 
-  isAuthenticated,
+  // isAuthenticated,
   async function (req, res, next) {
     const uri = req.session.apiUri;
     let param = {};
@@ -225,17 +231,17 @@ serverApp.get("/post-redirect",
   }
 )
 
-serverApp.post("/api-update", authProvider.acquireToken({
-  scopes: [],
-  redirectUri: redirectUri,
-  successRedirect: '/post-redirect'
-}));
+// serverApp.post("/api-update", authProvider.acquireToken({
+//   scopes: [],
+//   redirectUri: redirectUri,
+//   successRedirect: '/post-redirect'
+// }));
 
-serverApp.post("/api-post", authProvider.acquireToken({
-  scopes: ['.default'],
-  redirectUri: redirectUri,
-  successRedirect: '/post-redirect'
-}));
+// serverApp.post("/api-post", authProvider.acquireToken({
+//   scopes: ['.default'],
+//   redirectUri: redirectUri,
+//   successRedirect: '/post-redirect'
+// }));
 
 // serverApp.post("/getGroupList", authProvider.acquireToken({
 //     scopes: ['.default'],
@@ -302,68 +308,6 @@ serverApp.post("/getGroupList",  async function (req, res, next) {
 });
   
 
-serverApp.get("/group-redirect", 
-  isAuthenticated,
-  async function (req, res, next) {
-    // return;
-    try {
-        const oneDrive = await getFetch(endPoint + "/me/drive/root", req.session.accessToken);
-        const sharePointIds = await getFetch(endPoint + "/me/drive/SharePointIds", req.session.accessToken);
-        // const publicTeam = await getFetch(endPoint + "/groups?$filter=groupTypes/any(c:c+eq+'Unified')", req.session.accessToken);
-        const graphResponse = await getFetch(endPoint + "/me/joinedTeams", req.session.accessToken);
-        const sites = await getFetch(endPoint + "/sites/root", req.session.accessToken);
-        const sitesSharePoint = await getFetch(endPoint + "/sites/root/SharePointIds", req.session.accessToken);
-
-        // const public = publicTeam.value;
-        const teams = graphResponse.value;
-        oneDrive.sharePoint = sharePointIds;
-        sites.sharePoint = sitesSharePoint;
-        const resultObj = {
-          oneDrive : {
-            teams: oneDrive,
-          },
-          joinedTeams : {
-            teams : teams,
-            // teams : public,
-            items : {},
-          },
-          sites : {
-            teams : sites,
-          },
-        }
-
-        if (teams && teams.length) {
-        // if (public && public.length) {
-          // const options = {
-          //   responseType: 'arraybuffer',
-          //   headers: {
-          //     Authorization: `Bearer ${req.session.accessToken}`,
-          //     ConsistencyLevel: 'eventual',
-          //     withCredentials:true,
-          //   },
-          // };
-          for (let team of teams) {
-          // for (let team of public) {
-            const item = await getFetch(endPoint + "/groups/"+team.id+"/drive/items/root/children", req.session.accessToken);
-            const sharePoint = await getFetch(endPoint + "/groups/"+team.id+"/drive/SharePointIds", req.session.accessToken);
-            // const image = await axios.get(endPoint + "/groups/" + team.id + "/photo/$value", options);
-            // if (image && image.data) {
-            //   team.image = image.data;
-            // }
-            if (sharePoint) {
-              team.sharePoint = sharePoint;
-            }
-            if (item && item.value) {
-              resultObj.joinedTeams.items[team.id] = item.value;
-            }
-          }
-        }
-        res.json(resultObj);
-    } catch (error) {
-        next(error);
-    } 
-  }
-)
 
 function isAccessTokens(req, res, next) {
   if (!req.session.accessToken) {
@@ -593,146 +537,9 @@ serverApp.post('/api/check-name',
           console.log(error);
           res.json(error);
         }
-        // if (error.response) {
-        //   console.log(error.response.data.error); 
-        // }
-        // else {
-        //   console.log(error.AxiosError);
-        // }
-        // res.json({hasName: false});
-        // resultObj.success = 'F';
-        // resultObj.message = '선택하신 파일 정보 삭제중 오류가 발생하였습니다.\n' + error.response.data.error.message;
-        // return res.json(resultObj);
       }
 })
 
-// serverApp.post('/api/upload', upload.array('file'),
-//   isAuthenticated,
-//   isAccessTokens,
-//   async (req, res, next)=>{
-//     const startTime = new Date();
-//     const folderParam = {
-//       name: '',
-//       folder: { },
-//       '@microsoft.graph.conflictBehavior': 'rename'
-//     }
-//     const files = req.files;
-//     let {siteId, path, folder} = req.body;
-
-//     if (siteId && path) {
-//       const options = {
-//         headers: {
-//           Authorization: `Bearer ${req.session.accessToken}`,
-//         },
-//       };
-
-//         if (folder) {
-//           if (!Array.isArray(folder)) {
-//             folder = [folder];
-//           }
-//           let beforeUri = '';
-//           let beforeItemId = '';
-//           for (let item of folder) {
-//             const fileInfo = JSON.parse(item);
-//             const param = {...folderParam};
-//             param.name = fileInfo.name;
-//             let folderPath = '';
-//             if (fileInfo.path) {
-//               folderPath = fileInfo.path; 
-//               if (!path.includes(':')) {
-//                 folderPath = ":" + folderPath;
-//               }
-//             }
-//             let uri = endPoint + "/sites/"+ siteId + path + folderPath;
-//             try {
-              
-//               let itemId = '';
-//               if (beforeUri === uri) {
-//                 itemId = beforeItemId;
-//               }
-//               else {
-//                 const sitesInfo = await axios.get(uri, options);
-//                 itemId = sitesInfo.data.id;
-//                 beforeItemId = itemId;
-//                 beforeUri = uri;
-//               }
-//               await axios.post(endPoint + "/sites/"+ siteId +"/drive/items/" + itemId +"/children", param, options);
-//             }
-//             catch(error) {
-//               return res.json({success:'F', message: '요청하신 파일 업로드 중 오류가 발생하였습니다.<br>' + getErrorMessage(error)});
-//             }
-//           }
-//         }
-
-//         if (files && files.length > 0) {
-//           const promiseArray = [];
-//           let beforeUri = '';
-//           let beforeItemId = '';
-//           for (let file of files) {
-//             // const fileName = file.originalname.substring(0, file.originalname.lastIndexOf('.'));
-//             const fileName = file.originalname;
-//             let filePath = req.body[ fileName + "_path"];
-//             file.originalname = Buffer.from(file.originalname, 'ascii').toString('utf8');
-
-//             let formatPath = '';
-//             if (filePath) {
-//               if (Array.isArray(filePath) && filePath.length > 0) {
-//                 formatPath = filePath[0];
-//                 if (filePath.length > 1) {
-//                   req.body[ fileName + "_path"] = filePath.splice(1); 
-//                 }
-//               }
-//               else if (filePath.trim()){
-//                 formatPath = filePath;
-//                 }
-                
-//                 if (!path.includes(":")) {
-//                   formatPath = ":" + formatPath;
-//                 }
-//               }
-//               let itemId = '';
-//               const uri = endPoint + "/sites/"+ siteId + path + formatPath;
-              
-//               if (beforeUri === uri) {
-//                 itemId = beforeItemId;
-//               }
-//               else {
-//                 const sitesInfo = await axios.get(uri, options);
-//                 itemId = sitesInfo.data.id;
-//                 beforeUri = uri;
-//                 beforeItemId = itemId; 
-//               }
-//               const fileOptions = { headers: {
-//                 Authorization: `Bearer ${req.session.accessToken}`,
-//                 "Content-Type" : file.mimeType
-//               }}
-//               // await axios.put(endPoint + "/sites/"+ siteId +"/drive/items/"+itemId+':/'+file.originalname+':/content', file.buffer, fileOptions);
-//               promiseArray.push(axios.put(endPoint + "/sites/"+ siteId +"/drive/items/"+itemId+':/'+file.originalname+':/content', file.buffer, fileOptions));
-//           }
-
-//           if (promiseArray.length > 0) {
-//             try {
-//               const result = await Promise.all(promiseArray);
-//               console.log(result.length);
-
-//             }
-//             catch(error){
-//               return res.json({success:'F', message: '요청하신 파일 업로드 중 오류가 발생하였습니다.<br>' + getErrorMessage(error)});
-//             }
-//           }
-//         }
-//         const endTime = new Date();
-//         let betweenTime = endTime - startTime;
-//         if (betweenTime > 60000) {
-//           betweenTime = (betweenTime/1000/60) + ' 분';
-//         }
-//         else {
-//           betweenTime = (betweenTime/1000) + ' 초';       
-//         }
-//         console.log('시작 시간 :', startTime.toLocaleString(), ', 종료 시간 :', endTime.toLocaleString(), ', 소요 시간 :', betweenTime);
-//         res.json({success:'S', message: '요청하신 파일 업로드가 정상적으로 처리 되었습니다.'});
-//       }
-// });
 
 serverApp.post('/api/upload', upload.array('file'),
   // isAuthenticated,
@@ -752,8 +559,7 @@ serverApp.post('/api/upload', upload.array('file'),
           if (!Array.isArray(folder)) {
             folder = [folder];
           }
-          let beforeUri = '';
-          let beforeItemId = '';
+
           for (let item of folder) {
             const fileInfo = JSON.parse(item);
 
@@ -772,17 +578,6 @@ serverApp.post('/api/upload', upload.array('file'),
             }
             let uri = endPoint + "/sites/"+ siteId + path + folderPath;
             try {
-              
-              // let itemId = '';
-              // if (beforeUri === uri) {
-              //   itemId = beforeItemId;
-              // }
-              // else {
-              //   const sitesInfo = await axios.get(uri, options);
-              //   itemId = sitesInfo.data.id;
-              //   beforeItemId = itemId;
-              //   beforeUri = uri;
-              // }
               const result = await new Promise (async (resolve, reject)=>{
                 try {
                   const sitesInfo = await axios.get(uri, options);
@@ -814,8 +609,6 @@ serverApp.post('/api/upload', upload.array('file'),
               }).catch((error)=>{
                 console.log(error);
               })
-              console.log(result.createdDateTime);
-              // console.log(result);
             }
             catch(error) {
               return res.json({success:'F', message: '요청하신 파일 업로드 중 오류가 발생하였습니다.<br>' + getErrorMessage(error)});
@@ -842,6 +635,41 @@ serverApp.post('/api/upload', upload.array('file'),
             const fileName = file.originalname;
             let filePath = req.body[ fileName + "_path"];
             file.originalname = Buffer.from(file.originalname, 'ascii').toString('utf8');
+            let originName = file.originalname;
+            if (originName.lastIndexOf('.') >= 0) {
+              const possibleExt = await getPossibleExt();
+              const {supported_file_ext, protected_file_ext} = possibleExt;
+              const ext = originName.substring(originName.lastIndexOf('.'), originName.length);
+              if (supported_file_ext && protected_file_ext) {
+                const supportedArr = supported_file_ext.split(';');
+                if (!supportedArr.includes(ext)) {
+                    return res.json({success:'F', message: '파일명 : '+originName+'<br>해당 파일은 업로드 불가 파일입니다. 다시 시도해주세요.'});
+                }
+                const fileData = Buffer.from(file.buffer).toString('base64');
+                const param = {
+                  apiKey: process.env.GATE_WAY_KEY,
+                  email: req.session.account.idTokenClaims.email,
+                  dispFileName: originName,
+                  aipGuid: "878173ae-cc36-4881-af57-604af868314c",
+                  comment: "",
+                  fileData: fileData
+                }
+                
+                try {
+                  // const result = await axios.post('https://115.91.94.42/api/v1/stream/set-label', param);
+                  const result = await axios.post('http://192.168.20.99:5050/api/v1/stream/set-label', param);
+                  if (result) {
+                    if (result.data.statusCode === 200) {
+                      let bufferValue = Buffer.from(result.data.result.fileData, "base64");
+                      file = bufferValue;
+                    }
+                  }
+                }
+                catch(error) {
+                  console.log(error);
+                }
+              }
+            }
 
             let formatPath = '';
             if (filePath) {
@@ -853,30 +681,31 @@ serverApp.post('/api/upload', upload.array('file'),
               }
               else if (filePath.trim()){
                 formatPath = filePath;
-                }
-                
-                if (!path.includes(":")) {
-                  formatPath = ":" + formatPath;
-                }
               }
-              let itemId = '';
-              const uri = endPoint + "/sites/"+ siteId + path + formatPath;
               
-              if (beforeUri === uri) {
-                itemId = beforeItemId;
+              if (!path.includes(":")) {
+                formatPath = ":" + formatPath;
               }
-              else {
-                const sitesInfo = await axios.get(uri, options);
-                itemId = sitesInfo.data.id;
-                beforeUri = uri;
-                beforeItemId = itemId; 
-              }
-              const fileOptions = { headers: {
-                Authorization: `Bearer ${req.session.accessToken}`,
-                "Content-Type" : file.mimeType
-              }}
-              // await axios.put(endPoint + "/sites/"+ siteId +"/drive/items/"+itemId+':/'+file.originalname+':/content', file.buffer, fileOptions);
-              promiseArray.push(axios.put(endPoint + "/sites/"+ siteId +"/drive/items/"+itemId+':/'+file.originalname+':/content', file.buffer, fileOptions));
+            }
+
+            let itemId = '';
+            const uri = endPoint + "/sites/"+ siteId + path + formatPath;
+            
+            if (beforeUri === uri) {
+              itemId = beforeItemId;
+            }
+            else {
+              const sitesInfo = await axios.get(uri, options);
+              itemId = sitesInfo.data.id;
+              beforeUri = uri;
+              beforeItemId = itemId; 
+            }
+            const fileOptions = { headers: {
+              Authorization: `Bearer ${req.session.accessToken}`,
+              "Content-Type" : file.mimeType
+            }}
+            // await axios.put(endPoint + "/sites/"+ siteId +"/drive/items/"+itemId+':/'+file.originalname+':/content', file.buffer, fileOptions);
+            promiseArray.push(axios.put(endPoint + "/sites/"+ siteId +"/drive/items/"+itemId+':/'+originName+':/content', file, fileOptions));
           }
         }
         if (promiseArray.length > 0) {
@@ -905,6 +734,7 @@ serverApp.post('/api/download',
   // isAuthenticated,
   // isAccessTokens,
   async (req, res, next)=>{
+    let startTime = new Date();
     if (req.body) {
       const {siteId, path, fileIds, zipName} = req.body;
       if (siteId && path && fileIds) {
@@ -919,7 +749,7 @@ serverApp.post('/api/download',
           if (sitesInfo && sitesInfo.data) {
             const data = sitesInfo.data;
             if (data.folder) {
-              const folderObj = await getFolderItems(endPoint + "/sites/"+ siteId + "/drive/items/", arr, options);
+              const folderObj = await getFolderItems(endPoint + "/sites/"+ siteId + "/drive/items/", arr, options, req.session);
               const zip = new JSZIP();
               if (folderObj) {
                 createZipFile(folderObj, zip);
@@ -937,6 +767,15 @@ serverApp.post('/api/download',
                     level: 9
                   },
                 }).then((resZip)=>{
+                  const endTime = new Date();
+                  let betweenTime = endTime - startTime;
+                  if (betweenTime > 60000) {
+                    betweenTime = (betweenTime/1000/60) + ' 분';
+                  }
+                  else {
+                    betweenTime = (betweenTime/1000) + ' 초';       
+                  }
+                  console.log('시작 시간 :', startTime.toLocaleString(), ', 종료 시간 :', endTime.toLocaleString(), ', 소요 시간 :', betweenTime);
                   return res.json({success: 'S', data: resZip, name: data.name + '_' + year + '-' + month + '-' + date + '.zip'});
                 })
                 .catch((error)=>{
@@ -952,7 +791,41 @@ serverApp.post('/api/download',
               },});
               if (response.data) {
                 const file = response.data;
-                return res.json({success: 'S', data: file, type: data.file.mimeType, name: data.name});
+                let decodeFile = null;
+                try {
+                  const param = {
+                    apiKey: process.env.GATE_WAY_KEY,
+                    email : req.session.account.idTokenClaims.email,
+                    dispFileName: data.name,
+                    comment: "",
+                    fileData: Buffer.from(file).toString("base64")
+                  }
+                  const result = await axios.post('http://192.168.20.99:5050/api/v1/stream/delete-label', param);
+                  if (result && result.data.statusCode === 200) {
+                    var binaryString = atob(result.data.result.fileData);
+                    var bytes = new Uint8Array(binaryString.length);
+                    for (var i = 0; i < binaryString.length; i++) {
+                        bytes[i] = binaryString.charCodeAt(i);
+                    }
+                    decodeFile = bytes.buffer;
+                  }
+                  else {
+                    return res.json({message: '레이블 해제 중 오류가 발생하였습니다.<br>' + result.data.message, success: 'F'});
+                  }
+                }
+                catch(error) {
+                  return res.json({message: '레이블 해제 중 오류가 발생하였습니다.<br>' + JSON.stringify(error.message), success: 'F'});
+                }
+                const endTime = new Date();
+                let betweenTime = endTime - startTime;
+                if (betweenTime > 60000) {
+                  betweenTime = (betweenTime/1000/60) + ' 분';
+                }
+                else {
+                  betweenTime = (betweenTime/1000) + ' 초';       
+                }
+                console.log('시작 시간 :', startTime.toLocaleString(), ', 종료 시간 :', endTime.toLocaleString(), ', 소요 시간 :', betweenTime);
+                return res.json({success: 'S', data: decodeFile, type: data.file.mimeType, name: data.name});
               }
               else {
                 return res.json({message:'파일 다운로드에 실패하였습니다.', success:'F'})
@@ -964,7 +837,7 @@ serverApp.post('/api/download',
             try {
               const url = endPoint + "/sites/"+ siteId + "/drive/items/";
               const zip = new JSZIP();
-              const downObj = await getFolderItems(url, arr, options);
+              const downObj = await getFolderItems(url, arr, options, req.session);
               if (downObj) {
                 createZipFile(downObj, zip);
                 const now = new Date();
@@ -981,6 +854,15 @@ serverApp.post('/api/download',
                     level: 9
                   },
                 }).then((resZip)=>{
+                  const endTime = new Date();
+                  let betweenTime = endTime - startTime;
+                  if (betweenTime > 60000) {
+                    betweenTime = (betweenTime/1000/60) + ' 분';
+                  }
+                  else {
+                    betweenTime = (betweenTime/1000) + ' 초';       
+                  }
+                  console.log('시작 시간 :', startTime.toLocaleString(), ', 종료 시간 :', endTime.toLocaleString(), ', 소요 시간 :', betweenTime);
                   return res.json({success: 'S', data: resZip, name: zipName + '_' + year + '-' + month + '-' + date + '.zip'});
                 })
                 .catch((error)=>{
@@ -1003,6 +885,130 @@ serverApp.post('/api/download',
   }
 );
 
+serverApp.post('/api/folderMove', async (req, res, next)=>{
+  if (req.body) {
+    const {id, name, siteId, driveId, text, moveSiteId, movePath} = req.body;
+    const resultObj = {message:'폴더 이동에 실패 하였습니다.', success: 'F'};
+    if (name && isNaN(name)) {
+      const nameArray = JSON.parse(name);
+      const options = {
+        headers: {
+          Authorization: `Bearer ${req.session.accessToken}`,
+        },
+      };
+
+      if (nameArray && nameArray.length > 0) {
+        for (let moveItem of nameArray) {
+          if (moveItem) {
+            
+            try {
+              const copyFolderPath = `${endPoint}/sites/${siteId}/drive/items/${moveItem.id}`;
+              const result = await axios.get(copyFolderPath, options);
+              if (result && result.data) {
+                const data = result.data;
+                const moveUri = `${endPoint}/sites/${moveSiteId}/${movePath}`;
+                const moveFolderResult = await findSubFolder(data, moveUri, moveSiteId, options);
+                console.log('moveFolderResult : ',moveFolderResult);
+                if (!moveFolderResult) {
+                  resultObj.message ='폴더 이동 중 오류가 발생하였습니다.';
+                }
+                else {
+                  await axios.delete(endPoint + "/sites/"+ siteId + "/drive/items/" + moveItem.id, options);
+                  resultObj.message ='폴더 이동 되었습니다.';
+                  resultObj.success = 'S';
+                }
+              }
+            }
+            catch (error) {
+              console.log(error.message);
+              console.log(error.name);
+              console.log(error.errors);
+              resultObj.message = error.errors;
+              // resultObj.failItems.push(moveItem);
+            }
+          }
+        }
+      }
+    }
+    return res.json(resultObj);
+  }
+})
+
+async function findSubFolder(data, movePath, moveSiteId, options) {
+    let resultType = true;
+    try {
+      const moveItem = await axios.get(movePath, options);
+
+      if (moveItem.data && moveItem.data.id) {
+        const param = {
+          "name": data.name,
+          "folder": {},
+          "@microsoft.graph.conflictBehavior": "rename"
+        }
+
+        const makeFolderData = await axios.post(`${endPoint}/sites/${moveSiteId}/drive/items/${moveItem.data.id}/children`, param, options);
+        if (makeFolderData && makeFolderData.data) {
+            const makeFolderPath = `${endPoint}/sites/${moveSiteId}/${makeFolderData.data.parentReference.path}/${data.name}`;
+            
+            if (data.folder.childCount) {
+              const siteId = data.parentReference.siteId;
+              const childrenData = await axios.get(`${endPoint}/sites/${siteId}/drive/items/${data.id}/children`, options);
+              if (childrenData && childrenData.data && childrenData.data.value) {
+                const childrenValues = childrenData.data.value;
+                if (childrenValues.length > 0) {
+                  for (let ii = 0; ii < childrenValues.length; ii++) {
+                      const children = childrenValues[ii];
+                      if (children && children.folder) {
+                          const result = await findSubFolder(children, makeFolderPath, moveSiteId, options);
+                          if (!result) {
+                            resultType = result;
+                          }
+                      }
+                      else {
+                          const dataUrl = children['@microsoft.graph.downloadUrl'];
+                          const response = await axios.get(dataUrl, {responseType: 'arraybuffer', headers: {
+                            withCredentials:true,
+                          },});
+                          if (response.data) {
+                            const file = response.data;
+                            const uploadResult = await axios.put(`${endPoint}/sites/${moveSiteId}/drive/items/${makeFolderData.data.id}:/${children.name}:/content`, file.buffer, options);
+                            if (!uploadResult) {
+                              resultType = false;
+                            }
+                          }
+                          else {
+                            resultType = false;
+                          }
+                      }
+                  }
+                }
+                else {
+                  resultType = false;
+                }
+              }
+              else {
+                resultType = false;
+              }
+            }
+            else {
+              resultType = false;
+            }
+        }
+        else {
+          resultType = false;
+        }
+    }
+    else {
+      resultType = false;
+    }
+    return resultType;
+  }
+  catch(error) {
+    console.log(error);
+    return false;
+  }
+}
+
 function createZipFile(obj, zip) {
   
   if (obj.files.length > 0) {
@@ -1021,7 +1027,7 @@ function createZipFile(obj, zip) {
   }
 }
 
-async function getFolderItems(url, array, options) {
+async function getFolderItems(url, array, options, session) {
   const files = [];
   // let subFolder = [];
   let folder = [];
@@ -1039,7 +1045,7 @@ async function getFolderItems(url, array, options) {
             for (let children of itemsData.data.value) {
               idArr.push(children.id);
             }
-            let result = await getFolderItems(url, idArr, options);
+            let result = await getFolderItems(url, idArr, options, session);
             // subFolder.push(result);
             folderObj.subFolder = result;
           }
@@ -1051,8 +1057,35 @@ async function getFolderItems(url, array, options) {
         const response = await axios.get(dataUrl, {responseType: 'arraybuffer', headers: {
           withCredentials:true,
         },});
+        //암호화 해제
+        let decodeFile;
+        try {
+          const param = {
+            apiKey: process.env.GATE_WAY_KEY,
+            email : session.account.idTokenClaims.email,
+            dispFileName: data.name,
+            comment: "",
+            fileData: Buffer.from(response.data).toString("base64")
+          }
+          const result = await axios.post('http://192.168.20.99:5050/api/v1/stream/delete-label', param);
+          if (result && result.data.statusCode === 200) {
+            var binaryString = atob(result.data.result.fileData);
+            var bytes = new Uint8Array(binaryString.length);
+            for (var i = 0; i < binaryString.length; i++) {
+                bytes[i] = binaryString.charCodeAt(i);
+            }
+            decodeFile = bytes.buffer;
+          }
+          else {
+            return res.json({message: '레이블 해제 중 오류가 발생하였습니다.<br>' + result.data.message, success: 'F'});
+          }
+        }
+        catch(error) {
+          return res.json({message: '레이블 해제 중 오류가 발생하였습니다.<br>' + JSON.stringify(error.message), success: 'F'});
+        }
 
-        files.push({name : data.name, data : response.data, type: data.file.mimeType});
+        files.push({name : data.name, data : decodeFile, type: data.file.mimeType});
+        // files.push({name : data.name, data : response.data, type: data.file.mimeType});
       }
     }
   }
@@ -1065,6 +1098,21 @@ async function getFolderItems(url, array, options) {
   return resultObj;
 }
 
+
+serverApp.post('/api/getPossibleExtList', async (req, res, next)=>{
+  if (req.body) {
+    try {
+      const result = await getPossibleExt();
+      return res.json(result);
+    }
+    catch(error) {
+      console.log(error);
+      res.status(500);
+      res.send(error);
+    }
+  }
+})
+
 serverApp.post('/api/delete', 
   // isAuthenticated,
   // isAccessTokens,
@@ -1264,74 +1312,6 @@ serverApp.post('/api/loading',
 });
 
 
-serverApp.post('/api/folder-count',
-  // isAuthenticated,
-  // isAccessTokens,
-  async (req, res, next)=>{
-    if (req.body) {
-      const {id, siteId, originSiteId, originId, name, totalCount} = req.body;
-      const options = { headers: {
-        Authorization: `Bearer ${req.session.accessToken}`,
-      }}
-      let totCount = 0;
-      let successCount = 0;
-      if (id, siteId) {
-        try {
-          if (!totalCount) {
-            const originResult = await axios.get(endPoint + "/sites/"+ originSiteId +"/drive/items/"+originId, options);
-            if (originResult && originResult.data) {
-              totCount = await getFolderItemsCount(originSiteId, originResult.data.id, options, 0);
-              console.log('totCount', totCount);
-            }
-          }
-          else {
-            totCount = totalCount;
-          }
-          const result = await axios.get(endPoint + "/sites/"+ siteId +"/drive/items/"+id + "/children", options);
-          if (result && result.data && result.data.value) {
-            const value = result.data.value;
-            const idx = value.findIndex(obj=> obj.name === name);
-            successCount = await getFolderItemsCount(siteId, value[idx].id, options, 0);
-            console.log('successCount', totCount);
-          }
-          return res.json({totalCount: totCount, copyCount: successCount});
-          // const result = await axios.get(`${url}`);
-        }
-        catch (error) {
-          console.log(error.message);
-          console.log(error.name);
-          console.log(error.errors);
-          return res.json(error);
-        }
-      }
-  }
-});
-
-async function getFolderItemsCount(siteId, id, options, count) {
-  try {
-    const result = await axios.get(endPoint + "/sites/"+ siteId +"/drive/items/"+id +"/children", options);
-    // console.log("실행 URL :", endPoint + "/sites/"+ siteId +"/drive/items/"+id +"/children");
-  
-    if (result.data && result.data.value) {
-      const value = result.data.value;
-      console.log('value.length', value.length);
-      count += value.length;
-      for (let ii = 0; ii < value.length; ii++) {
-        if (value[ii].folder && value[ii].folder.childCount) {
-          count += await getFolderItemsCount(siteId, value[ii].id, options, 0);
-        }
-      }
-    }
-  }
-  catch(error) {
-    console.log(error.message);
-    console.log(error.name);
-    console.log(error.errors);
-  }
-  // console.log('개수', count);
-  return count;
-}
-
 
 serverApp.post('/api/add-tab', 
 // isAuthenticated,
@@ -1389,4 +1369,39 @@ async (req, res, next)=>{
     }
     return res.json(resultObj);
   }
-});
+});
+
+// // 데이터베이스 연결
+// pool.connect((err) => {
+//   // 연결이 안될 경우 에러 내용 콘솔에 출력
+//   if (err) {
+//       console.error('Error connecting to database:', err);
+//       return;
+//   }
+//   // 연결에 성공할 경우 연결 성공 메시지 콘솔에 출력
+//   console.log('Connected to database');
+// });
+
+async function getPossibleExt() {
+  const sqlQuery = 
+    `SELECT 
+        A.ConfigValue AS supported_file_ext, 
+        B.ConfigValue AS protected_file_ext 
+      FROM (SELECT * FROM TB_AIP_CONFIG WHERE ConfigKey = 'SupportedFileExt') A,  
+           (SELECT * FROM TB_AIP_CONFIG WHERE ConfigKey = 'ProtectedFileExt') B`;
+    try {
+      const query = await pool;
+      const result = await query.request().query(sqlQuery);
+      if (result) {
+        return result.recordset[0];
+      }
+    }
+    catch(error) {
+      console.log(error);
+    }
+}
+
+
+server.listen(SERVER_PORT, function () {
+  console.log(`\n${serverApp.name} listening to ${SERVER_PORT}`);
+}); 

+ 2 - 1
src/auth/AuthProvider.js

@@ -65,6 +65,7 @@ class AuthProvider {
             }
 
             const msalInstance = this.getMsalInstance(this.msalConfig);
+            console.log(msalInstance);
             // trigger the first leg of auth code flow
             return this.redirectToAuthCodeUrl(
                 authCodeUrlRequestParams,
@@ -221,7 +222,7 @@ class AuthProvider {
             };
             
             try {
-                console.log('==============================================리다이렉트================================================================')
+                console.log(req.session);
                 const authCodeUrlResponse = await msalInstance.getAuthCodeUrl(req.session.authCodeUrlRequest);
 
                 res.redirect(authCodeUrlResponse);

+ 30 - 0
src/config/config.js

@@ -0,0 +1,30 @@
+const dotenv  = require('dotenv');
+
+dotenv.config("'./env/.env.local'");
+
+module.exports = { 
+    config : {
+        port: process.env.PORT,
+        dbconfig: {
+            server: process.env.DB_DEV_SERVER,
+            port: parseInt(process.env.DB_DEV_PORT),
+            pool: {
+                max: 5,
+                min: 1,
+                idleTimeoutMillis: 30000,
+            },
+            options: {
+                encrypt: false,
+                datebase: process.env.DB_DEV_DATEBASE,
+                trustServerCertificate: true,
+            },
+            authentication: {
+                type: 'default',
+                options: {
+                    userName: process.env.DB_DEV_USERNAME,
+                    password: process.env.DB_DEV_PASSOWRD,
+                },
+            },
+        },
+    }
+};

+ 17 - 0
src/config/sql.js

@@ -0,0 +1,17 @@
+const sql = require('mssql');
+const { config } =  require('./config.js');
+
+const connPool = new sql.ConnectionPool(config.dbconfig)
+    .connect()
+    .then((pool)=>{
+        console.log("CONNECT TO MS SQL SERVER");
+        return pool;
+    })
+    .catch((error)=>{
+        console.log(error);
+    })
+
+module.exports = {
+    sql : sql,
+    pool : connPool
+}

+ 0 - 1
src/static/scripts/teamsapp.js

@@ -4,7 +4,6 @@
   // Call the initialize API first
   microsoftTeams.app.initialize().then(function () {
     microsoftTeams.app.getContext().then(function (context) {
-      console.log(context);
       if (context?.app?.host?.name) {
         updateHubState(context.app.host.name);
       }

+ 1 - 1
src/static/styles/custom.css

@@ -161,7 +161,7 @@ li {
   border-bottom: 1px solid #cfcece;
 }
 
-.file-title > div:hover{
+.file-title > div:hover:not(:nth-child(1)){
   cursor: pointer;
 }
 .file-title > div{

+ 118 - 167
src/views/hello.html

@@ -87,25 +87,17 @@
   });
 
   $(()=>{
-    // console.log();
-    // console.log();
-    // microsoftTeams.app.getContext().then((result)=>{
-    //   console.log(result);
-    // })
-    // .catch((error)=>{
-    //   console.log(error);
-    // })
-    // 
+
     microsoftTeams.app.initialize().then(() => {
-      microsoftTeams.appInitialization.notifySuccess();  
       getClientSideToken()
-            .then((clientSideToken) => {
-              // console.log(clientSideToken);
-                return getServerSideToken(clientSideToken);
-            })
-            .then((profile) => {
-              // console.log(profile);
-              getGroupList();
+      .then((clientSideToken) => {
+        // console.log(clientSideToken);
+        return getServerSideToken(clientSideToken);
+      })
+      .then((profile) => {
+        // console.log(profile);
+        microsoftTeams.appInitialization.notifySuccess();  
+        getGroupList();
                 // return useServerSideToken(profile);
             })
             .catch((error) => {
@@ -704,7 +696,7 @@
                                   </div>
                                   <div class="button-box">
                                       <div id="move-btn" onclick="moveUpdate('${text}')">여기로 ${text}</div>
-                                      <div onclick="modalClose('move')">취소</div>
+                                      <div id="close-btn" onclick="modalClose('move')">취소</div>
                                   </div>
                               </div>
                           </div>
@@ -722,6 +714,13 @@
     }
 
     function moveUpdate(text) {
+      $('#move-btn').attr('onclick', null);
+      $('#move-btn').css('opacity', '0.5');
+      $('#move-btn').hover(()=>{
+        $('#move-btn').css('cursor', 'default');
+        $('#move-btn').css('filter', 'brightness(1.0)');
+      });
+
       const alertTitle = '파일 '+ text;
       const selectedDrive = $('.modal-move-box .left-box div.on');
       const siteId = selectedDrive.attr('id');
@@ -746,13 +745,14 @@
         if (selectId === currentId && path === getDrivePath()) {
           return alertMessage(alertTitle, '대상 경로는 원본 개체와 같을 수 없습니다.');
         }
+
         callApi('get', '/sites/'+ currentId + getDrivePath(), (itemData)=>{
           if (itemData && itemData.id){
             const itemId = itemData.id;
             callApi('get', '/sites/'+ selectId + path, async (jsonData)=>{
               const $selectedItems = $('.file-content div.on');
               const name = [];
-              let str = `<div class="loading-box"><div>파일 생성중입니다...</div>`;
+              let str = `<div class="loading-box"><div class="loading-title">파일 생성중입니다...</div>`;
               for (let ii = 0; ii < $selectedItems.length; ii++) {
                 const selectCheck =  $selectedItems.eq(ii).find('input[type="checkbox"]');
                 const selectName = $selectedItems.eq(ii).find('.sp-name');
@@ -783,147 +783,65 @@
               }
 
               if (jsonData && jsonData.id) {
+
                 let uri = '/api/copy-item';
-                if (selectId === currentId) {
+                
+                if (selectId === currentId && text === '이동') {
                   uri = '/api/move-item';
                 }
                 else {
                   $('.modal-move-box .content').append(str);
                 }
-                let param = {
-                  siteId : currentId,
-                  itemId : itemId,
-                  id : jsonData.id,
-                  name : JSON.stringify(name),
-                  driveId : jsonData.parentReference.driveId,
-                  text : text,
-                }
-              
-                $.ajax({
-                  method : 'post',
-                  url : uri,
-                  data : param,
-                  global: false,
-                  success : (res) => {
-                    if (res){
-                      let message = res.message;
-                      let failIndexes = [];
-                      if (res.failItems && res.failItems.length) {
-                        res.failItems.forEach((failItem)=>{
-                          let idx = name.findIndex(obj=> obj.name === failItem.name);
-                          failIndexes.push(idx);
-                          $('.loading_image_' + idx).remove();
-                          $('.loading_image_' + idx +'_box').html('실패');
-                        });
-                      }
+                
+                  let param = {
+                    siteId : currentId,
+                    itemId : itemId,
+                    id : jsonData.id,
+                    name : JSON.stringify(name),
+                    driveId : jsonData.parentReference.driveId,
+                    moveSiteId : selectId,
+                    movePath : path,
+                    text : text,
+                  }
+                  
+                  $.ajax({
+                    method : 'post',
+                    url : uri,
+                    data : param,
+                    global: false,
+                    success : (res) => {
+                      if (res){
+                        let message = res.message;
+                        let failIndexes = [];
+                        if (res.failItems && res.failItems.length) {
+                          res.failItems.forEach((failItem)=>{
+                            let idx = name.findIndex(obj=> obj.name === failItem.name);
+                            failIndexes.push(idx);
+                            $('.loading_image_' + idx).remove();
+                            $('.loading_image_' + idx +'_box').html('실패');
+                          });
+                        }
 
-                      if (res.locations && res.locations.length > 0) {
-                        // function getLoadingState(arr, totalCount){
-                        //   Promise.all(res.locations.map((val, idx) => {
-                        //     if (failIndexes.includes(idx)) {
-                        //       return null;
-                        //     }
-                        //     if (name[idx].isFolder) {
-                        //       return $.ajax({ url: '/api/folder-count', global : false, method: 'post', 
-                        //                       data: { id: jsonData.id, siteId: selectId, name: name[idx].name, 
-                        //                             originSiteId: currentId, originId: name[idx].id, totalCount: totalCount }
-                        //                     });
-                        //     }
-                        //     return $.ajax({url: '/api/loading', global: false, method:'post', data: {url: val}});
-                        //   }))
-                        //   .then((values)=>{
-                        //     console.log(values);
-                        //     if (values) {
-                        //       const array = [];
-                        //       for (let idx in values) {
-                        //         const value = values[idx];
-                        //         if (value && value.percentageComplete) {
-                        //           if (value.percentageComplete !== 100) {
-                        //             array.push(res.locations[idx]);
-                        //           }
-                        //           else {
-                        //             $('.loading_image_' + idx).remove();
-                        //             $('.loading_image_' + idx +'_box').html('완료됨');
-                        //           }
-                        //           const percent = value.percentageComplete;
-                        //           $('.gauge_'+ idx).css('width', percent+'%');
-                        //           $('.gauge_'+ idx + '_value').html(percent);
-                        //         }
-                        //         else if(value && value.totalCount){
-                        //           console.log(value);
-                        //         }
-                        //       }
-                        //       if (array.length) {
-                        //         setTimeout(()=>{
-                        //           getLoadingState(array);
-                        //         }, 2000)
-                        //       }
-                        //       else {
-                        //         if (text === '이동') {
-                        //           const checkedArr = [];
-                        //           name.forEach((obj)=>{
-                        //             checkedArr.push(obj.id);
-                        //           });
-                        //           $.ajax({
-                        //             url: '/api/delete', 
-                        //             global: false, 
-                        //             method:'post', 
-                        //             data: {
-                        //               siteId : currentId,
-                        //               itemIds : JSON.stringify(checkedArr),
-                        //             },
-                        //             success: (res)=>{
-                        //               console.log();
-                        //               if (res && res.success === 'S') {
-                        //                 alertMessage(alertTitle, message);
-                        //                 const selected = $('section .panel-item.on');
-                        //                 selected.removeClass('on');
-                        //                 selected.click();
-                        //                 modalClose('move');
-                        //               }
-                        //             },
-                        //             error : (error)=>{
-                        //               console.log(error);
-                        //             }
-                        //           });
-                        //         }
-                        //         else {
-                        //           alertMessage(alertTitle, message);
-                        //           const selected = $('section .panel-item.on');
-                        //           selected.removeClass('on');
-                        //           selected.click();
-                        //           modalClose('move');
-                        //         }
-                        //       }
-                        //     }
-                        //   })
-                        //   .catch((error)=>{
-                        //     console.log(error);
-                        //   })
-                        // }
-                        // getLoadingState(res.locations);
-                        // jsonData.id, siteId: selectId, name: name[idx].name, 
-                        //                             originSiteId: currentId, originId: name[idx].id, totalCount: totalCount 
-                        for (let idx in res.locations) {
-                          if (!failIndexes.includes(idx)) {
-                              getFileState(jsonData.id, selectId, name[idx].name, currentId, name[idx].id, 0, 
-                              res.locations[idx], name[idx].isFolder, idx, alertTitle, message);
+                        if (res.locations && res.locations.length > 0) {
+                          for (let idx in res.locations) {
+                            if (!failIndexes.includes(idx)) {
+                                getFileState(currentId, name[idx].id, res.locations[idx], idx, alertTitle, message, text);
+                            }
                           }
                         }
+                        else {
+                          alertMessage(alertTitle, message);
+                          const selected = $('section .panel-item.on');
+                          selected.removeClass('on');
+                          selected.click();
+                          modalClose('move');
+                        }
                       }
-                      else {
-                        alertMessage(alertTitle, message);
-                        const selected = $('section .panel-item.on');
-                        selected.removeClass('on');
-                        selected.click();
-                        modalClose('move');
-                      }
+                    },
+                    error : (error) => {
+                      console.log(error);
                     }
-                  },
-                  error : (error) => {
-                    console.log(error);
-                  }
-                })
+                  })
               }
               else {
                 alertMessage(alertTitle, '선택된 그룹 정보를 찾을 수 없습니다.');
@@ -940,12 +858,25 @@
       }
     }
 
-    function getFileState(id, siteId, name, originSiteId, originId, totalCount, value, isFolder, idx, alertTitle, message) {
+    function getFileState(originSiteId, originId, value, idx, alertTitle, message, text) {
       const wss = new WebSocket('wss://localhost:53000/');
       wss.onopen = (event)=>{
         console.log('WebSocket Connection');
-        wss.send(JSON.stringify({id: id, siteId : siteId, name: name, originSiteId : originSiteId, 
-                                originId : originId, totalCount: totalCount, value : value, isFolder : isFolder}));
+        wss.send(JSON.stringify({ value : value }));
+        if (text === '이동') {
+          $('#close-btn').attr('onclick', null);
+          $('#close-btn').on('click', ()=>{
+            confirmMessage(alertTitle,'파일 이동을 취소 하시겠습니까? 취소 시 원본 디렉토리의 파일이 삭제 되지 않을 수 있습니다.', ()=>{
+              wss.close();
+              modalClose('confirm');
+              alertMessage(alertTitle, '파일 이동을 취소하였습니다.');
+              const selected = $('section .panel-item.on');
+              selected.removeClass('on');
+              selected.click();
+              modalClose('move');
+            });
+          });
+        }
       };
       
       wss.onclose = (event)=>{
@@ -960,20 +891,21 @@
           if (percent === '100') {
             $('.loading_image_' + idx).remove();
             $('.loading_image_' + idx +'_box').html('완료됨');
-            try {
-              const deleteData = await $.ajax({
-                url: '/api/delete', 
-                global: false, 
-                method:'post', 
-                data: {
-                  siteId : originSiteId,
-                  itemIds : JSON.stringify([originId]),
-                },});
-                console.log(deleteData);
-            }
-            catch(error) {
-              console.log(error);
-            }
+            if (text === '이동') {
+              try {
+                const deleteData = await $.ajax({
+                  url: '/api/delete', 
+                  global: false, 
+                  method:'post', 
+                  data: {
+                    siteId : originSiteId,
+                    itemIds : JSON.stringify([originId]),
+                  },});
+              }
+              catch(error) {
+                console.log(error);
+              }
+            } 
 
             if ($('.modal.move').length && $('img[src="/static/images/refresh.png"]').length === 0) {
               alertMessage(alertTitle, message);
@@ -1427,7 +1359,7 @@
           },
           error: (error) => {
             console.log(error);
-            alertMessage(alertTitle, error, null, 'red');
+            alertMessage(alertTitle, JSON.stringify(error), null, 'red');
           },
           
         });
@@ -1869,6 +1801,7 @@
         _selectedData.value.sort(function (a, b){
           return a[type] > b[type] ? first : a[type] === b[type] ? 0 : end;
         });
+        console.log(_selectedData.value);
       }
   }
   $('.tree.group input[type="checkbox"]').on('change', function(event){
@@ -2152,4 +2085,22 @@
     selectDrive.click();
   }
 
+  async function getFolderCount(siteId, driveId) {
+    const param = {
+      siteId : siteId,
+      driveId : driveId,
+    }
+    const resultObj = {success: 'F', obj: {}};
+    try {
+      const result = await $.ajax({ method : 'post', url : '/api/folderCount', data : param });
+      resultObj.success = 'S';
+      resultObj.obj = result;
+    }
+    catch(error) {
+      console.log(error);
+      resultObj.obj = error;
+    }
+
+    return resultObj;
+  }
 </script>

BIN
test - 복사본 (3).xlsx


Einige Dateien werden nicht angezeigt, da zu viele Dateien in diesem Diff geändert wurden.