authState.js (2920B)
1 const { BufferJSON, initAuthCreds, proto } = require('@whiskeysockets/baileys'); 2 3 // --- FIRESTORE AUTH ADAPTER FOR BAILEYS --- 4 async function useFirestoreAuthState(db, collectionName = 'whatsapp_auth') { 5 const collection = db.collection(collectionName); 6 7 const writeData = async (data, id) => { 8 try { 9 const str = JSON.stringify(data, BufferJSON.replacer); 10 await collection.doc(id).set({ data: str }); 11 } catch (err) { 12 console.error("System: Error writing auth state:", err.message); 13 } 14 }; 15 16 const readData = async (id, throwOnError = false) => { 17 try { 18 const doc = await collection.doc(id).get(); 19 if (doc.exists) { 20 return JSON.parse(doc.data().data, BufferJSON.reviver); 21 } 22 } catch (err) { 23 console.error("System: Error reading auth state:", err.message); 24 if (throwOnError) throw err; 25 } 26 return null; 27 }; 28 29 const removeData = async (id) => { 30 try { 31 await collection.doc(id).delete(); 32 } catch (err) { 33 console.error("System: Error removing auth state:", err.message); 34 } 35 }; 36 37 let creds; 38 try { 39 // Pass true to strictly enforce failure up to startWhatsApp for backoff 40 creds = (await readData('creds', true)) || initAuthCreds(); 41 } catch (err) { 42 throw err; 43 } 44 45 return { 46 state: { 47 creds, 48 keys: { 49 get: async (type, ids) => { 50 const data = {}; 51 await Promise.all(ids.map(async id => { 52 let value = await readData(`${type}-${id}`); 53 if (type === 'app-state-sync-key' && value) { 54 value = proto.Message.AppStateSyncKeyData.fromObject(value); 55 } 56 data[id] = value; 57 })); 58 return data; 59 }, 60 set: async (data) => { 61 const tasks = []; 62 for (const category in data) { 63 for (const id in data[category]) { 64 const value = data[category][id]; 65 const docId = `${category}-${id}`; 66 if (value) { 67 tasks.push(writeData(value, docId)); 68 } else { 69 tasks.push(removeData(docId)); 70 } 71 } 72 } 73 await Promise.all(tasks); 74 } 75 } 76 }, 77 saveCreds: () => { 78 return writeData(creds, 'creds'); 79 }, 80 clearState: async () => { 81 await removeData('creds'); 82 } 83 }; 84 } 85 86 module.exports = { useFirestoreAuthState };