| 295 | } |
| 296 | |
| 297 | void TranslationLoader::run() |
| 298 | { |
| 299 | QNetworkAccessManager manager; |
| 300 | QEventLoop q; |
| 301 | QTimer tT; |
| 302 | |
| 303 | tT.setSingleShot(true); |
| 304 | connect(&tT, &QTimer::timeout, &q, &QEventLoop::quit); |
| 305 | connect(&manager, &QNetworkAccessManager::finished, &q, &QEventLoop::quit); |
| 306 | |
| 307 | QString urlStr = QString("https://api.mymemory.translated.net/get?q=%1&langpair=%2|%3") |
| 308 | .arg(QString::fromUtf8(QUrl::toPercentEncoding(text)), from, to); |
| 309 | |
| 310 | QNetworkReply *reply = manager.get(QNetworkRequest(QUrl(urlStr))); |
| 311 | |
| 312 | tT.start(5000); // 5s timeout |
| 313 | q.exec(); |
| 314 | |
| 315 | if (tT.isActive()) { |
| 316 | // download complete |
| 317 | if (reply->error() == QNetworkReply::NoError) { |
| 318 | QJsonDocument doc = QJsonDocument::fromJson(reply->readAll()); |
| 319 | QString translated = doc["responseData"]["translatedText"].toString(); |
| 320 | if (!translated.isEmpty()) |
| 321 | emit requestFinished(translated); |
| 322 | else |
| 323 | emit error(); |
| 324 | } else |
| 325 | emit error(); |
| 326 | } else { |
| 327 | emit timeOut(); |
| 328 | } |
| 329 | } |