[go: up one dir, main page]

0% found this document useful (0 votes)
4 views5 pages

Code Gs 11

This document contains a Google Apps Script that provides a web interface for data collection and processing. It includes functions to handle form data, save various types of media, and store location information in Google Drive and Google Sheets. The script also includes error handling and categorization of QR code data based on its content type.

Uploaded by

Ramadan Hasibuan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views5 pages

Code Gs 11

This document contains a Google Apps Script that provides a web interface for data collection and processing. It includes functions to handle form data, save various types of media, and store location information in Google Drive and Google Sheets. The script also includes error handling and categorization of QR code data based on its content type.

Uploaded by

Ramadan Hasibuan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

// Fungsi utama untuk menampilkan antarmuka web

function doGet() {
return HtmlService.createHtmlOutputFromFile('Index')
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
.addMetaTag('viewport', 'width=device-width, initial-scale=1');
}

// Fungsi untuk memproses data dari form HTML


function processFormData(data) {
try {
// 1. Setup Folder dan Spreadsheet
const mainFolder = createFolder("AplikasiPengumpulanData");
const todayFolder = createFolder(
Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyy-MM-dd"),
mainFolder.getId()
);

const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName("Data") || ss.insertSheet("Data");

// 2. Handle Timestamp
const timestamp = getValidTimestamp(data.timestamp);
const timestampStr = Utilities.formatDate(timestamp,
Session.getScriptTimeZone(), "yyyy-MM-dd HH:mm:ss");
const fileTimestamp = Utilities.formatDate(timestamp,
Session.getScriptTimeZone(), "yyyyMMdd_HHmmss");

// 3. Handle Location Data


const locationInfo = processLocationData(data.locationData, timestamp);

// 4. Simpan Semua Data ke Drive


const savedFiles = {
text: saveTextData(data.textData, todayFolder, fileTimestamp),
photo: saveMedia(data.photoData, "photo", "image/jpeg", todayFolder,
fileTimestamp),
video: saveMedia(data.videoData, "video", "video/webm", todayFolder,
fileTimestamp),
audio: saveMedia(data.audioData, "audio", "audio/webm", todayFolder,
fileTimestamp),
location: saveLocationData(locationInfo, todayFolder, fileTimestamp)
};

// 5. Simpan ke Spreadsheet
if (sheet.getLastRow() === 0) {
sheet.appendRow([
"Timestamp", "Link Teks", "Link Foto", "Link Video", "Link Audio",
"Link Data Lokasi", "Link Google Maps", "Latitude", "Longitude",
"Akurasi (m)", "Teks di Foto", "Durasi Rekaman", "Perangkat", "Folder
Drive"
]);
}

sheet.appendRow([
timestampStr,
savedFiles.text.url || "-",
savedFiles.photo.url || "-",
savedFiles.video.url || "-",
savedFiles.audio.url || "-",
savedFiles.location.jsonUrl || "-",
savedFiles.location.mapUrl || "-",
locationInfo.lat || "-",
locationInfo.lng || "-",
locationInfo.accuracy || "-",
data.photoText || "-",
data.recordingDuration || "-",
JSON.stringify(data.deviceInfo || {}),
todayFolder.getUrl()
]);

return {
status: "success",
message: "✅ Data berhasil disimpan!",
links: {
spreadsheet: ss.getUrl(),
driveFolder: todayFolder.getUrl(),
...savedFiles
}
};

} catch (error) {
console.error("Error in processFormData:", error);
return {
status: "error",
message: "❌ Gagal menyimpan data: " + error.message
};
}
}

// =========================================
// FUNGSI BANTU UTAMA
// =========================================

function createFolder(folderName, parentFolderId = null) {


try {
const folders = parentFolderId
? DriveApp.getFolderById(parentFolderId).getFoldersByName(folderName)
: DriveApp.getFoldersByName(folderName);

return folders.hasNext()
? folders.next()
: (parentFolderId
? DriveApp.getFolderById(parentFolderId).createFolder(folderName)
: DriveApp.createFolder(folderName));
} catch (error) {
throw new Error(`Gagal membuat folder ${folderName}: ${error.message}`);
}
}

function getValidTimestamp(timestamp) {
try {
if (!timestamp) return new Date();
if (timestamp instanceof Date) return isNaN(timestamp.getTime()) ? new Date() :
timestamp;

const date = new Date(timestamp);


return isNaN(date.getTime()) ? new Date() : date;
} catch (e) {
console.warn("Error parsing timestamp, using current time:", e);
return new Date();
}
}

function processLocationData(locationData, fallbackTimestamp) {


if (!locationData) {
return {
lat: null,
lng: null,
accuracy: null,
timestamp: fallbackTimestamp.toISOString(),
mapUrl: null
};
}

try {
const lat = parseFloat(locationData.lat);
const lng = parseFloat(locationData.lng);
const accuracy = parseInt(locationData.accuracy);

return {
lat: isNaN(lat) ? null : lat,
lng: isNaN(lng) ? null : lng,
accuracy: isNaN(accuracy) ? null : accuracy,
timestamp: getValidTimestamp(locationData.timestamp).toISOString(),
mapUrl: (!isNaN(lat) && !isNaN(lng))
? `https://www.google.com/maps?q=${lat},${lng}`
: null
};
} catch (error) {
console.error("Error processing location data:", error);
return {
lat: null,
lng: null,
accuracy: null,
timestamp: fallbackTimestamp.toISOString(),
mapUrl: null
};
}
}

function saveTextData(text, folder, timestamp) {


if (!text || text.trim() === "") return { url: null };

try {
const fileName = `teks_${timestamp}.txt`;
const file = folder.createFile(fileName, text, MimeType.PLAIN_TEXT);
return { url: file.getUrl() };
} catch (error) {
console.error("Error saving text:", error);
return { url: null };
}
}

function saveMedia(base64Data, type, mimeType, folder, timestamp) {


if (!base64Data) return { url: null };

try {
const base64Content = base64Data.split(",")[1] || base64Data;
const extension = mimeType === "image/jpeg" ? ".jpg" : ".webm";
const fileName = `${type}_${timestamp}${extension}`;

const blob = Utilities.newBlob(


Utilities.base64Decode(base64Content),
mimeType,
fileName
);

const file = folder.createFile(blob);


return { url: file.getUrl() };
} catch (error) {
console.error(`Error saving ${type}:`, error);
return { url: null };
}
}

function saveLocationData(locationInfo, folder, timestamp) {


if (!locationInfo.lat || !locationInfo.lng) {
return { jsonUrl: null, mapUrl: null };
}

try {
const jsonContent = {
latitude: locationInfo.lat,
longitude: locationInfo.lng,
accuracy: locationInfo.accuracy,
timestamp: locationInfo.timestamp,
mapUrl: locationInfo.mapUrl
};

const jsonFileName = `lokasi_${timestamp}.json`;


const jsonFile = folder.createFile(
jsonFileName,
JSON.stringify(jsonContent, null, 2),
MimeType.PLAIN_TEXT
);

return {
jsonUrl: jsonFile.getUrl(),
mapUrl: locationInfo.mapUrl
};
} catch (error) {
console.error("Error saving location:", error);
return { jsonUrl: null, mapUrl: null };
}
}

// =========================================
// FUNGSI QR CODE (VERSI DISATUKAN)
// =========================================

function saveQRCodeData(qrData) {
try {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName("QR Codes") || ss.insertSheet("QR Codes");

// Header jika sheet baru


if (sheet.getLastRow() === 0) {
sheet.appendRow(["Timestamp", "QR Content", "Tipe Data"]);
sheet.getRange(1, 1, 1, 3).setFontWeight("bold");
}

// Deteksi tipe data


const dataType = classifyQRData(qrData.content);

// Tambahkan data baru


sheet.appendRow([
Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyy-MM-dd
HH:mm:ss"),
qrData.content,
dataType
]);

return {
status: "success",
message: `QR Code (${dataType}) berhasil disimpan!`
};
} catch (error) {
console.error("Error saveQRCodeData:", error);
return {
status: "error",
message: `Gagal menyimpan QR: ${error.message}`
};
}
}

function classifyQRData(content) {
if (!content) return "EMPTY";

const patterns = {
URL: /^(http|https):\/\//,
EMAIL: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
PHONE: /^\+?[\d\s\-()]{8,}$/,
NUMERIC: /^\d{6,}$/,
WIFI: /^WIFI:/i
};

for (const [type, regex] of Object.entries(patterns)) {


if (regex.test(content)) return type;
}

return content.length > 50 ? "LONG_TEXT" : "TEXT";


}

You might also like