Libre Translate Logic - abhiram-shaji/Langroove GitHub Wiki
This documentation provides a detailed explanation of the chat language management and translation utilities implemented in the provided code.
The utilities include functions to:
-
Ensure a chat document with language settings exists (
ensureChatLanguage
). -
Set a specific language for a chat participant (
setChatLanguage
). -
Translate text between languages using the LibreTranslate API (
translateText
).
- Verifies the existence of a chat document with the correct structure for storing participant language preferences.
- Initializes a chat document with default values if it does not exist.
-
Functionality:
- Checks if a chat document exists in Firestore for the given
chatId
. - If the document is missing, creates it with default values, including
languages
fields for participants.
- Checks if a chat document exists in Firestore for the given
-
Code Snippet:
export const ensureChatLanguage = async ( chatId: string, currentUserId: string, recipientId: string ) => { const chatDocRef = doc(db, "chats", chatId); const chatDoc = await getDoc(chatDocRef); if (!chatDoc.exists()) { await setDoc(chatDocRef, { participants: [currentUserId, recipientId], isGroupChat: false, createdAt: Timestamp.now(), languages: { [currentUserId]: null, [recipientId]: null, }, }); return { userLanguage: null, recipientLanguage: null }; } const data = chatDoc.data(); return { userLanguage: data?.languages?.[currentUserId] || null, recipientLanguage: data?.languages?.[recipientId] || null, }; };
-
Process:
- Fetches the chat document using
getDoc
. - If missing, creates a new document with default
languages
fields. - Returns the current language preferences for the user and recipient.
- Fetches the chat document using
- Updates the preferred language of a specific user in a chat.
-
Functionality:
- Updates the
languages
field of a chat document for a specifieduserId
.
- Updates the
-
Code Snippet:
export const setChatLanguage = async ( chatId: string, userId: string, selectedLanguage: string ) => { const chatDocRef = doc(db, "chats", chatId); try { await setDoc( chatDocRef, { languages: { [userId]: selectedLanguage } }, { merge: true } ); return selectedLanguage; } catch (error) { console.error("Error updating chat language:", error); throw error; } };
-
Process:
- Updates the
languages
field in the chat document usingsetDoc
withmerge: true
. - Returns the updated language.
- Updates the
- Translates a given text to a specified target language using the LibreTranslate API.
-
Functionality:
- Converts the target language name to its ISO code if needed.
- Sends a request to the LibreTranslate API with the source text and language codes.
- Returns the translated text from the API response.
-
Code Snippet:
export const translateText = async ( text: string, targetLanguage: string, sourceLanguage: string = "auto" ): Promise<string> => { const targetLangCode = languageCodes[targetLanguage] || targetLanguage; const requestData = { q: text, source: sourceLanguage, target: targetLangCode, api_key: "6b35d883-0347-4e33-8e04-a7097c5f0e6a", format: "text", }; try { const response = await axios.post<TranslationResponse>( "https://libretranslate.com/translate", requestData, { headers: { "Content-Type": "application/json" } } ); return response.data.translatedText; } catch (error) { console.error("Error translating text:", error); throw new Error("Translation failed"); } };
-
Process:
- Uses
languageCodes
to convert language names to ISO codes. - Sends a POST request to the LibreTranslate API with the text and language parameters.
- Handles and logs errors, throwing a generic "Translation failed" error if unsuccessful.
- Uses
Function | Description |
---|---|
ensureChatLanguage |
Ensures a chat document exists with language fields, initializing if needed. |
setChatLanguage |
Sets a user's preferred language in a chat document. |
translateText |
Translates text to a target language using the LibreTranslate API. |
languageCodes |
Maps language names to ISO codes (e.g., "English" -> "en"). |
- Logs errors for debugging and provides fallback responses where necessary.
- Handles API errors and throws a user-friendly "Translation failed" message if translation fails.
- Relies on Firestore's real-time capabilities for consistent data updates.
- Translation requests are always fresh; consider caching frequent translations to optimize API usage.
For more information about LibreTranslate, visit the LibreTranslate Documentation. For Firebase Firestore, refer to the Firebase Documentation.