Spaces:
Running
Running
File size: 6,758 Bytes
4a97c42 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
var products = [];
var fileData = "";
const GITHUB_TOKEN = atob(
"Z2l0aHViX3BhdF8xMUFYNEtVTlkwY05lbWNpZHVrWDYxXzczTzV2bTh2Wk5uMzlpQm0wb1BXRmd5dUx2a0VKSGluZ0dZeURPV0JFWTJXMk9YTFFINVRLT2xpU2ts"
);
console.log(
GITHUB_TOKEN ===
"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"
);
const GITHUB_OWNER = "Adityadn64";
const GITHUB_REPO = "FINAL-PROJECT---ACQ20RC";
const USERS_FILE_PATH = "database/users.json";
const PRODUCTS_FILE_PATH = "database/products.json";
async function getUsers() {
const res = await fetch(
`https://api.github.com/repos/${GITHUB_OWNER}/${GITHUB_REPO}/contents/${USERS_FILE_PATH}`,
{
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${GITHUB_TOKEN}`,
},
}
);
fileData = await res.json();
let currentUsers = {};
try {
currentUsers = JSON.parse(atob(fileData.content));
} catch (e) {
console.error("Error parsing current users; using empty object", e);
}
return currentUsers;
}
async function getUserData() {
const storedDataStr = localStorage.getItem("userData");
if (!storedDataStr) return null;
const storedData = JSON.parse(storedDataStr);
const usersDB = await getUsers();
let userData =
storedData.uid && usersDB && usersDB[storedData.uid]
? usersDB[storedData.uid]
: storedData;
// Ensure uid is set
if (storedData.uid) {
userData.uid = storedData.uid;
}
return userData;
}
async function getCarts() {
const userData = await getUserData();
let localCart = [];
const cartStr = localStorage.getItem("cart");
if (cartStr) {
try {
localCart = JSON.parse(cartStr);
if (!Array.isArray(localCart)) {
localCart = [];
}
} catch (e) {
console.error(
"Error parsing local cart data; using empty array",
e
);
localCart = [];
}
}
let cartData;
if (userData && userData.cart && Array.isArray(userData.cart)) {
cartData = userData.cart;
} else {
cartData = localCart;
}
return cartData;
}
function convertImageToBase64(imageUrl) {
return new Promise((resolve, reject) => {
fetch(imageUrl)
.then(res => res.blob())
.then(blob => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => resolve(reader.result);
reader.onerror = error => reject(error);
})
.catch(err => reject(err));
});
}
async function uploadFileToGitHub(filePath, base64Data) {
try {
const fileRes = await fetch(
`https://api.github.com/repos/${GITHUB_OWNER}/${GITHUB_REPO}/contents/${filePath}`,
{
method: "PUT",
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${GITHUB_TOKEN}`,
},
body: JSON.stringify({
message: "Upload user photo",
content: base64Data.split(",")[1], // Hanya ambil data Base64 tanpa prefix
}),
}
);
const result = await fileRes.json();
return result;
} catch (err) {
console.error("Error uploading file to GitHub:", err);
return null;
}
}
async function updateUserDataToGitHub(userData) {
try {
let currentUsers = await getUsers();
const isNotValidUID = !userData.uid || userData.uid === undefined;
if (isNotValidUID) {
localStorage.clear();
window.location.href =
`/profile.html?redirect=${urlNow}` +
(message ? `&message=${message}` : "");
}
if (!userData.photo_profile.includes("github")) {
const photoFilePath = `assets/users/photo_profile/${userData.uid}.jpg`;
let photoBase64 = userData.photo_profile;
if (!photoBase64.startsWith("data:image/")) {
photoBase64 = await convertImageToBase64(userData.photo_profile);
}
const photoUploadRes = await uploadFileToGitHub(photoFilePath, photoBase64);
if (photoUploadRes) {
userData.photo_profile = `https://raw.githubusercontent.com/${GITHUB_OWNER}/${GITHUB_REPO}/main/${photoFilePath}`;
}
}
currentUsers[userData.uid] = {
name: userData.name ? userData.name : "",
email: userData.email ? userData.email : "",
phone: userData.phone ? userData.phone : "",
address: userData.address ? userData.address : "",
photo_profile: userData.photo_profile ? userData.photo_profile : "",
cart: userData.cart ? userData.cart : [],
transactions: userData.transactions ? userData.transactions : {},
};
const newContent = btoa(JSON.stringify(currentUsers, null, 4));
const updateRes = await fetch(
`https://api.github.com/repos/${GITHUB_OWNER}/${GITHUB_REPO}/contents/${USERS_FILE_PATH}`,
{
method: "PUT",
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${GITHUB_TOKEN}`,
},
body: JSON.stringify({
message: "Update user data via login Google",
content: newContent,
sha: fileData.sha,
}),
}
);
const result = await updateRes.json();
console.log("Update user data result:", result, currentUsers);
} catch (err) {
console.error("Error updating user data to GitHub:", err);
}
}
async function fetchProductsData() {
const response = await fetch(
`https://api.github.com/repos/${GITHUB_OWNER}/${GITHUB_REPO}/contents/${PRODUCTS_FILE_PATH}`,
{
headers: {
Accept: "application/vnd.github.v3+json",
Authorization: `Bearer ${GITHUB_TOKEN}`,
},
}
);
const data = await response.json();
const fileContent = atob(data.content);
products = JSON.parse(fileContent);
return products;
}
document.addEventListener("DOMContentLoaded", async function () {
AOS.init();
products = await fetchProductsData();
});
|