std::string Translator::detect(std::string text) { std::string myLang = ""; _curlBuffer = ""; std::string request = "https://translate.yandex.net/api/v1.5/tr.json/detect?key="; request += getApiKey(); request += "&text="; request += text; curl_easy_setopt(curl, CURLOPT_URL, request.c_str()); CURLcode res = curl_easy_perform(curl); if(res != CURLE_OK) { // error return ""; } Json::Reader reader; Json::Value root; reader.parse(_curlBuffer, root); myLang = root["lang"].asString(); return myLang; }
Translator::Langs Translator::getLangs() const { _curlBuffer = ""; Translator::Langs langs; std::string mylang = getMyLang(); if(mylang.empty()) mylang = "en"; // default std::string url = "https://translate.yandex.net/api/v1.5/tr.json/getLangs?key="; url += getApiKey(); url += "&ui="; url += mylang; curl_easy_setopt(curl, CURLOPT_URL, url.c_str());; CURLcode res = curl_easy_perform(curl); if(res != CURLE_OK) { // error } Json::Reader reader; Json::Value root; reader.parse(_curlBuffer, root); for(Json::ValueIterator it = root["langs"].begin(); it != root["langs"].end(); it++) { langs.push_back(std::make_pair( it.key().asString(), // key (*it).asString() // value )); } return langs; }
std::string Translator::translate(std::string from, std::string to, std::string text) { std::string result = ""; CURLcode res; _curlBuffer = ""; std::string request = "https://translate.yandex.net/api/v1.5/tr.json/translate?key="; request += getApiKey(); request += "&lang="; request += from+"-"+to; request += "&text="+text; curl_easy_setopt(curl, CURLOPT_URL, request.c_str()); res = curl_easy_perform(curl); if(res != CURLE_OK) { // fix this curl_easy_cleanup(curl); return ""; } Json::Reader reader; Json::Value root; reader.parse(_curlBuffer, root); for(int i = 0; i < root["text"].size(); i++) result += root["text"][i].asString()+" "; return result; }
void Exchange_BitCurex::sendToApi(int reqType, QByteArray method, bool auth, QByteArray hashData, QByteArray postData) { if(julyHttp==0) { julyHttp=new JulyHttp("api.bitcurex.com","Key: "+getApiKey()+"\r\n",this,true); connect(julyHttp,SIGNAL(anyDataReceived()),baseValues_->mainWindow_,SLOT(anyDataReceived())); connect(julyHttp,SIGNAL(apiDown(bool)),baseValues_->mainWindow_,SLOT(setApiDown(bool))); connect(julyHttp,SIGNAL(setDataPending(bool)),baseValues_->mainWindow_,SLOT(setDataPending(bool))); connect(julyHttp,SIGNAL(errorSignal(QString)),baseValues_->mainWindow_,SLOT(showErrorMessage(QString))); connect(julyHttp,SIGNAL(sslErrorSignal(const QList<QSslError> &)),this,SLOT(sslErrors(const QList<QSslError> &))); connect(julyHttp,SIGNAL(dataReceived(QByteArray,int)),this,SLOT(dataReceivedAuth(QByteArray,int))); }
void Exchange_BitMarket::sendToApi(int reqType, QByteArray method, bool auth, bool sendNow) { if(julyHttp==0) { julyHttp=new JulyHttp("www.bitmarket.pl","API-Key: "+getApiKey()+"\r\n",this); connect(julyHttp,SIGNAL(anyDataReceived()),baseValues_->mainWindow_,SLOT(anyDataReceived())); connect(julyHttp,SIGNAL(apiDown(bool)),baseValues_->mainWindow_,SLOT(setApiDown(bool))); connect(julyHttp,SIGNAL(setDataPending(bool)),baseValues_->mainWindow_,SLOT(setDataPending(bool))); connect(julyHttp,SIGNAL(errorSignal(QString)),baseValues_->mainWindow_,SLOT(showErrorMessage(QString))); connect(julyHttp,SIGNAL(sslErrorSignal(const QList<QSslError> &)),this,SLOT(sslErrors(const QList<QSslError> &))); connect(julyHttp,SIGNAL(dataReceived(QByteArray,int)),this,SLOT(dataReceivedAuth(QByteArray,int))); }
void checkWeatherUpdate() { APP_LOG(APP_LOG_LEVEL_DEBUG, "> checkWeatherUpdate"); char* apiKey = getApiKey(); if (apiKey == NULL) { APP_LOG(APP_LOG_LEVEL_WARNING, "< checkWeatherUpdate - No api key to send."); return; } if (!isJsReady()) { APP_LOG(APP_LOG_LEVEL_WARNING, "< checkWeatherUpdate - PebbleKit JS is not yet ready."); return; } bool weatherUpdateNecessary = false; if (weatherConfigChanged()) { weatherUpdateNecessary = true; APP_LOG(APP_LOG_LEVEL_DEBUG, "Weather update necessary due to config change."); } else { unsigned int diff = time(NULL) - getLastWeatherUpdate(); unsigned int maxDiff = 60 * getUpdateFrequencyInMinutes(); if (diff >= maxDiff) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Last update was %i seconds ago > configured maximum %i. Updating.", diff, maxDiff); weatherUpdateNecessary = true; } } if (weatherUpdateNecessary) { // Begin dictionary DictionaryIterator *iter; AppMessageResult result = app_message_outbox_begin(&iter); if(result == APP_MSG_OK) { // Construct the message - add a key-value pair APP_LOG(APP_LOG_LEVEL_DEBUG, "Sending api key."); dict_write_cstring(iter, MESSAGE_KEY_OWM_APPID, apiKey); int value = useCelsius() ? 1 : 0; dict_write_int(iter, MESSAGE_KEY_UNIT_TEMP, &value, sizeof(int), true); int localeValue = getWeatherLocale(); dict_write_int(iter, MESSAGE_KEY_WEATHER_LOCALE, &localeValue, sizeof(int), true); // Send the message! app_message_outbox_send(); } else { // The outbox cannot be used right now APP_LOG(APP_LOG_LEVEL_ERROR, "Error preparing the outbox: %d", (int)result); } } APP_LOG(APP_LOG_LEVEL_DEBUG, "< checkWeatherUpdate"); }
void Exchange_BTCChina::sendToApi(int reqType, QByteArray method, bool auth, bool sendNow, QByteArray commands) { if(auth) { if(julyHttpAuth==0) { julyHttpAuth=new JulyHttp("api.btcchina.com","",this,true,true,"application/json-rpc"); connect(julyHttpAuth,SIGNAL(anyDataReceived()),baseValues_->mainWindow_,SLOT(anyDataReceived())); connect(julyHttpAuth,SIGNAL(setDataPending(bool)),baseValues_->mainWindow_,SLOT(setDataPending(bool))); connect(julyHttpAuth,SIGNAL(apiDown(bool)),baseValues_->mainWindow_,SLOT(setApiDown(bool))); connect(julyHttpAuth,SIGNAL(errorSignal(QString)),baseValues_->mainWindow_,SLOT(showErrorMessage(QString))); connect(julyHttpAuth,SIGNAL(sslErrorSignal(const QList<QSslError> &)),this,SLOT(sslErrors(const QList<QSslError> &))); connect(julyHttpAuth,SIGNAL(dataReceived(QByteArray,int)),this,SLOT(dataReceivedAuth(QByteArray,int))); } QByteArray signatureParams; signatureParams=commands; signatureParams.replace("\"",""); signatureParams.replace("true","1"); signatureParams.replace("false",""); QByteArray postData; QByteArray appendedHeader; static int tonceCounter=0; static quint32 lastTonce=QDateTime::currentDateTime().toTime_t(); quint32 newTonce=QDateTime::currentDateTime().toTime_t(); if(lastTonce!=newTonce) { tonceCounter=0; lastTonce=newTonce; } else { tonceCounter+=10; if(tonceCounter>99)tonceCounter=0; } QByteArray tonceCounterData=QByteArray::number(tonceCounter); if(tonceCounter>9)tonceCounterData.append("0000"); else tonceCounterData.append("00000"); QByteArray tonce=QByteArray::number(newTonce)+tonceCounterData; QByteArray signatureString="tonce="+tonce+"&accesskey="+getApiKey()+"&requestmethod=post&id=1&method="+method+"¶ms="+signatureParams; signatureString=getApiKey()+":"+hmacSha1(getApiSign(),signatureString).toHex(); if(debugLevel&&reqType>299)logThread->writeLog(postData); postData="{\"method\":\""+method+"\",\"params\":["+commands+"],\"id\":1}"; appendedHeader="Authorization: Basic "+signatureString.toBase64()+"\r\n"; appendedHeader+="Json-Rpc-Tonce: "+tonce+"\r\n"; if(sendNow) julyHttpAuth->sendData(reqType, "POST /api_trade_v1.php",postData,appendedHeader); else julyHttpAuth->prepareData(reqType, "POST /api_trade_v1.php",postData,appendedHeader); }
// The 'self' parameter is for keeping the current Group object alive while this thread is running. void Group::spawnThreadOOBWRequest(GroupPtr self, ProcessPtr process) { TRACE_POINT(); boost::this_thread::disable_interruption di; boost::this_thread::disable_syscall_interruption dsi; Socket *socket; Connection connection; Pool *pool = getPool(); Pool::DebugSupportPtr debug = pool->debugSupport; UPDATE_TRACE_POINT(); P_DEBUG("Performing OOBW request for process " << process->inspect()); if (debug != NULL && debug->oobw) { debug->debugger->send("OOBW request about to start"); debug->messages->recv("Proceed with OOBW request"); } UPDATE_TRACE_POINT(); { // Standard resource management boilerplate stuff... boost::unique_lock<boost::mutex> lock(pool->syncher); if (OXT_UNLIKELY(!process->isAlive() || process->enabled == Process::DETACHED || !isAlive())) { return; } if (process->enabled != Process::DISABLED) { UPDATE_TRACE_POINT(); P_INFO("Out-of-Band Work canceled: process " << process->inspect() << " was concurrently re-enabled."); if (debug != NULL && debug->oobw) { debug->debugger->send("OOBW request canceled"); } return; } assert(process->oobwStatus == Process::OOBW_IN_PROGRESS); assert(process->sessions == 0); socket = process->findSessionSocketWithLowestBusyness(); } UPDATE_TRACE_POINT(); unsigned long long timeout = 1000 * 1000 * 60; // 1 min try { boost::this_thread::restore_interruption ri(di); boost::this_thread::restore_syscall_interruption rsi(dsi); // Grab a connection. The connection is marked as fail in order to // ensure it is closed / recycled after this request (otherwise we'd // need to completely read the response). connection = socket->checkoutConnection(); connection.fail = true; ScopeGuard guard(boost::bind(&Socket::checkinConnection, socket, connection)); // This is copied from Core::Controller when it is sending data using the // "session" protocol. char sizeField[sizeof(boost::uint32_t)]; SmallVector<StaticString, 10> data; data.push_back(StaticString(sizeField, sizeof(boost::uint32_t))); data.push_back(P_STATIC_STRING_WITH_NULL("REQUEST_METHOD")); data.push_back(P_STATIC_STRING_WITH_NULL("OOBW")); data.push_back(P_STATIC_STRING_WITH_NULL("PASSENGER_CONNECT_PASSWORD")); data.push_back(getApiKey().toStaticString()); data.push_back(StaticString("", 1)); boost::uint32_t dataSize = 0; for (unsigned int i = 1; i < data.size(); i++) { dataSize += (boost::uint32_t) data[i].size(); } Uint32Message::generate(sizeField, dataSize); gatheredWrite(connection.fd, &data[0], data.size(), &timeout); // We do not care what the actual response is ... just wait for it. UPDATE_TRACE_POINT(); waitUntilReadable(connection.fd, &timeout); } catch (const SystemException &e) { P_ERROR("*** ERROR: " << e.what() << "\n" << e.backtrace()); } catch (const TimeoutException &e) { P_ERROR("*** ERROR: " << e.what() << "\n" << e.backtrace()); } UPDATE_TRACE_POINT(); boost::container::vector<Callback> actions; { // Standard resource management boilerplate stuff... Pool *pool = getPool(); boost::unique_lock<boost::mutex> lock(pool->syncher); if (OXT_UNLIKELY(!process->isAlive() || !isAlive())) { return; } process->oobwStatus = Process::OOBW_NOT_ACTIVE; if (process->enabled == Process::DISABLED) { enable(process, actions); assignSessionsToGetWaiters(actions); } pool->fullVerifyInvariants(); initiateNextOobwRequest(); } UPDATE_TRACE_POINT(); runAllActions(actions); actions.clear(); UPDATE_TRACE_POINT(); P_DEBUG("Finished OOBW request for process " << process->inspect()); if (debug != NULL && debug->oobw) { debug->debugger->send("OOBW request finished"); } }