Przeglądaj źródła

update 2024-06-14

junggilpark 1 rok temu
rodzic
commit
16811d0a14
2 zmienionych plików z 188 dodań i 128 usunięć
  1. 184 125
      src/app.js
  2. 4 3
      src/views/hello.html

+ 184 - 125
src/app.js

@@ -530,10 +530,10 @@ async function setLabelFiles(param, headers, lengthSync, apiKey, email) {
           dispFileName: result.data.result.dispFileName,
           realFileName: result.data.result.outputFileName,
         }
-        console.log(infoParam);
+        // console.log(infoParam);
         const infoData = await axios.post(apiUrl + '/api/v1/file/info', infoParam);
-        console.log('=================infoData ========================');
-        console.log(infoData.data);
+        // console.log('=================infoData ========================');
+        // console.log(infoData.data);
         resultObj.data = result.data.result;
         resultObj.success = 'S'; 
       }
@@ -599,7 +599,7 @@ serverApp.post('/api/makePptx',
       const options = getOptions(req.session.accessToken);
       const {siteId, path, name} = req.body;
       const pres = new pptxgen();
-      pres.addSlide("TITLE_SLIDE");
+      pres.addSlide();
       const resultObj = {message:'', success: 'F'};
       pres.stream().then(async (data)=>{
         try{
@@ -610,6 +610,7 @@ serverApp.post('/api/makePptx',
           if (labelData.success === 'F') {
             return res.json(labelData);
           }
+          
           const parentData = await axios.get(endPoint + "/sites/"+ siteId +path, options);
           if (parentData.data) {
             const result = await axios.put(endPoint + "/sites/"+ siteId +"/drive/items/"+parentData.data.id+':/'+name+':/content', labelData.data, options);
@@ -643,10 +644,10 @@ serverApp.post('/api/check-name',
           const result = await axios.get(endPoint + "/sites/"+ siteId +"/drive/items/" + itemId +"/children", options);
           if (result && result.data && result.data.value) {
             let idx = result.data.value.findIndex(obj=>obj.name === name);
-            console.log(name);
-            console.log(idx);
-            console.log((idx > -1));
-            console.log(result.data.value);
+            // console.log(name);
+            // console.log(idx);
+            // console.log((idx > -1));
+            // console.log(result.data.value);
             res.json({hasName: (idx > -1)});
           }
         }
@@ -745,33 +746,33 @@ serverApp.post('/api/upload', upload.array('file'),
       if (files && files.length > 0) {
           const promiseArray = [];
           const labelPromiseArray = [];
-          const fileWriteArray = [];
+          // const fileWriteArray = [];
           const possibleExt = POSSIBLE_EXT;
           const {supported_file_ext, protected_file_ext} = possibleExt;
           let supportedArr = [];
-          let protectedArr = [];
-          let protectedMap = new Map();
+          // let protectedArr = [];
+          // let protectedMap = new Map();
           if (supported_file_ext && protected_file_ext) {
             supportedArr = supported_file_ext.split(';');
-            protectedArr = protected_file_ext.split(';');
+            // protectedArr = protected_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]);
-                }
-              }
-            }
+            // 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;
@@ -786,35 +787,35 @@ serverApp.post('/api/upload', upload.array('file'),
                                       + 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
-                  })
-                }));
+                // 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",
+                  aipGuid: "878173ae-cc36-4881-af57-604af868314c",
+                  // aipGuid: "0166b75f-6a93-47f3-8fd3-e1e7c59141ab",
+                  // comment: "set-protection",
+                  comment: "set-label",
                   fileData: base64Data,
                 }
-                // console.log(realFileName);
-                // console.log(param);
-                // labelPromiseArray.push(axios.post(apiUrl + '/api/v1/stream/set-label', param));
-                labelPromiseArray.push(axios.post(apiUrl + '/api/v1/stream/set-protection', param));
+
+                // 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]);
+                  // console.log(file_path[idx]);
                   if (!path.includes(":")) { 
                     formatPath = ":" + file_path[idx]; 
                   }
@@ -825,6 +826,7 @@ serverApp.post('/api/upload', upload.array('file'),
     
                 let itemId = '';
                 const uri = endPoint + "/sites/"+ siteId + path + formatPath;
+                // siteInfoArr.push(axios.get(uri, options));
                 if (beforeUri === uri) { 
                   itemId = beforeItemId;
                 }
@@ -841,16 +843,20 @@ serverApp.post('/api/upload', upload.array('file'),
                   }
                 }
                 
-                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+':/'+originName+':/content');
+                // 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);
 
@@ -860,20 +866,30 @@ serverApp.post('/api/upload', upload.array('file'),
 
               const labelTime = new Date();
               const labelResult = await Promise.all(labelPromiseArray);
-              console.log(labelResult[0].data.result.fileData);
+              // console.log(labelResult[0].data.result.fileData);
               console.log('label time : ', timeCheck(labelTime, new Date()));
-
-              labelResult.forEach((obj, idx)=>{
-                console.log(obj.data);
+              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');
-                  console.log(obj.data);
-                  promiseArray[idx] = axios.put(promiseArray[idx], data, options);
+                  // 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)=>{
@@ -947,42 +963,60 @@ serverApp.post('/api/download',
           const options = getOptions(req.session.accessToken);
           const arr = JSON.parse(fileIds);
           const url = endPoint + "/sites/"+ siteId + "/drive/items/";
-          const zip = new JSZIP();
-          const downObj = await getFolderItems(url, arr, options, req.session);
-          const folderLength = downObj.folder.length;
-          const fileLength = downObj.files.length;
-          if (downObj) {
-            if (folderLength > 0 || fileLength > 1 ) {
-              createZipFile(downObj, zip);
-              const now = new Date();
-              const year = now.getFullYear().toString();
-              let month = now.getMonth() + 1;
-              if (month < 10) month = "0" + month;
-              let date = now.getDate();
-              if (date < 10) date = "0" + date;
-              zip.generateAsync({
-                type: 'nodebuffer',
-                mimeType: 'application/epub+zip',
-                compression: 'DEFLATE',
-                compressionOptions: {
-                  level: 9
-                },
-              }).then((resZip)=>{
-                const endTime = new Date();
-                console.log('시작 시간 :', startTime.toLocaleString(), ', 종료 시간 :', endTime.toLocaleString(), ', 소요 시간 :', timeCheck(startTime, endTime));
-                return res.json({success: 'S', data: resZip, name: zipName + '_' + year + '-' + month + '-' + date + '.zip'});
-              })
-              .catch((error)=>{
-                console.log(error);
-                return res.json({success: 'F', message:'파일 다운로드 중 오류가 발생하였습니다.', error: error});
-              });
+          const result = await axios(url + arr[0], options);
+
+          // 단일 파일 다운로드
+          if (arr.length === 1 && result && result.data && result.data.file) {
+            const dataUrl = result.data['@microsoft.graph.downloadUrl'];
+            const fileOption = {responseType: 'arraybuffer', headers: { withCredentials : true }};
+            const fileData = await axios.get(dataUrl, fileOption);
+            const bufferData = Buffer.from(fileData.data, 'base64');
+            const param = {
+              apiKey: gateWayKey,
+              email : res.session.account.idTokenClaims.email,
+              dispFileName: result.data.name,
+              comment: "",
+              fileData: Buffer.from(bufferData).toString('base64')
             }
-            else if (downObj.files.length === 1){
-              const data = downObj.files[0];
-              const bufferData = Buffer.from(data.data, 'base64');
-              return res.json({success: 'S', data: bufferData, name: data.name})
+            const deleteLabelResult = await axios.post(apiUrl + '/api/v1/stream/delete-label', param);
+            if (deleteLabelResult && deleteLabelResult.data && !deleteLabelResult.data.result.errorCode) {
+              return res.json({success: 'S', data: Buffer.from(data.data, 'base64'), name: deleteLabelResult.data.result.name})
             }
           }
+          //폴더 또는 다중 파일 다운로드
+          else {
+            const zip = new JSZIP();
+            // const downObj = await getFolderItems(url, arr, options, req.session, zip);
+            const timer = new Date();
+            console.log('getFolderItems Start : ', timer.toLocaleString());
+            await getFolderItems(url, arr, options, req.session, zip);
+            const timerEnd = new Date();
+            console.log('getFolderItems end : ', timerEnd.toLocaleString(), ',소요시간 : '+ timeCheck(timer,timerEnd));
+            // createZipFile(downObj, zip);
+            const now = new Date();
+            const year = now.getFullYear().toString();
+            let month = now.getMonth() + 1;
+            if (month < 10) month = "0" + month;
+            let date = now.getDate();
+            if (date < 10) date = "0" + date;
+            zip.generateAsync({
+              type: 'nodebuffer',
+              // mimeType: 'application/epub+zip',
+              // compression: 'DEFLATE',
+              // compressionOptions: {
+              //   level: 9
+              // },
+            }).then((resZip)=>{
+              const endTime = new Date();
+              console.log('시작 시간 :', startTime.toLocaleString(), ', 종료 시간 :', endTime.toLocaleString(), ', 소요 시간 :', timeCheck(startTime, endTime));
+              return res.json({success: 'S', data: resZip, name: zipName + '_' + year + '-' + month + '-' + date + '.zip'});
+            })
+            .catch((error)=>{
+              console.log(error);
+              return res.json({success: 'F', message:'파일 다운로드 중 오류가 발생하였습니다.', error: error});
+            });
+
+          }
       }
       else {
         return res.json({message:'다운로드 파일 정보를 확인 할 수 없습니다.', success:'F'})
@@ -1101,12 +1135,14 @@ function createZipFile(obj, zip) {
   
   if (obj.files && obj.files.length > 0) {
     for (let file of obj.files) {
+      console.log(file.name);
       zip.file(file.name, file.data, {base64: true});
     }
   }
 
   if (obj.folder && obj.folder.length > 0) {
     for (let folder of obj.folder) {
+      console.log(folder.name);
       zip.folder(folder.name);
       if (folder.subFolder) {
         createZipFile(folder.subFolder, zip.folder(folder.name));
@@ -1115,26 +1151,32 @@ function createZipFile(obj, zip) {
   }
 }
 
-async function getFolderItems(url, array, options, session) {
-  const files         = [];
-  const folder        = [];
+async function getFolderItems(url, array, options, session, zip) {
+  // const files         = [];
+  // const folder        = [];
   const sitesInfoArr  = [];
   const fileArr       = [];
   const fileInfoArr   = [];
 
-  const folderCheckTime = new Date();
+  // const folderCheckTime = new Date();
+  // for (let fileId of array) {
+  //   sitesInfoArr.push(axios.get(url + fileId, options));
+  // }
+  // const siteInfos = await Promise.all(sitesInfoArr).catch((error)=>{
+  //   console.log(error);
+  //   throw error;
+  // });
   for (let fileId of array) {
     sitesInfoArr.push(axios.get(url + fileId, options));
   }
-  const siteInfos = await Promise.all(sitesInfoArr).catch((error)=>{
-    console.log(error);
-  });
-
+  const siteInfos = await Promise.all(sitesInfoArr);
+  
   for (let site of siteInfos) {
     const data = site.data;
     if (data) {
       if (data.folder) {
-        const folderObj = {name : data.name, subFolder : []};
+        // const folderObj = {name : data.name, subFolder : []};
+        zip.folder(data.name);
         if (data.folder.childCount) {
           const itemsData = await axios.get(url + data.id + '/children', options);
           if (itemsData && itemsData.data && itemsData.data.value.length > 0) {
@@ -1144,8 +1186,9 @@ async function getFolderItems(url, array, options, session) {
             }
 
             try {
-              let result = await getFolderItems(url, idArr, options, session);
-              folderObj.subFolder = result;
+              // let result = await getFolderItems(url, idArr, options, session, zip.folder(data.name));
+              await getFolderItems(url, idArr, options, session, zip.folder(data.name));
+              // folderObj.subFolder = result;
             }
             catch(error) {
               if (error) {
@@ -1155,7 +1198,7 @@ async function getFolderItems(url, array, options, session) {
             // subFolder.push(result);
           }
         }
-        folder.push(folderObj);
+        // folder.push(folderObj);
       }
       else {
         const dataUrl = data['@microsoft.graph.downloadUrl'];
@@ -1166,47 +1209,63 @@ async function getFolderItems(url, array, options, session) {
     }
   }
 
-  console.log('======================= folder check end ===============================');
-  console.log('folder check 소요시간 : ', timeCheck(folderCheckTime, new Date()));
+  // console.log('======================= folder check end ===============================');
+  // console.log('folder check 소요시간 : ', timeCheck(folderCheckTime, new Date()));
 
 
-  console.log('======================= delete label start ===============================');
-  const fileDataArr = await Promise.all(fileArr);
-  
-  const deleteLabelTime = new Date();
-  const deleteLabelArr = [];
-  for (let idx in fileDataArr) {
-    let fileData = fileDataArr[idx].data;
-    const param = {
-      apiKey: gateWayKey,
-      email : session.account.idTokenClaims.email,
-      dispFileName: fileInfoArr[idx].name,
-      comment: "",
-      fileData: Buffer.from(fileData).toString('base64')
+  // console.log('======================= delete label start ===============================');
+  const fileDataArr = await Promise.all(fileArr).then((result)=>{
+    let deleteLabelArr = [];
+    for (let idx in result) {
+      let fileData = result[idx].data;
+      const param = {
+        apiKey: gateWayKey,
+        email : session.account.idTokenClaims.email,
+        dispFileName: fileInfoArr[idx].name,
+        comment: "",
+        fileData: Buffer.from(fileData).toString('base64')
+      }
+      deleteLabelArr.push(axios.post(apiUrl + '/api/v1/stream/delete-label', param));
     }
-    deleteLabelArr.push(axios.post(apiUrl + '/api/v1/stream/delete-label', param));
-  }
+    return deleteLabelArr;
+  });
+  
+  // const deleteLabelTime = new Date();
+  // const deleteLabelArr = [];
+  // for (let idx in fileDataArr) {
+  //   let fileData = fileDataArr[idx].data;
+  //   const param = {
+  //     apiKey: gateWayKey,
+  //     email : session.account.idTokenClaims.email,
+  //     dispFileName: fileInfoArr[idx].name,
+  //     comment: "",
+  //     fileData: Buffer.from(fileData).toString('base64')
+  //   }
+  //   deleteLabelArr.push(axios.post(apiUrl + '/api/v1/stream/delete-label', param));
+  // }
 
-  const deleteLabelFiles = await Promise.all(deleteLabelArr);
+  const deleteLabelFiles = await Promise.all(fileDataArr);
+  // const deleteLabelFiles = await Promise.all(deleteLabelArr);
   for (let idx in deleteLabelFiles) {
     const fileObj = deleteLabelFiles[idx];
     const data = fileObj.data;
     if (data.success && !data.result.errorCode) {
-      files.push({name : fileInfoArr[idx].name, data: data.result.fileData});
+      // files.push({name : data.result.dispFileName, data: data.result.fileData});
+      zip.file(data.result.dispFileName, data.result.fileData, {base64: true});
     }
     else {
       throw data.result.dispFileName + ' : ' + data.result.errorMessage;
     }
   }
-  console.log('======================= delete label end ===============================')
-  console.log('delete label 소요시간 : ',timeCheck(deleteLabelTime, new Date()));
+  // console.log('======================= delete label end ===============================')
+  // console.log('delete label 소요시간 : ',timeCheck(deleteLabelTime, new Date()));
 
-  const resultObj = {
-    folder : folder,
-    files : files,
-  };
+  // const resultObj = {
+  //   folder : folder,
+  //   files : files,
+  // };
 
-  return resultObj;
+  // return resultObj;
 }
 
 

+ 4 - 3
src/views/hello.html

@@ -565,13 +565,14 @@
         let imageExt = ".svg";
         //photo 
         // if (obj.file.mimeType && obj.file.mimeType.includes('image')){
-        if (['psd', 'bmp', 'rle', 'dib', 'jpeg', 'jpg', 'gif', 'ppng', 'png', 'tiff', 'raw', 'ico'].includes(ext)){
+        if (['psd', 'bmp', 'pbmp', 'rle', 'dib', 'jpeg', 'pjpeg', 'jpg', 'pjpg', 'gif', 'pgif', 'ppng', 'png', 
+        'tif', 'ptif', 'ptiff', 'tiff', 'raw', 'ico', 'jpe', 'pjpe', 'jt', 'pjt'].includes(ext)){
           ext = 'photo';
         }
         else if (['ai', 'eps', 'svg'].includes(ext)) {
           ext = 'vector';
         }
-        else if (['txt', 'properties'].includes(ext)) {
+        else if (['txt', 'ptxt', 'properties'].includes(ext)) {
           ext = 'txt';
         }
         else if (['pptx', 'ppt', 'pptm'].includes(ext)) {
@@ -615,7 +616,7 @@
         'mf', 'otf', 'pfa', 'pfb', 'pfr', 'sfd', 'suit', 'tfm', 'ttc', 'vlw', 'woff', 'xfn'].includes(ext)) {
           ext = 'font';
         }
-        else if (['xml'].includes(ext)) {
+        else if (['xml', 'pxml'].includes(ext)) {
           ext = 'xml';
         }
         else {