274 lines
12 KiB
JavaScript
274 lines
12 KiB
JavaScript
const API_KEY = 'AIzaSyAobSJ6RDkfIj6oUNYhvRjygkAODzQocyg';
|
|
const DEFAULT_FOLDER_ID = '1kB7XZrLeVG3vTnEaLYM4Q9JPn4CG23B7'; // รหัสที่อยู่หลัง /folders/ ใน URL
|
|
const UPLOAD_TO = 'http://localhost:3001/api/upload-file';
|
|
const CREATE_CONTENT_TO = 'http://localhost:3001/api/content';
|
|
// const UPLOAD_TO = 'https://web-lsw-dev.nueamek.app/api/upload-file';
|
|
// const CREATE_CONTENT_TO = 'https://web-lsw-dev.nueamek.app/api/content';
|
|
|
|
const { google } = require('googleapis');
|
|
const fs = require('fs');
|
|
|
|
// ฟังก์ชันแยกชื่อและวันที่จาก string
|
|
function parseTitleAndDate(input) {
|
|
try {
|
|
// รูปแบบวันที่: ตัวเลข 1-2 หลัก + ชื่อเดือนไทย + ปี 2 หลัก
|
|
// เช่น: 24 ก.ย.67, 1 ม.ค.67, 15 ธ.ค.66
|
|
// รองรับทั้งกรณีที่มีและไม่มีช่องว่างก่อนตัวเลขวัน
|
|
|
|
// Pattern: ตัวเลข 1-2 หลัก + ช่องว่าง + เดือนไทย + ช่องว่าง optional + ปี 2 หลัก
|
|
// ใช้ชื่อเดือนโดยตรงเพราะ character class [ก-๙] ไม่ทำงาน
|
|
const monthPattern = '(ม\\.ค|ก\\.พ|มี\\.ค|เม\\.ย|พ\\.ค|มิ\\.ย|ก\\.ค|ส\\.ค|ก\\.ย|ต\\.ค|พ\\.ย|ธ\\.ค|มกราคม|กุมภาพันธ์|มีนาคม|เมษายน|พฤษภาคม|มิถุนายน|กรกฎาคม|สิงหาคม|กันยายน|ตุลาคม|พฤศจิกายน|ธันวาคม)';
|
|
const datePattern = new RegExp(`(\\d{1,2})\\s+${monthPattern}\\.?\\s*(\\d{2})$`);
|
|
let match = input.match(datePattern);
|
|
|
|
// ถ้าไม่เจอ ลองหาแบบทั่วไป (ไม่ต้องอยู่ท้าย string)
|
|
if (!match) {
|
|
const datePatternGeneral = new RegExp(`(\\d{1,2})\\s+${monthPattern}\\.?\\s*(\\d{2})`);
|
|
match = input.match(datePatternGeneral);
|
|
}
|
|
|
|
if (!match) {
|
|
return {
|
|
title: input,
|
|
date: null
|
|
};
|
|
}
|
|
|
|
const day = parseInt(match[1]);
|
|
// match[2] จะเป็นชื่อเดือนที่ match จาก pattern (เช่น "ก.ย" หรือ "ก.ย.")
|
|
// ลบจุดท้ายออกถ้ามี
|
|
const monthThai = match[2].replace(/\.$/, '');
|
|
const yearShort = parseInt(match[3]);
|
|
|
|
// แปลงชื่อเดือนไทยเป็นเลขเดือน
|
|
const monthMap = {
|
|
'ม.ค': 1, 'ก.พ': 2, 'มี.ค': 3, 'เม.ย': 4, 'พ.ค': 5, 'มิ.ย': 6,
|
|
'ก.ค': 7, 'ส.ค': 8, 'ก.ย': 9, 'ต.ค': 10, 'พ.ย': 11, 'ธ.ค': 12,
|
|
'มกราคม': 1, 'กุมภาพันธ์': 2, 'มีนาคม': 3, 'เมษายน': 4, 'พฤษภาคม': 5, 'มิถุนายน': 6,
|
|
'กรกฎาคม': 7, 'สิงหาคม': 8, 'กันยายน': 9, 'ตุลาคม': 10, 'พฤศจิกายน': 11, 'ธันวาคม': 12
|
|
};
|
|
|
|
const month = monthMap[monthThai];
|
|
if (!month) {
|
|
return {
|
|
title: input,
|
|
date: null
|
|
};
|
|
}
|
|
|
|
// แปลงปี 2 หลักเป็นปี 4 หลัก (พ.ศ.)
|
|
// สมมติว่า 67 = พ.ศ. 2567, 66 = พ.ศ. 2566
|
|
const fullYearBE = 2500 + yearShort; // พ.ศ. 25xx
|
|
|
|
// แปลงเป็น ค.ศ. สำหรับ format YYYY-MM-DD
|
|
const yearAD = fullYearBE - 543;
|
|
|
|
// สร้างวันที่ในรูปแบบ YYYY-MM-DD
|
|
const dateStr = `${yearAD}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
|
|
|
|
// แยกชื่อออก (ลบส่วนวันที่ออก)
|
|
const title = input.substring(0, match.index).trim();
|
|
|
|
return {
|
|
title: title,
|
|
date: dateStr
|
|
};
|
|
} catch (error) {
|
|
return {
|
|
title: input,
|
|
date: null
|
|
};
|
|
}
|
|
}
|
|
|
|
// 1. ระบุ path ของไฟล์ JSON ที่คุณโหลดมา
|
|
const KEYFILEPATH = 'lsw-website-484309-6a86a07bc9d5.json';
|
|
|
|
// 2. กำหนดสิทธิ์ (Scopes) - ในที่นี้คืออ่านไฟล์ใน Drive
|
|
const SCOPES = ['https://www.googleapis.com/auth/drive.readonly'];
|
|
|
|
// 3. สร้างตัวตน (Auth Client)
|
|
const auth = new google.auth.GoogleAuth({
|
|
keyFile: KEYFILEPATH,
|
|
scopes: SCOPES,
|
|
});
|
|
|
|
async function listFiles(deep = 0,folderId = undefined, folderName = '') {
|
|
// https://www.googleapis.com/drive/v3/files
|
|
const url = `https://www.googleapis.com/drive/v3/files?q='${folderId ?? DEFAULT_FOLDER_ID}'+in+parents&key=${API_KEY}`;
|
|
|
|
let files = []
|
|
try {
|
|
const response = await fetch(url);
|
|
const data = await response.json();
|
|
|
|
if (data.files && data.files.length > 0) {
|
|
let forTest = data.files
|
|
if(deep == 0){
|
|
forTest = data.files.slice(0, 1)
|
|
}
|
|
for(let i = 0; i < data.files.length; i++){
|
|
const file = data.files[i]
|
|
// data.files.forEach(async file => {
|
|
// console.log(file);
|
|
// console.log(`ชื่อไฟล์: ${file.name}, ID: ${file.id}`);
|
|
|
|
if(file.mimeType.includes('folder')){
|
|
const fileResultList = await listFiles(deep+1, file.id, file.name)
|
|
const onlyHaveUrlList = fileResultList.filter(fileResult => fileResult.url)
|
|
files.push(...onlyHaveUrlList)
|
|
}
|
|
else if(file.mimeType.includes('image/jpeg')){
|
|
const fileResult = await downloadAndUpload(file.id, file.name)
|
|
if(fileResult.url){
|
|
files.push(fileResult)
|
|
}
|
|
}
|
|
// });
|
|
}
|
|
} else {
|
|
console.log('ไม่พบไฟล์ในโฟลเดอร์นี้');
|
|
}
|
|
} catch (error) {
|
|
console.error('เกิดข้อผิดพลาด:', error);
|
|
}
|
|
|
|
if(deep == 1 && folderName){
|
|
// แยกชื่อและวันที่จาก folderName
|
|
const { title, date } = parseTitleAndDate(folderName);
|
|
|
|
const payload = {
|
|
menuId: 402,
|
|
templateId: 2,
|
|
tag: 2,
|
|
title: title || folderName, // ใช้ชื่อที่แยกแล้ว หรือใช้ชื่อเดิมถ้าแยกไม่ได้
|
|
content: ' ',
|
|
startAt: date || undefined, // ใช้วันที่ที่แยกแล้ว หรือใช้ค่า default
|
|
// filedoc: null,
|
|
imageList: files,
|
|
}
|
|
|
|
console.log('payload :', payload)
|
|
// {
|
|
// "menuId": 402,
|
|
// "templateId": 2,
|
|
// "tag": "1",
|
|
// "title": "1",
|
|
// "content": "<p>1</p>",
|
|
// "startAt": "2026-01-19",
|
|
// "imageList": [
|
|
// {
|
|
// "id": "effbdaf8-40d3-4980-9f3c-dd32ae93a272",
|
|
// "url": "https://nu-test01.nueamek.app/lsw/uploads/1768789089263-84cwzzhe1iw.jpg",
|
|
// "name": "LINE_ALBUM_ทำบุญให้รถบัส นักเรียนที่เสียชีวิต 251167_241125_1.jpg"
|
|
// }
|
|
// ]
|
|
// }
|
|
|
|
// console.log('Parsed:', { original: folderName, title, date });
|
|
|
|
try {
|
|
const contentResponse = await fetch(CREATE_CONTENT_TO, {
|
|
method: 'POST',
|
|
body: payload
|
|
});
|
|
console.log('contentResponse :', contentResponse)
|
|
} catch (error) {
|
|
console.error('create content error: ',error)
|
|
}
|
|
}
|
|
|
|
return files
|
|
}
|
|
|
|
async function downloadAndUpload(fileId, fileName) {
|
|
try {
|
|
// #region วิธีที่ง่ายแต่ access มากไปจะโดน google block เพราะคิดว่าเป็น bot
|
|
// // 1. ดาวน์โหลดเนื้อหาไฟล์จาก Google Drive (ใช้ alt=media)
|
|
// const downloadUrl = `https://www.googleapis.com/drive/v3/files/${fileId}?alt=media&key=${API_KEY}`;
|
|
// const response = await fetch(downloadUrl);
|
|
|
|
// console.log('response', response)
|
|
// if (!response.ok) {
|
|
// // อ่านรายละเอียด Error จาก Google
|
|
// const errorText = await response.text();
|
|
// console.error("Error Detail:", errorText);
|
|
// throw new Error('Download failed');
|
|
// }
|
|
|
|
// const fileBlob = await response.blob();
|
|
|
|
// // 2. สร้าง FormData เพื่อเตรียมส่งไปยัง API ของคุณ
|
|
// const formData = new FormData();
|
|
// // 'file' คือชื่อ field ที่ API ของคุณรอรับ (เปลี่ยนได้ตามความเหมาะสม)
|
|
// formData.append('file', fileBlob, fileName);
|
|
// #endregion
|
|
|
|
// #region Service Account
|
|
const drive = google.drive({ version: 'v3', auth });
|
|
|
|
// 1. การดึงเนื้อหาไฟล์ (Media)
|
|
const res = await drive.files.get(
|
|
{ fileId: fileId, alt: 'media' },
|
|
// { responseType: 'stream' }
|
|
{ responseType: 'arraybuffer' }
|
|
);
|
|
// คุณสามารถส่ง res.data นี้เข้า FormData เพื่อส่งต่อไปยัง API ของคุณได้เลย
|
|
|
|
// 2. สร้าง FormData เพื่อเตรียมส่งไปยัง API ของคุณ
|
|
// แปลง ArrayBuffer ที่ได้เป็น Blob
|
|
const fileBlob = new Blob([res.data]);
|
|
const formData = new FormData();
|
|
formData.append('file', fileBlob, fileName);
|
|
// #endregion
|
|
|
|
// 3. ส่งข้อมูลไปยัง API ของคุณด้วย POST method
|
|
const uploadResponse = await fetch(UPLOAD_TO, {
|
|
method: 'POST',
|
|
body: formData
|
|
});
|
|
|
|
const result = await uploadResponse.json();
|
|
// console.log(`อัปโหลดไฟล์ ${fileName} สำเร็จ:`, result);
|
|
|
|
return result
|
|
} catch (error) {
|
|
console.error(`เกิดข้อผิดพลาดกับไฟล์ ${fileName}:`, error);
|
|
return {
|
|
error: error
|
|
}
|
|
}
|
|
}
|
|
|
|
// // ตัวอย่างการใช้งานร่วมกับรายชื่อไฟล์ที่ได้จากข้อก่อนหน้า
|
|
// async function processAllFiles(files) {
|
|
// for (const file of files) {
|
|
// // กรองเอาเฉพาะไฟล์ .js (ถ้าจำเป็น)
|
|
// if (file.name.endsWith('.js')) {
|
|
// await downloadAndUpload(file.id, file.name);
|
|
// }
|
|
// }
|
|
// }
|
|
|
|
// downloadAndUpload('14SGY4irPJ1FwUA5472zlyYtzHvDNaCQ4', 'test')
|
|
|
|
// // ตัวอย่างการทดสอบฟังก์ชัน parseTitleAndDate
|
|
// // if (require.main === module) {
|
|
// const testCases = [
|
|
// "จิตอาสา รร.อบต.บึงคำพร้อย24 ก.ย.67",
|
|
// "กิจกรรมวันเด็ก 15 ม.ค.67",
|
|
// "ประชุมสภา 1 ธ.ค.66",
|
|
// "ไม่มีวันที่ในนี้"
|
|
// ];
|
|
|
|
// console.log('\n=== ทดสอบฟังก์ชัน parseTitleAndDate ===');
|
|
// testCases.forEach(test => {
|
|
// const result = parseTitleAndDate(test);
|
|
// console.log(`Input: "${test}"`);
|
|
// console.log(` -> Title: "${result.title}"`);
|
|
// console.log(` -> Date: ${result.date || 'ไม่พบวันที่'}`);
|
|
// console.log('');
|
|
// });
|
|
// // }
|
|
|
|
listFiles(); |