junggilpark 1 рік тому
батько
коміт
8bdbd7a2ba
2 змінених файлів з 190 додано та 216 видалено
  1. 187 214
      src/app.js
  2. 3 2
      src/views/hello.html

+ 187 - 214
src/app.js

@@ -78,6 +78,10 @@ serverApp.use(session({
   }
 }));
 
+serverApp.use(async (req, res, next)=>{
+  POSSIBLE_EXT = await init();
+  next();
+})
 serverApp.set(express.json());
 serverApp.use(cookieParser());
 serverApp.use(express.urlencoded({ extended: false }));
@@ -140,7 +144,6 @@ serverApp.use(bodyParser.json());
 
 serverApp.get("/tab", 
   async function (req, res, next) {
-    POSSIBLE_EXT = await init();
     res.sendFile(globalPath.join(__dirname, "/views/hello.html"), 
     );
   }
@@ -213,13 +216,6 @@ serverApp.get("/post-redirect",
 
 serverApp.post("/getGroupList",  async function (req, res, next) {
   try {
-    // throw new Error('Error');
-      // 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 options = getOptions(req.session.accessToken);
       const uriArr = [
         axios.get(endPoint + "/me/drive/root", options),
@@ -253,13 +249,8 @@ serverApp.post("/getGroupList",  async function (req, res, next) {
 
       if (teams && teams.length) {
         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;
           }
@@ -451,6 +442,7 @@ async function uploadDrive(options, folder, siteId, path) {
   if (!Array.isArray(folder)) {
     folder = [folder];
   }
+  let promiseArray = [];
   for (let item of folder) {
     const fileInfo = JSON.parse(item);
 
@@ -468,6 +460,7 @@ async function uploadDrive(options, folder, siteId, path) {
       }
     }
     let uri = endPoint + "/sites/"+ siteId + path + folderPath;
+    promiseArray.push(axios.get(uri, options));
     const result = await new Promise (async (resolve, reject)=>{
         axios.get(uri, options).then((sitesInfo)=>{
           resolve(sitesInfo.data);
@@ -506,212 +499,189 @@ serverApp.post('/api/upload', upload.array('file'),
     const startTime = new Date();
     const files = req.files;
     let {siteId, path, folder, file_path} = req.body; 
-    if (siteId && path) {
-      const options = getOptions(req.session.accessToken);
-      if (folder){
-        const uploadDriveResult = await uploadDrive(options, folder, siteId, path);
-        if (uploadDriveResult.success === 'F') {
-          return res.json(uploadDriveResult);
+    try {
+    
+      if (siteId && path) {
+        const options = getOptions(req.session.accessToken);
+        if (folder){
+          const uploadDriveResult = await uploadDrive(options, folder, siteId, path);
+          if (uploadDriveResult.success === 'F') {
+            return res.json(uploadDriveResult);
+          }
         }
-      }
 
-      let fileWriteTime = new Date();
-      if (files && files.length > 0) {
-          const promiseArray = [];
-          const labelPromiseArray = [];
-          // const fileWriteArray = [];
-          const possibleExt = POSSIBLE_EXT;
-          const {supported_file_ext, protected_file_ext} = possibleExt;
-          let supportedArr = [];
-          // let protectedArr = [];
-          // let protectedMap = new Map();
-          if (supported_file_ext && protected_file_ext) {
-            supportedArr = supported_file_ext.split(';');
-            // protectedArr = protected_file_ext.split(';');
-            if (!supportedArr[supportedArr.length - 1]) {
-              supportedArr.splice(supportedArr.length - 1);
+        let fileWriteTime = new Date();
+        if (files && files.length > 0) {
+            const promiseArray = [];
+            const labelPromiseArray = [];
+            // const fileWriteArray = [];
+            const possibleExt = POSSIBLE_EXT;
+            const {supported_file_ext, protected_file_ext} = possibleExt;
+            let supportedArr = [];
+            if (supported_file_ext && protected_file_ext) {
+              supportedArr = supported_file_ext.split(';');
+              if (!supportedArr[supportedArr.length - 1]) {
+                supportedArr.splice(supportedArr.length - 1);
+              }
             }
-            // if (!protectedArr[protectedArr.length - 1]) {
-            //   protectedArr.splice(protectedArr.length - 1);
-            // }
-            // if (protectedArr.length > 0) {
-            //   for (let array of protectedArr) {
-            //     array = array.split('-');
-            //     if (array.length === 2) {
-            //       protectedMap.set(array[0], array[1]);
-            //     }
-            //   }
-            // }
-          }
-          let beforeUri = '';
-          let beforeItemId = '';
-          // const siteInfoArr = [];
-          for (let idx in files) {
-            const file = files[idx];
-            //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) {
-                let ext = globalPath.extname(originName);
-                if (supportedArr.length > 0 && !supportedArr.includes(ext)) {
-                    return res.json({success:'F', message: '파일명 : ' + originName 
-                                      +'<br>업로드 불가 파일이 포함되어 있습니다.<br>가능 확장자 :' 
-                                      + JSON.stringify(supportedArr)});
-                }
-
-                // const uuid = uuidv4();
-                // const realFileName = uuid + ext;
-                // fileWriteArray.push(new Promise((resolve, reject) => {
-                //   const data = fs.writeFileSync('Z:/Source/' + realFileName, file.buffer)
-                //   resolve({
-                //     data
-                //   })
-                // }));
+            let beforeUri = '';
+            let beforeItemId = '';
+            for (let idx in files) {
+              const file = files[idx];
+              file.originalname = Buffer.from(file.originalname, 'ascii').toString('utf8');
+              let originName = file.originalname;
+              if (originName) {
+                  let ext = globalPath.extname(originName);
+                  if (supportedArr.length > 0 && !supportedArr.includes(ext)) {
+                      return res.json({success:'F', message: '파일명 : ' + originName 
+                                        +'<br>업로드 불가 파일이 포함되어 있습니다.<br>가능 확장자 :' 
+                                        + JSON.stringify(supportedArr)});
+                  }
 
-                const base64Data = Buffer.from(file.buffer).toString('base64');
-                const param = {
-                  apiKey: gateWayKey,
-                  email: req.session.account.idTokenClaims.email,
-                  dispFileName: originName,
-                  aipGuid: "878173ae-cc36-4881-af57-604af868314c",
-                  // aipGuid: "0166b75f-6a93-47f3-8fd3-e1e7c59141ab",
-                  // comment: "set-protection",
-                  comment: "set-label",
-                  fileData: base64Data,
-                }
+                  // const uuid = uuidv4();
+                  // const realFileName = uuid + ext;
+                  // fileWriteArray.push(new Promise((resolve, reject) => {
+                  //   const data = fs.writeFileSync('Z:/Source/' + realFileName, file.buffer)
+                  //   resolve({
+                  //     data
+                  //   })
+                  // }));
+
+                  const base64Data = Buffer.from(file.buffer).toString('base64');
+                  const param = {
+                    apiKey: gateWayKey,
+                    email: req.session.account.idTokenClaims.email,
+                    dispFileName: originName,
+                    aipGuid: "878173ae-cc36-4881-af57-604af868314c",
+                    // aipGuid: "0166b75f-6a93-47f3-8fd3-e1e7c59141ab",
+                    // comment: "set-protection",
+                    comment: "set-label",
+                    fileData: base64Data,
+                  }
 
-                // labelPromiseArray.push(new Promise(async (resolve)=>{resolve(await axios.post(apiUrl + '/api/v1/stream/set-label', param))}));
-                labelPromiseArray.push(axios.post(apiUrl + '/api/v1/stream/set-label', param));
-                // labelPromiseArray.push(axios.post(apiUrl + '/api/v1/stream/set-protection', param));
-                
-                let formatPath = '';
-                
-                if (file_path[idx]) {
-                  // console.log(file_path[idx]);
-                  if (!path.includes(":")) { 
-                    formatPath = ":" + file_path[idx]; 
+                  // labelPromiseArray.push(new Promise(async (resolve)=>{resolve(await axios.post(apiUrl + '/api/v1/stream/set-label', param))}));
+                  labelPromiseArray.push(axios.post(apiUrl + '/api/v1/stream/set-label', param));
+                  // labelPromiseArray.push(axios.post(apiUrl + '/api/v1/stream/set-protection', param));
+                  
+                  let formatPath = '';
+                  
+                  if (file_path[idx]) {
+                    // console.log(file_path[idx]);
+                    if (!path.includes(":")) { 
+                      formatPath = ":" + file_path[idx]; 
+                    }
+                    else {
+                      formatPath = file_path[idx];
+                    }
                   }
-                  else {
-                    formatPath = file_path[idx];
+      
+                  let itemId = '';
+                  const uri = endPoint + "/sites/"+ siteId + path + formatPath;
+                  // siteInfoArr.push(axios.get(uri, options));
+                  if (beforeUri === uri) { 
+                    itemId = beforeItemId;
                   }
-                }
-    
-                let itemId = '';
-                const uri = endPoint + "/sites/"+ siteId + path + formatPath;
-                // siteInfoArr.push(axios.get(uri, options));
-                if (beforeUri === uri) { 
-                  itemId = beforeItemId;
-                }
-                else {
-                  try {
+                  else {
                     const sitesInfo = await axios.get(uri, options);
                     itemId = sitesInfo.data.id;
                     beforeUri = uri;
                     beforeItemId = itemId; 
                   }
-                  catch(error) {
-                    console.log(error);
-                    res.json({success:'F', message: '파일 업로드 작업 중 오류가 발생했습니다.<br>에러 : ' + JSON.stringify(error.message)});
+                  
+                  // if (protectedMap.size > 0 && protectedMap.get(ext)) {
+                  //   let name = originName.replace(ext, '');
+                  //   ext = protectedMap.get(ext);
+                  //   originName = name + ext;
+                  // }
+                  promiseArray.push(endPoint + "/sites/"+ siteId +"/drive/items/"+itemId+':/');
+              }
+            }
+
+                // const siteInfos = await Promise.all(siteInfoArr);
+                // siteInfos.forEach((obj)=>{
+                //   promiseArray.push(endPoint + "/sites/"+ siteId +"/drive/items/"+obj.data.id+':/');
+                // })
+                //file write 시 사용
+                //const writeArr = await Promise.all(fileWriteArray);
+
+                let writeTime = timeCheck(fileWriteTime, new Date());
+                console.log('파일 Write Time : '+ writeTime);
+                
+
+                const labelTime = new Date();
+                const labelResult = await Promise.all(labelPromiseArray);
+                // console.log(labelResult[0].data.result.fileData);
+                console.log('label time : ', timeCheck(labelTime, new Date()));
+                for (let idx in labelResult) {
+                  const obj = labelResult[idx];
+                  if (obj.data && !obj.data.result.errorCode && obj.data.result.fileData) {
+                    const data = Buffer.from(obj.data.result.fileData, 'base64');
+                    // promiseArray[idx] = new Promise(async (resolve)=> resolve(await axios.put(promiseArray[idx] + obj.data.result.dispFileName + ':/content', data, options)));
+                    promiseArray[idx] = axios.put(promiseArray[idx] + obj.data.result.dispFileName + ':/content', data, options);
+                    // promiseArray.push(axios.put(endPoint + "/sites/"+ siteId +"/drive/items/"+ siteInfos[idx].data.id + ':/' + obj.data.result.dispFileName + ':/content', data, options));
+                  }
+                  else {
+                    throw '파일명 : '+obj.data.result.dispFileName + '<br>에러 : ' + obj.data.result.errorMessage;
                   }
                 }
+                // labelResult.forEach((obj, idx)=>{
+                //   if (obj.data && !obj.data.result.errorCode && obj.data.result.fileData) {
+                //     const data = Buffer.from(obj.data.result.fileData, 'base64');
+                //     promiseArray[idx] = axios.put(promiseArray[idx] + obj.data.result.dispFileName + ':/content', data, options);
+                //     // promiseArray.push(axios.put(endPoint + "/sites/"+ siteId +"/drive/items/"+ siteInfos[idx].data.id + ':/' + obj.data.result.dispFileName + ':/content', data, options));
+                //   }
+                //   else {
+                //     throw '파일명 : '+obj.data.result.dispFileName + '<br>에러 : ' + obj.data.result.errorMessage;
+                //   }
+                // })
+                // const readArray = [];
+                // labelResult.forEach((obj)=>{
+                //   readArray.push(new Promise((resolve, reject)=>{
+                //       if (obj.data && !obj.data.result.errorCode) {
+                //         fs.readFile('Z:/Target/' + obj.data.result.outputFileName, (err, data)=>{
+                //           if (err) {
+                //             reject({err}); 
+                //           }
+                //           resolve({data});
+                //           //promiseArray[idx] = axios.put(promiseArray[idx], data, options);
+                //         });
+                //       }
+                //       else {
+                //         reject(obj.data.result.errorMessage);
+                //       }
+                //   }))
+                // });
+                // console.log('labelResult : ', labelResult);
+                // let readTime = new Date();
+                // const readResult = await Promise.all(readArray);
+
+                // console.log(readResult);
+                // console.log('File Read time : ', timeCheck(readTime, new Date()));
                 
-                // if (protectedMap.size > 0 && protectedMap.get(ext)) {
-                //   let name = originName.replace(ext, '');
-                //   ext = protectedMap.get(ext);
-                //   originName = name + ext;
-                // }
-                promiseArray.push(endPoint + "/sites/"+ siteId +"/drive/items/"+itemId+':/');
-            }
-          }
 
-          try {
-              // const siteInfos = await Promise.all(siteInfoArr);
-              // siteInfos.forEach((obj)=>{
-              //   promiseArray.push(endPoint + "/sites/"+ siteId +"/drive/items/"+obj.data.id+':/');
-              // })
-              //file write 시 사용
-              //const writeArr = await Promise.all(fileWriteArray);
-
-              let writeTime = timeCheck(fileWriteTime, new Date());
-              console.log('파일 Write Time : '+ writeTime);
-              
-
-              const labelTime = new Date();
-              const labelResult = await Promise.all(labelPromiseArray);
-              // console.log(labelResult[0].data.result.fileData);
-              console.log('label time : ', timeCheck(labelTime, new Date()));
-              for (let idx in labelResult) {
-                const obj = labelResult[idx];
-                if (obj.data && !obj.data.result.errorCode && obj.data.result.fileData) {
-                  const data = Buffer.from(obj.data.result.fileData, 'base64');
-                  // promiseArray[idx] = new Promise(async (resolve)=> resolve(await axios.put(promiseArray[idx] + obj.data.result.dispFileName + ':/content', data, options)));
-                  promiseArray[idx] = axios.put(promiseArray[idx] + obj.data.result.dispFileName + ':/content', data, options);
-                  // promiseArray.push(axios.put(endPoint + "/sites/"+ siteId +"/drive/items/"+ siteInfos[idx].data.id + ':/' + obj.data.result.dispFileName + ':/content', data, options));
-                }
-                else {
-                  throw '파일명 : '+obj.data.result.dispFileName + '<br>에러 : ' + obj.data.result.errorMessage;
-                }
-              }
-              // labelResult.forEach((obj, idx)=>{
-              //   if (obj.data && !obj.data.result.errorCode && obj.data.result.fileData) {
-              //     const data = Buffer.from(obj.data.result.fileData, 'base64');
-              //     promiseArray[idx] = axios.put(promiseArray[idx] + obj.data.result.dispFileName + ':/content', data, options);
-              //     // promiseArray.push(axios.put(endPoint + "/sites/"+ siteId +"/drive/items/"+ siteInfos[idx].data.id + ':/' + obj.data.result.dispFileName + ':/content', data, options));
-              //   }
-              //   else {
-              //     throw '파일명 : '+obj.data.result.dispFileName + '<br>에러 : ' + obj.data.result.errorMessage;
-              //   }
-              // })
-              // const readArray = [];
-              // labelResult.forEach((obj)=>{
-              //   readArray.push(new Promise((resolve, reject)=>{
-              //       if (obj.data && !obj.data.result.errorCode) {
-              //         fs.readFile('Z:/Target/' + obj.data.result.outputFileName, (err, data)=>{
-              //           if (err) {
-              //             reject({err}); 
-              //           }
-              //           resolve({data});
-              //           //promiseArray[idx] = axios.put(promiseArray[idx], data, options);
-              //         });
-              //       }
-              //       else {
-              //         reject(obj.data.result.errorMessage);
-              //       }
-              //   }))
-              // });
-              // console.log('labelResult : ', labelResult);
-              // let readTime = new Date();
-              // const readResult = await Promise.all(readArray);
-
-              // console.log(readResult);
-              // console.log('File Read time : ', timeCheck(readTime, new Date()));
-              
-
-              let uploadTime = new Date();
-              // promiseArray.forEach((obj, idx)=>{
-              //   // console.log(readResult[idx].data);
-              //   // console.log(obj[idx]);
-              //   promiseArray[idx] = axios.put(obj, readResult[idx].data, options); 
-              // });
-
-              const uploadResult = await Promise.all(promiseArray);
-              
-              console.log('File uploadTime : ', timeCheck(uploadTime, new Date()));
+                let uploadTime = new Date();
+                // promiseArray.forEach((obj, idx)=>{
+                //   // console.log(readResult[idx].data);
+                //   // console.log(obj[idx]);
+                //   promiseArray[idx] = axios.put(obj, readResult[idx].data, options); 
+                // });
 
+                const uploadResult = await Promise.all(promiseArray);
+                
+                console.log('File uploadTime : ', timeCheck(uploadTime, new Date()));
           }
-          catch(error){
-            return res.json({success:'F', message: '요청하신 파일 업로드 중 오류가 발생하였습니다.<br>' + getErrorMessage(error)});
-          }
-
-        }
-        const endTime = new Date();
-        let betweenTime = timeCheck(startTime, endTime);
-        console.log('시작 시간 :', startTime.toLocaleString(), ', 종료 시간 :', endTime.toLocaleString(), ', 소요 시간 :', betweenTime);
-        res.json({success:'S', message: '요청하신 파일 업로드가 정상적으로 처리 되었습니다.'});
+          const endTime = new Date();
+          let betweenTime = timeCheck(startTime, endTime);
+          console.log('시작 시간 :', startTime.toLocaleString(), ', 종료 시간 :', endTime.toLocaleString(), ', 소요 시간 :', betweenTime);
+          res.json({success:'S', message: '요청하신 파일 업로드가 정상적으로 처리 되었습니다.'});
+      }
+      else {
+        return res.json({success:'F', message: '업로드 요청 파라미터 정보를 확인해 주세요.'});
+      }
     }
-    else {
-      return res.json({success:'F', message: '업로드 요청 파라미터 정보를 확인해 주세요.'});
+    catch(error) {
+      console.log(error);
+      res.json({success:'F', message: '파일 업로드 작업 중 오류가 발생했습니다.<br>에러 : ' + JSON.stringify(error.message)});
     }
 });
 
@@ -775,11 +745,12 @@ serverApp.post('/api/download',
             let date = now.getDate();
             if (date < 10) date = "0" + date;
             zip.generateAsync({
-              type: 'base64',
+              type: 'nodebuffer',
             }).then((resZip)=>{
               const endTime = new Date();
+              const base64Data = Buffer.from(resZip).toString('base64');
               console.log('시작 시간 :', startTime.toLocaleString(), ', 종료 시간 :', endTime.toLocaleString(), ', 소요 시간 :', timeCheck(startTime, endTime));
-              return res.json({success: 'S', data: resZip, name: zipName + '_' + year + '-' + month + '-' + date + '.zip'});
+              return res.json({success: 'S', data: base64Data, name: zipName + '_' + year + '-' + month + '-' + date + '.zip'});
             })
             .catch((error)=>{
               console.log(error);
@@ -805,6 +776,7 @@ async function getFolderItems(url, array, options, session, zip) {
     return axios.get(url + obj.id, options);
   }))
   .then(async (siteInfos)=>{
+    let promiseArray = [];
       for (let site of siteInfos) {
         const data = site.data;
         if (data) {
@@ -813,14 +785,8 @@ async function getFolderItems(url, array, options, session, zip) {
             if (data.folder.childCount) {
               const itemsData = await axios.get(url + data.id + '/children', options);
               if (itemsData && itemsData.data && itemsData.data.value.length > 0) {
-                try {
-                  await getFolderItems(url, itemsData.data.value, options, session, zip.folder(data.name));
-                }
-                catch(error) {
-                  if (error) {
-                    throw error;
-                  }
-                }
+                  promiseArray.push(new Promise((resolve)=>resolve(getFolderItems(url, itemsData.data.value, options, session, zip.folder(data.name)))));
+                  // promiseArray.push(getFolderItems(url, itemsData.data.value, options, session, zip.folder(data.name)));
               }
             }
           }
@@ -837,13 +803,20 @@ async function getFolderItems(url, array, options, session, zip) {
           }
         }
       }
+      
+      if (promiseArray.length > 0) {
+        await Promise.all(promiseArray);
+      }
+      
       if (fileArr.length) {
         return Promise.all(fileArr);
       }
   })
   .then((result)=>{
     if (result && result.length) {
-      return Promise.all(result.map((data, idx)=>{
+      let array = [];
+      for (let idx in result) {
+        const data = result[idx];
         const param = {
           apiKey: gateWayKey,
           email : session.account.idTokenClaims.email,
@@ -851,8 +824,9 @@ async function getFolderItems(url, array, options, session, zip) {
           comment: "",
           fileData: Buffer.from(data.data).toString('base64')
         }
-        return axios.post(apiUrl + '/api/v1/stream/delete-label', param);
-      }))  
+        array.push(axios.post(apiUrl + '/api/v1/stream/delete-label', param));
+      }
+      return Promise.all(array)
     }
   })
   .then((deleteLabelFiles)=>{
@@ -869,7 +843,6 @@ async function getFolderItems(url, array, options, session, zip) {
         }))
     }
   });
-
 }
 
 

+ 3 - 2
src/views/hello.html

@@ -1388,7 +1388,8 @@
       });
     }
 
-  async function upload(formData) {
+    //업로드 
+    async function upload(formData) {
         const folders = formData.getAll('folder');
         const files = formData.getAll('file');
         const alertTitle = '파일 업로드';
@@ -1797,7 +1798,7 @@
       let str = '';
       let possibleExt = [];
       try {
-        const result = await $.ajax({method: 'post', url: '/api/getPossibleExtList'});
+        const result = await $.ajax({method: 'post', global: false, url: '/api/getPossibleExtList'});
         possibleExt = result.supported_file_ext.split(';');
         possibleExt.splice(possibleExt.length - 1);
       }