1+ package com.anysoftkeyboard.janus.network
2+
3+ import com.anysoftkeyboard.janus.database.TranslationDao
4+ import com.anysoftkeyboard.janus.database.Translation
5+
6+ class TranslationRepository (private val wikipediaApi : WikipediaApi , private val translationDao : TranslationDao ) {
7+
8+ suspend fun getTranslation (sourceWord : String , sourceLang : String , targetLang : String ): Translation ? {
9+ // First, try to get the translation from the database
10+ val cachedTranslation = translationDao.findTranslation(sourceWord, sourceLang, targetLang)
11+ if (cachedTranslation != null ) {
12+ return cachedTranslation
13+ }
14+
15+ // If not found in the database, fetch from the network
16+ return try {
17+ val searchResponse = wikipediaApi.search(sourceWord)
18+ val searchResult = searchResponse.query.search.firstOrNull()
19+
20+ if (searchResult != null ) {
21+ val newTranslation = Translation (
22+ sourceWord = sourceWord,
23+ sourceLangCode = sourceLang,
24+ sourceArticleUrl = " https://en.wikipedia.org/wiki/${searchResult.title} " ,
25+ sourceShortDescription = searchResult.snippet,
26+ sourceSummary = null , // Wikipedia search API does not provide full summary
27+ translatedWord = searchResult.title, // For now, assume translated word is the article title
28+ targetLangCode = targetLang,
29+ targetArticleUrl = " https://en.wikipedia.org/wiki/${searchResult.title} " ,
30+ targetShortDescription = searchResult.snippet,
31+ targetSummary = null
32+ )
33+ translationDao.insertTranslation(newTranslation)
34+ newTranslation
35+ } else {
36+ null
37+ }
38+ } catch (e: Exception ) {
39+ e.printStackTrace()
40+ null
41+ }
42+ }
43+ }
0 commit comments