bool SarClient::createEndpoints()
{
    int i = 0;
    DWORD dummy;

    for (auto& endpoint : _driverConfig.endpoints) {
        SarCreateEndpointRequest request = {};

        request.type = endpoint.type == EndpointType::Playback ?
            SAR_ENDPOINT_TYPE_PLAYBACK : SAR_ENDPOINT_TYPE_RECORDING;
        request.channelCount = endpoint.channelCount;
        request.index = i++;
        wcscpy_s(request.name, UTF8ToWide(endpoint.description).c_str());
        wcscpy_s(request.id, UTF8ToWide(endpoint.id).c_str());

        if (!DeviceIoControl(_device, SAR_CREATE_ENDPOINT,
            (LPVOID)&request, sizeof(request), nullptr, 0, &dummy, nullptr)) {

            std::ostringstream os;

            os << "Endpoint creation for " << endpoint.description
               << " failed.";
            OutputDebugStringA(os.str().c_str());
            return false;
        }
    }

    return true;
}
Esempio n. 2
0
 SNumeral2Number(const char* cardinal, const char* ordinal, const char* adverb, const char* noun, ui64 integer, int fract)
     : m_Cardinal(UTF8ToWide(cardinal))
     , m_Ordinal(UTF8ToWide(ordinal))
     , m_Adverb(UTF8ToWide(adverb))
     , m_Noun(UTF8ToWide(noun))
     , m_Integer(integer)
     , m_Fractional(fract)
 {
 }
Esempio n. 3
0
bool
GMPProcessParent::Launch(int32_t aTimeoutMs)
{
  nsCOMPtr<nsIFile> path;
  if (!GetEMEVoucherPath(getter_AddRefs(path))) {
    NS_WARNING("GMPProcessParent can't get EME voucher path!");
    return false;
  }
  nsAutoCString voucherPath;
  path->GetNativePath(voucherPath);

  vector<string> args;

#if defined(XP_WIN) && defined(MOZ_SANDBOX)
  std::wstring wGMPPath = UTF8ToWide(mGMPPath.c_str());

  // The sandbox doesn't allow file system rules where the paths contain
  // symbolic links or junction points. Sometimes the Users folder has been
  // moved to another drive using a junction point, so allow for this specific
  // case. See bug 1236680 for details.
  if (!widget::WinUtils::ResolveMovedUsersFolder(wGMPPath)) {
    NS_WARNING("ResolveMovedUsersFolder failed for GMP path.");
    return false;
  }
  mAllowedFilesRead.push_back(wGMPPath + L"\\*");
  args.push_back(WideToUTF8(wGMPPath));
#else
  args.push_back(mGMPPath);
#endif

  args.push_back(string(voucherPath.BeginReading(), voucherPath.EndReading()));

  return SyncLaunch(args, aTimeoutMs, base::GetCurrentProcessArchitecture());
}
static std::string getProductName(const std::string& path)
{
    auto wpath = UTF8ToWide(path);
    auto verLength = GetFileVersionInfoSize(wpath.c_str(), nullptr);

    if (!verLength) {
        return "";
    }

    auto buffer = malloc(verLength);

    if (!GetFileVersionInfo(wpath.c_str(), 0, verLength, buffer)) {
        free(buffer);
        return "";
    }

    struct LANGANDCODEPAGE
    {
        WORD language;
        WORD codePage;
    } *translations;
    UINT translationsLength, nameLength;
    WCHAR subBlockName[50];
    WCHAR *neutralSubBlock = L"\\StringFileInfo\\00000000\\FileDescription";
    WCHAR *name;

    if (!VerQueryValue(buffer, L"\\VarFileInfo\\Translation",
        (void **)&translations, &translationsLength)) {

        free(buffer);
        return "";
    }

    if (translationsLength < sizeof(LANGANDCODEPAGE)) {
        free(buffer);
        return "";
    }

    // TODO: try current locale/codepage
    if (!VerQueryValue(buffer, neutralSubBlock, (void **)&name, &nameLength)) {
        _snwprintf_s(subBlockName, _TRUNCATE,
            L"\\StringFileInfo\\%04x%04x\\FileDescription",
            translations[0].language, translations[0].codePage);

        if (!VerQueryValue(buffer, subBlockName, (void **)&name, &nameLength)) {
            free(buffer);
            return "";
        }
    }

    std::string result = TCHARToUTF8(name);

    free(buffer);
    return result;
}
void CParserOptions::InitFromConfigObject(const TTextMinerConfig& config) {
    for (int i = 0; i < config.facts_size(); ++i) {
        TTextMinerConfig::TFactTypeRef ref = config.get_idx_facts(i);
        AddFactToShow(ref.name(), ref.nonequality());
    }

    for (int i = 0; i < config.articles_size(); ++i) {
        TTextMinerConfig::TArticleRef ref = config.get_idx_articles(i);
        AddArticle(UTF8ToWide(ref.name()));
    }

    for (int i = 0; i < config.situations_size(); ++i) {
        TTextMinerConfig::TArticleRef ref = config.get_idx_situations(i);
        AddSituation(UTF8ToWide(ref.name()));
    }

    SetIgnoreUpperCase(config.GetIgnoreUpperCase());

    m_maxNamesCount = config.GetMaxNamesCount();
}
Esempio n. 6
0
bool
GMPProcessParent::Launch(int32_t aTimeoutMs)
{
  vector<string> args;
  args.push_back(mGMPPath);

#if defined(XP_WIN) && defined(MOZ_SANDBOX)
  std::wstring wGMPPath = UTF8ToWide(mGMPPath.c_str());
  mAllowedFilesRead.push_back(wGMPPath + L"\\*");
#endif

  return SyncLaunch(args, aTimeoutMs, base::GetCurrentProcessArchitecture());
}
	void Win32TrayItem::SetHint(std::string& hint)
	{
		if (this->trayIconData)
		{
			// NotifyIconData.szTip has 128 character limit.
			ZeroMemory(this->trayIconData->szTip, 128);

			// make sure we don't overflow the static buffer.
			std::wstring hintW = UTF8ToWide(hint);
			lstrcpyn(this->trayIconData->szTip, hintW.c_str(), 128);

			Shell_NotifyIcon(NIM_MODIFY, this->trayIconData);
		}
	}
std::string ConfigurationPath(const std::string& name)
{
    TCHAR path[MAX_PATH];

    if (SUCCEEDED(SHGetFolderPath(
        nullptr, CSIDL_APPDATA, nullptr, 0, path))) {

        PathAppend(path, TEXT("\\SynchronousAudioRouter\\"));
        CreateDirectory(path, nullptr);
        PathAppend(path, UTF8ToWide(name).c_str());
    }

    return TCHARToUTF8(path);
}
Esempio n. 9
0
    // 在致命(fatal)消息时显示错误消息框给用户, 同时关闭应用程序.
    void DisplayDebugMessageInDialog(const std::string& str)
    {
        if(str.empty())
        {
            return;
        }

        if(!show_error_dialogs)
        {
            return;
        }

        // 对于Windows程序显示MessageBox会导致消息循环, 有可能引起更多的严重错误.
        // 所以首先尝试通过其他进程来显示错误消息. 在相同目录下查找
        // "debug_message.exe"程序, 如果存在我们用它来显示错误消息; 否则使用常规
        // 方式弹出MessageBox.
        wchar_t prog_name[MAX_PATH];
        GetModuleFileNameW(NULL, prog_name, MAX_PATH);
        wchar_t* backslash = wcsrchr(prog_name, '\\');
        if(backslash)
        {
            backslash[1] = 0;
        }
        wcscat_s(prog_name, MAX_PATH, L"debug_message.exe");

        std::wstring cmdline = UTF8ToWide(str);
        if(cmdline.empty())
        {
            return;
        }

        STARTUPINFO startup_info;
        memset(&startup_info, 0, sizeof(startup_info));
        startup_info.cb = sizeof(startup_info);

        PROCESS_INFORMATION process_info;
        if(CreateProcessW(prog_name, &cmdline[0], NULL, NULL, false, 0, NULL,
            NULL, &startup_info, &process_info))
        {
            WaitForSingleObject(process_info.hProcess, INFINITE);
            CloseHandle(process_info.hThread);
            CloseHandle(process_info.hProcess);
        }
        else
        {
            // debug process broken, let's just do a message box
            MessageBoxW(NULL, &cmdline[0], L"Fatal error", MB_OK|MB_ICONHAND|MB_TOPMOST);
        }
    }
Esempio n. 10
0
	void SnarlWin32::ShowNotification(std::string& title, std::string& description,
		std::string& iconURL, int timeout, KMethodRef callback)
	{
		SnarlInterface snarlInterface;

		std::wstring wideTitle = UTF8ToWide(title);
		std::wstring wideText = UTF8ToWide(description);
		std::wstring wideIconPath(L"");
		if (!iconURL.empty())
		{
			std::string iconPath = URLUtils::URLToPath(iconURL);
			wideIconPath.append(UTF8ToWide(iconPath));
		}

		HWND replyWindow = Win32Host::Win32Instance()->AddMessageHandler(
			&SnarlWin32::MessageHandler);
		long id = snarlInterface.snShowMessage(wideTitle, wideText, timeout,
			wideIconPath, replyWindow, SnarlWin32::snarlWindowMessage);

		if (!callback.isNull())
		{
			SnarlWin32::snarlCallbacks[id] = callback;
		}
	}
    bool ClipboardUtil::GetUrl(IDataObject* data_object, std::wstring* url,
        std::wstring* title, bool convert_filenames)
    {
        DCHECK(data_object && url && title);
        if(!HasUrl(data_object))
        {
            return false;
        }

        // 尝试从|data_object|的多种格式中提取URL.
        STGMEDIUM store;
        if(GetUrlFromHDrop(data_object, url, title))
        {
            return true;
        }

        if(SUCCEEDED(data_object->GetData(GetMozUrlFormat(), &store)) ||
            SUCCEEDED(data_object->GetData(GetUrlWFormat(), &store)))
        {
            {
                // Mozilla URL格式或者unicode URL.
                base::win::ScopedHGlobal<wchar_t> data(store.hGlobal);
                SplitUrlAndTitle(data.get(), url, title);
            }
            ReleaseStgMedium(&store);
            return true;
        }

        if(SUCCEEDED(data_object->GetData(GetUrlFormat(), &store)))
        {
            {
                // URL使用ascii.
                base::win::ScopedHGlobal<char> data(store.hGlobal);
                SplitUrlAndTitle(UTF8ToWide(data.get()), url, title);
            }
            ReleaseStgMedium(&store);
            return true;
        }

        if(convert_filenames)
        {
            return GetFileUrl(data_object, url, title);
        }
        else
        {
            return false;
        }
    }
Esempio n. 12
0
Value* JSONReader::JsonToValue(const std::string& json, bool check_root,
                               bool allow_trailing_comma)
{
    // 输入必须是UTF-8编码.
    if(!IsStringUTF8(json.c_str()))
    {
        error_code_ = JSON_UNSUPPORTED_ENCODING;
        return NULL;
    }

    // 从UTF8到wstring的转换会移除空字节(好事).
    std::wstring json_wide(UTF8ToWide(json));
    start_pos_ = json_wide.c_str();

    // 当输入的JSON字符串开头有UTF-8的Byte-Order-Mark(0xEF, 0xBB, 0xBF),
    // UTF8ToWide()函数会把它转换成BOM(U+FEFF). 为防止JSONReader::BuildValue()
    // 函数把它当成非法字符而返回NULL, 如果存在Unicode的BOM则先跳过.
    if(!json_wide.empty() && start_pos_[0]==0xFEFF)
    {
        ++start_pos_;
    }

    json_pos_ = start_pos_;
    allow_trailing_comma_ = allow_trailing_comma;
    stack_depth_ = 0;
    error_code_ = JSON_NO_ERROR;

    scoped_ptr<Value> root(BuildValue(check_root));
    if(root.get())
    {
        if(ParseToken().type == Token::END_OF_INPUT)
        {
            return root.release();
        }
        else
        {
            SetErrorCode(JSON_UNEXPECTED_DATA_AFTER_ROOT, json_pos_);
        }
    }

    // "语法错误".
    if(error_code_ == 0)
    {
        SetErrorCode(JSON_SYNTAX_ERROR, json_pos_);
    }

    return NULL;
}
Esempio n. 13
0
bool
GMPProcessParent::Launch(int32_t aTimeoutMs)
{
  nsCOMPtr<nsIFile> path;
  if (!GetEMEVoucherPath(getter_AddRefs(path))) {
    NS_WARNING("GMPProcessParent can't get EME voucher path!");
    return false;
  }
  nsAutoCString voucherPath;
  path->GetNativePath(voucherPath);

  vector<string> args;
  args.push_back(mGMPPath);
  args.push_back(string(voucherPath.BeginReading(), voucherPath.EndReading()));

#if defined(XP_WIN) && defined(MOZ_SANDBOX)
  std::wstring wGMPPath = UTF8ToWide(mGMPPath.c_str());
  mAllowedFilesRead.push_back(wGMPPath + L"\\*");
#endif

  return SyncLaunch(args, aTimeoutMs, base::GetCurrentProcessArchitecture());
}
    bool ClipboardUtil::GetHtml(IDataObject* data_object, std::wstring* html,
        std::string* base_url)
    {
        DCHECK(data_object && html && base_url);

        STGMEDIUM store;
        if(SUCCEEDED(data_object->QueryGetData(GetHtmlFormat())) &&
            SUCCEEDED(data_object->GetData(GetHtmlFormat(), &store)))
        {
            {
                // MS CF html
                base::win::ScopedHGlobal<char> data(store.hGlobal);

                std::string html_utf8;
                CFHtmlToHtml(std::string(data.get(), data.Size()), &html_utf8, base_url);
                html->assign(UTF8ToWide(html_utf8));
            }
            ReleaseStgMedium(&store);
            return true;
        }

        if(FAILED(data_object->QueryGetData(GetTextHtmlFormat())))
        {
            return false;
        }

        if(FAILED(data_object->GetData(GetTextHtmlFormat(), &store)))
        {
            return false;
        }

        {
            // text/html
            base::win::ScopedHGlobal<wchar_t> data(store.hGlobal);
            html->assign(data.get());
        }
        ReleaseStgMedium(&store);
        return true;
    }
Esempio n. 15
0
	Win32Sound::Win32Sound(std::string &url) :
		Sound(url),
		path(UTF8ToWide(URLUtils::URLToPath(url))),
		graphBuilder(NULL),
		mediaControl(NULL),
		mediaEventEx(NULL),
		mediaSeeking(NULL)
	{
		HRESULT hr;

		hr = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
			IID_IGraphBuilder, (void **) &graphBuilder);
		if (FAILED(hr))
			throw ValueException::FromString("Failed creating Graph Builder for sound");

		hr = graphBuilder->QueryInterface(IID_IBasicAudio, (void**) &basicAudio);
		if (FAILED(hr))
			throw ValueException::FromString("Failed querying IBasicAudio for sound");

		hr = graphBuilder->QueryInterface(IID_IMediaControl, (void **) &mediaControl);
		if (FAILED(hr))
			throw ValueException::FromString("Failed querying IMediaControl for sound");

		hr = graphBuilder->QueryInterface(IID_IMediaEventEx, (void **) &mediaEventEx);
		if (FAILED(hr))
			throw ValueException::FromString("Failed querying IMediaEventEx for sound");

		hr = graphBuilder->QueryInterface(IID_IMediaSeeking, (void **) &mediaSeeking);
		if (FAILED(hr))
			throw ValueException::FromString("Failed querying IMediaSeeking for sound");

		HWND hwnd = Win32Host::Win32Instance()->AddMessageHandler(
			&Win32Sound::StaticGraphCallback);
		mediaEventEx->SetNotifyWindow((OAHWND) hwnd, graphNotifyMessage,
			reinterpret_cast<LONG_PTR>(this));

		this->Load();
	}
Esempio n. 16
0
Module* Host::CreateModule(std::string& path)
{
    std::wstring widePath(UTF8ToWide(path));
    HMODULE module = LoadLibraryExW(widePath.c_str(),
                                    NULL, LOAD_WITH_ALTERED_SEARCH_PATH);

    if (!module)
    {
        throw ValueException::FromFormat("Error loading module (%d): %s: %s\n",
                                         GetLastError(), path.c_str(),
                                         Win32Utils::QuickFormatMessage(GetLastError()).c_str());
    }

    // get the module factory
    ModuleCreator* create = (ModuleCreator*)GetProcAddress(module, "CreateModule");
    if (!create)
    {
        throw ValueException::FromFormat(
            "Couldn't find ModuleCreator entry point for %s\n", path.c_str());
    }

    return create(this, FileUtils::GetDirectory(path).c_str());
}
    bool ClipboardUtil::GetPlainText(IDataObject* data_object,
        std::wstring* plain_text)
    {
        DCHECK(data_object && plain_text);
        if(!HasPlainText(data_object))
        {
            return false;
        }

        STGMEDIUM store;
        if(SUCCEEDED(data_object->GetData(GetPlainTextWFormat(), &store)))
        {
            {
                // Unicode文本.
                base::win::ScopedHGlobal<wchar_t> data(store.hGlobal);
                plain_text->assign(data.get());
            }
            ReleaseStgMedium(&store);
            return true;
        }

        if(SUCCEEDED(data_object->GetData(GetPlainTextFormat(), &store)))
        {
            {
                // ascii文本.
                base::win::ScopedHGlobal<char> data(store.hGlobal);
                plain_text->assign(UTF8ToWide(data.get()));
            }
            ReleaseStgMedium(&store);
            return true;
        }

        // 如果是window平台上拖放的文件, 没有提供任何类型的普通文本格式, 所以
        // 这里我们尝试强行获取一个url.
        std::wstring title;
        return GetUrl(data_object, plain_text, &title, false);
    }
Esempio n. 18
0
tstring UTF8ToString(const std::string& string) {return UTF8ToWide(string);}
Esempio n. 19
0
tstring UTF8ToString(const std::string& string) {return WideToMultibyte(UTF8ToWide(string));}
Esempio n. 20
0
bool UTF8ToWide(const char* utf8, std::wstring* utf16) {
  // Compute string length of NULL-terminated string with strlen().
  return UTF8ToWide(utf8, strlen(utf8), utf16);
}
Esempio n. 21
0
Wtroka ClauseType2Str(EClauseType ClauseType)
{
    YASSERT(ClauseType >= 0 && ClauseType < ClauseTypesCount);
    return UTF8ToWide(ClauseTypeNames[ClauseType]);
}
Esempio n. 22
0
	// This method will return true if we should keep attempting to use a proxy
	// or false if the auto proxy determination was to use a direct connection.
	static bool GetAutoProxiesForURL(string& url, vector<SharedProxy>& proxies)
	{
		bool shouldUseProxy = true;
		WINHTTP_PROXY_INFO autoProxyInfo;
		ZeroMemory(&autoProxyInfo, sizeof(WINHTTP_PROXY_INFO)); 
		
		WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions;
		ZeroMemory(&autoProxyOptions, sizeof(WINHTTP_AUTOPROXY_OPTIONS)); 
		
		// This type of auto-detection might take several seconds, so
		// if the user specified  an autoconfiguration URL don't do it.
		// TODO: Maybe we should use this as a fallback later, but it's *very* expensive.
		if (autoConfigURL.empty() && useProxyAutoConfig)
		{
			autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT;
			autoProxyOptions.dwAutoDetectFlags = 
				WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A;
		}

		if (!autoConfigURL.empty())
		{
			autoProxyOptions.dwFlags |= WINHTTP_AUTOPROXY_CONFIG_URL;
			autoProxyOptions.lpszAutoConfigUrl = autoConfigURL.c_str();
		}
		
		// From Chromium:
		// Per http://msdn.microsoft.com/en-us/library/aa383153(VS.85).aspx, it is
		// necessary to first try resolving with fAutoLogonIfChallenged set to false.
		// Otherwise, we fail over to trying it with a value of true.  This way we
		// get good performance in the case where WinHTTP uses an out-of-process
		// resolver.  This is important for Vista and Win2k3.
		wstring wideURL = UTF8ToWide(url);
		autoProxyOptions.fAutoLogonIfChallenged = FALSE;
		BOOL ok = WinHttpGetProxyForUrl(
			httpSession.GetHandle(), wideURL.c_str(), &autoProxyOptions, &autoProxyInfo);

		if (!ok && ERROR_WINHTTP_LOGIN_FAILURE == GetLastError())
		{
			autoProxyOptions.fAutoLogonIfChallenged = TRUE;
			ok = WinHttpGetProxyForUrl(
				httpSession.GetHandle(), wideURL.c_str(), &autoProxyOptions, &autoProxyInfo);
		}
		
		if (ok && autoProxyInfo.dwAccessType == WINHTTP_ACCESS_TYPE_NAMED_PROXY &&
			 autoProxyInfo.lpszProxy)
		{
			// Only the first proxy in the list will get a copy of the bypass list.
			std::string bypassList;
			if (autoProxyInfo.lpszProxyBypass)
			{
				std::wstring bypassW = autoProxyInfo.lpszProxyBypass;
				bypassList = string(bypassW.begin(), bypassW.end());
			}

			std::wstring proxyListW = autoProxyInfo.lpszProxy;
			string proxyList = string(proxyListW.begin(), proxyListW.end());
			ParseProxyList(proxyList, bypassList, proxies);
		}
		else if (ok && autoProxyInfo.dwAccessType == WINHTTP_ACCESS_TYPE_NO_PROXY)
		{
			// The only case in which we do not continue to try using a proxy.
			// In this case the auto proxy setup told us to use a direct connection.
			shouldUseProxy = false;
		}
		else
		{
			// Auto proxy failed, so try another method
			string error = "Could not get proxy for url=";
			error.append(url);
			error.append(": ");
			error.append(ErrorCodeToString(GetLastError()));
			Logger::Get("Proxy")->Error(error);
		}
		
		// Always cleanup
		if (autoProxyInfo.lpszProxy)
			GlobalFree(autoProxyInfo.lpszProxy);
		if (autoProxyInfo.lpszProxyBypass)
			GlobalFree(autoProxyInfo.lpszProxyBypass);
		
		return shouldUseProxy;
	}
Esempio n. 23
0
bool TwitterProto::NegotiateConnection()
{
	debugLogA( _T("***** Negotiating connection with Twitter"));
	disconnectionCount = 0;

	// saving the current status to a temp var
	int old_status = m_iStatus;
	DBVARIANT dbv;

	wstring oauthToken;
	wstring oauthTokenSecret;	
	wstring oauthAccessToken;
	wstring oauthAccessTokenSecret;
	string screenName;

	INT_PTR dbTOK = db_get_ws(0,m_szModuleName,TWITTER_KEY_OAUTH_TOK,&dbv);
	if (!dbTOK) {
		oauthToken = dbv.pwszVal;
		db_free(&dbv);
		//debugLogW("**NegotiateConnection - we have an oauthToken already in the db - %s", oauthToken);
	}
 
	INT_PTR dbTOKSec = db_get_ws(0,m_szModuleName,TWITTER_KEY_OAUTH_TOK_SECRET,&dbv);
	if (!dbTOKSec) {
		oauthTokenSecret = dbv.pwszVal;
		db_free(&dbv);
		//debugLogW("**NegotiateConnection - we have an oauthTokenSecret already in the db - %s", oauthTokenSecret);
	}

	INT_PTR dbName = db_get_s(0,m_szModuleName,TWITTER_KEY_NICK,&dbv);
	if (!dbName) {
		screenName = dbv.pszVal;
		db_free(&dbv);
		//debugLogW("**NegotiateConnection - we have a username already in the db - %s", screenName);
	}
	else {
		dbName = db_get_s(0,m_szModuleName,TWITTER_KEY_UN,&dbv);
		if (!dbName) {
			screenName = dbv.pszVal;
			db_set_s(0,m_szModuleName,TWITTER_KEY_NICK,dbv.pszVal);
			db_free(&dbv);
			//debugLogW("**NegotiateConnection - we have a username already in the db - %s", screenName);
		}
	}

 	// twitter changed the base URL in v1.1 of the API, I don't think users will need to modify it, so
	// i'll be forcing it to the new API URL here. After a while I can get rid of this as users will
	// have either had this run at least once, or have reset their miranda profile. 14/10/2012
	if(db_get_b(0,m_szModuleName,"UpgradeBaseURL",1)) {
		db_set_s(0,m_szModuleName,TWITTER_KEY_BASEURL,"https://api.twitter.com/");
		db_set_b(0,m_szModuleName,"UpgradeBaseURL",0);
	}

	if((oauthToken.size() <= 1) || (oauthTokenSecret.size() <= 1)) {
		// first, reset all the keys so we can start fresh
		resetOAuthKeys();
		debugLogA( _T("**NegotiateConnection - Reset OAuth Keys"));

		//twit_.set_credentials(ConsumerKey, ConsumerSecret, oauthAccessToken, oauthAccessTokenSecret, L"", false);
		// i think i was doin the wrong thing here.. i was setting the credentials as oauthAccessToken instead of oauthToken
		// have to test..
		debugLogA( _T("**NegotiateConnection - Setting Consumer Keys..."));
		/*debugLogW("**NegotiateConnection - sending set_cred: consumerKey is %s", ConsumerKey);
		debugLogW("**NegotiateConnection - sending set_cred: consumerSecret is %s", ConsumerSecret);
		debugLogW("**NegotiateConnection - sending set_cred: oauthToken is %s", oauthToken);
		debugLogW("**NegotiateConnection - sending set_cred: oauthTokenSecret is %s", oauthTokenSecret);
		debugLogA("**NegotiateConnection - sending set_cred: no pin");*/
		twit_.set_credentials("", ConsumerKey, ConsumerSecret, oauthToken, oauthTokenSecret, L"", false);
		debugLogA( _T("**NegotiateConnection - Requesting oauthTokens"));
		http::response resp = twit_.request_token();

		//wstring rdata_WSTR(resp.data.length(),L' ');
		//std::copy(resp.data.begin(), resp.data.end(), rdata_WSTR.begin());
		wstring rdata_WSTR = UTF8ToWide(resp.data);

		//debugLogW("**NegotiateConnection - REQUEST TOKEN IS %s", rdata_WSTR);
		OAuthParameters response = twit_.ParseQueryString(rdata_WSTR);
		oauthToken = response[L"oauth_token"];
		oauthTokenSecret = response[L"oauth_token_secret"];
		//debugLogW("**NegotiateConnection - oauthToken is %s", oauthToken);
		//debugLogW("**NegotiateConnection - oauthTokenSecret is %s", oauthTokenSecret);

		if (oauthToken.length() < 1) {
			ShowPopup("OAuth Tokens not received, check your internet connection?", 1);
			debugLogA( _T("**NegotiateConnection - OAuth tokens not received, stopping before we open the web browser.."));
			return false;
		}

		//write those bitches to the db foe latta
		db_set_ws(0,m_szModuleName,TWITTER_KEY_OAUTH_TOK,oauthToken.c_str());
		db_set_ws(0,m_szModuleName,TWITTER_KEY_OAUTH_TOK_SECRET,oauthTokenSecret.c_str());
		
		// this looks like bad code.. can someone clean this up please?  or confirm that it's ok
		wchar_t buf[1024] = {};
		mir_snwprintf(buf, SIZEOF(buf), AuthorizeUrl.c_str(), oauthToken.c_str());

		debugLogW( _T("**NegotiateConnection - Launching %s"), buf);
		ShellExecute(NULL, L"open", buf, NULL, NULL, SW_SHOWNORMAL);
		
		ShowPinDialog();
	}

	if (!db_get_ts(NULL,m_szModuleName,TWITTER_KEY_GROUP,&dbv)) {
		CallService(MS_CLIST_GROUPCREATE, 0, (LPARAM)dbv.ptszVal );
		db_free(&dbv);	
	}

	bool realAccessTok = false;
	bool realAccessTokSecret = false;

	// remember, dbTOK is 0 (false) if the db setting has returned something
	dbTOK = db_get_ws(0,m_szModuleName,TWITTER_KEY_OAUTH_ACCESS_TOK,&dbv);
	if (!dbTOK) { 
		oauthAccessToken = dbv.pwszVal;
		db_free(&dbv);
		// this bit is saying "if we have found the db key, but it contains no data, then set dbTOK to 1"
		if (oauthAccessToken.size() > 1) { 
			realAccessTok = true; 
			//debugLogW("**NegotiateConnection - we have an oauthAccessToken already in the db - %s", oauthAccessToken); 
		}
		else { debugLogA( _T("**NegotiateConnection - oauthAccesToken too small? this is.. weird.")); }
	}

	dbTOKSec = db_get_ws(0,m_szModuleName,TWITTER_KEY_OAUTH_ACCESS_TOK_SECRET,&dbv);
	if (!dbTOKSec) { 
		oauthAccessTokenSecret = dbv.pwszVal;
		db_free(&dbv);
		if (oauthAccessTokenSecret.size() > 1) { 
			realAccessTokSecret = true; 
			//debugLogW("**NegotiateConnection - we have an oauthAccessTokenSecret already in the db - %s", oauthAccessTokenSecret); 
		}
		else { debugLogA( _T("**NegotiateConnection - oauthAccessTokenSecret too small? weird")); }
	}

	if (!realAccessTok || !realAccessTokSecret) {  // if we don't have one of these beasties then lets go get 'em!
		wstring pin;
		debugLogA( _T("**NegotiateConnection - either the accessToken or accessTokenSecret was not there.."));
		if (!db_get_ws(0,m_szModuleName,TWITTER_KEY_OAUTH_PIN,&dbv)) {
			pin = dbv.pwszVal;
			//debugLogW("**NegotiateConnection - we have an pin already in the db - %s", pin);
			db_free(&dbv);
		}
		else {
			ShowPopup(TranslateT("OAuth variables are out of sequence, they have been reset. Please reconnect and reauthorize Miranda to Twitter.com (do the PIN stuff again)"));
			debugLogA( _T("**NegotiateConnection - We don't have a PIN?  this doesn't make sense.  Resetting OAuth keys and setting offline."));
			resetOAuthKeys();

			ProtoBroadcastAck(0,ACKTYPE_STATUS,ACKRESULT_FAILED,(HANDLE)old_status,m_iStatus);

			// Set to offline
			old_status = m_iStatus;
			m_iDesiredStatus = m_iStatus = ID_STATUS_OFFLINE;
			ProtoBroadcastAck(0,ACKTYPE_STATUS,ACKRESULT_SUCCESS,(HANDLE)old_status,m_iStatus);

			return false;
		}

		debugLogA( _T("**NegotiateConnection - Setting Consumer Keys and PIN..."));
		/*debugLogW("**NegotiateConnection - sending set_cred: consumerKey is %s", ConsumerKey);
		debugLogW("**NegotiateConnection - sending set_cred: consumerSecret is %s", ConsumerSecret);
		debugLogW("**NegotiateConnection - sending set_cred: oauthToken is %s", oauthToken);
		debugLogW("**NegotiateConnection - sending set_cred: oauthTokenSecret is %s", oauthTokenSecret);
		debugLogW("**NegotiateConnection - sending set_cred: pin is %s", pin);*/

		twit_.set_credentials("", ConsumerKey, ConsumerSecret, oauthToken, oauthTokenSecret, pin, false);

		debugLogA( _T("**NegotiateConnection - requesting access tokens..."));
		http::response accessResp = twit_.request_access_tokens();
		if (accessResp.code != 200) {
			debugLogA( _T("**NegotiateConnection - Failed to get Access Tokens, HTTP response code is: %d"), accessResp.code);
			ShowPopup(TranslateT("Failed to get Twitter Access Tokens, please go offline and try again. If this keeps happening, check your internet connection."));

			resetOAuthKeys();

			ProtoBroadcastAck(0,ACKTYPE_STATUS,ACKRESULT_FAILED,(HANDLE)old_status,m_iStatus);

			// Set to offline
			old_status = m_iStatus;
			m_iDesiredStatus = m_iStatus = ID_STATUS_OFFLINE;
			ProtoBroadcastAck(0,ACKTYPE_STATUS,ACKRESULT_SUCCESS,(HANDLE)old_status,m_iStatus);

			return false;
		}
		else {
			debugLogA( _T("**NegotiateConnection - Successfully retrieved Access Tokens"));

			wstring rdata_WSTR2 = UTF8ToWide(accessResp.data);
			//debugLogW("**NegotiateConnection - accessToken STring is %s", rdata_WSTR2);
		
			OAuthParameters accessTokenParameters = twit_.ParseQueryString(rdata_WSTR2);

			oauthAccessToken = accessTokenParameters[L"oauth_token"];
			//debugLogW("**NegotiateConnection - oauthAccessToken is %s", oauthAccessToken);

			oauthAccessTokenSecret = accessTokenParameters[L"oauth_token_secret"];
			//debugLogW("**NegotiateConnection - oauthAccessTokenSecret is %s", oauthAccessTokenSecret);

			screenName = WideToUTF8(accessTokenParameters[L"screen_name"]);
			debugLogA( _T("**NegotiateConnection - screen name is %s"), screenName.c_str());
	
			//save em
			db_set_ws(0,m_szModuleName,TWITTER_KEY_OAUTH_ACCESS_TOK,oauthAccessToken.c_str());
			db_set_ws(0,m_szModuleName,TWITTER_KEY_OAUTH_ACCESS_TOK_SECRET,oauthAccessTokenSecret.c_str());
			db_set_s(0,m_szModuleName,TWITTER_KEY_NICK,screenName.c_str());
			db_set_s(0,m_szModuleName,TWITTER_KEY_UN,screenName.c_str());
		}
	}

/*	if( !db_get_s(0,m_szModuleName,TWITTER_KEY_PASS,&dbv)) {
		CallService(MS_DB_CRYPT_DECODESTRING,strlen(dbv.pszVal)+1,
			reinterpret_cast<LPARAM>(dbv.pszVal));
		pass = dbv.pszVal;
		db_free(&dbv);
	}
	else {
		ShowPopup(TranslateT("Please enter a password."));
		return false;
	}*/

	if( !db_get_s(0,m_szModuleName,TWITTER_KEY_BASEURL,&dbv))
	{
		ScopedLock s(twitter_lock_);
		twit_.set_base_url(dbv.pszVal);
		db_free(&dbv);
	}

	debugLogA( _T("**NegotiateConnection - Setting Consumer Keys and verifying creds..."));
	/*debugLogW("**NegotiateConnection - sending set_cred: consumerKey is %s", ConsumerKey);
	debugLogW("**NegotiateConnection - sending set_cred: consumerSecret is %s", ConsumerSecret);
	debugLogW("**NegotiateConnection - sending set_cred: oauthAccessToken is %s", oauthAccessToken);
	debugLogW("**NegotiateConnection - sending set_cred: oauthAccessTokenSecret is %s", oauthAccessTokenSecret);
	debugLogA("**NegotiateConnection - sending set_cred: no pin");*/

	if (screenName.empty()) {
		ShowPopup(TranslateT("You're missing the Nick key in the database. This isn't really a big deal, but you'll notice some minor quirks (self contact in list, no group chat outgoing message highlighting, etc). To fix it either add it manually or reset your Twitter account in the Miranda account options"));
		debugLogA( _T("**NegotiateConnection - Missing the Nick key in the database.  Everything will still work, but it's nice to have"));
	}

	bool success;
	{		
		ScopedLock s(twitter_lock_);

		success = twit_.set_credentials(screenName, ConsumerKey, ConsumerSecret, oauthAccessToken, oauthAccessTokenSecret, L"", true);
	}

	if(!success) {
		//ShowPopup(TranslateT("Something went wrong with authorisation, OAuth keys have been reset.  Please try to reconnect.  If problems persist, please se your doctor"));
		debugLogA( _T("**NegotiateConnection - Verifying credentials failed!  No internet maybe?"));

		//resetOAuthKeys();
		ProtoBroadcastAck(0,ACKTYPE_STATUS,ACKRESULT_FAILED,(HANDLE)old_status,m_iStatus);

		// Set to offline
		old_status = m_iStatus;
		m_iDesiredStatus = m_iStatus = ID_STATUS_OFFLINE;
		ProtoBroadcastAck(0,ACKTYPE_STATUS,ACKRESULT_SUCCESS,(HANDLE)old_status,m_iStatus);

		return false;
	}
	else {
		m_iStatus = m_iDesiredStatus;

		ProtoBroadcastAck(0,ACKTYPE_STATUS,ACKRESULT_SUCCESS,(HANDLE)old_status,m_iStatus);
		return true;
	}
}
Esempio n. 24
0
#include "graminfo.h"
#include <FactExtract/Parser/common/string_tokenizer.h>
#include <FactExtract/Parser/common/pathhelper.h>
#include <util/stream/file.h>
#include <util/string/strip.h>


const Wtroka g_strNameStubShort                 = UTF8ToWide("#n#");
const Wtroka g_strPatronomycStubShort           = UTF8ToWide("#p#");
const Wtroka g_strInitialPatronomycStubShort    = UTF8ToWide("#ip#");
const Wtroka g_strInitialNameStubShort          = UTF8ToWide("#in#");

const Wtroka g_strFioFormPrefix                 = UTF8ToWide("$$$ff");
const Wtroka g_strFioLemmaPrefix                = UTF8ToWide("$$$fl");

const Wtroka g_strFIONonTerminal                = UTF8ToWide("@фио");
const Wtroka g_strDateNonTerminal               = UTF8ToWide("@дата");

struct SNumeral2Number
{
    Wtroka m_Cardinal; // "РґРІР°"
    Wtroka m_Ordinal; // "второй"
    Wtroka m_Adverb;
    Wtroka m_Noun;
    ui64 m_Integer;
    int m_Fractional;

    SNumeral2Number(const char* cardinal, const char* ordinal, const char* adverb, const char* noun, ui64 integer, int fract)
        : m_Cardinal(UTF8ToWide(cardinal))
        , m_Ordinal(UTF8ToWide(ordinal))
Esempio n. 25
0
void CommandLine::AppendArg(const std::string& value)
{
    DCHECK(IsStringUTF8(value));
    AppendArgNative(UTF8ToWide(value));
}
Esempio n. 26
0
http::response mir_twitter::slurp(const std::string &url, http::method meth, OAuthParameters postParams)
{
	NETLIBHTTPREQUEST req = {sizeof(req)};
	req.requestType = (meth == http::get) ? REQUEST_GET:REQUEST_POST;
	req.szUrl = const_cast<char*>(url.c_str());

	//std::wstring url_WSTR(url.length(),L' ');
	//std::copy(url.begin(), url.end(), url_WSTR.begin());
	std::wstring url_WSTR = UTF8ToWide(url);
	std::string pdata_STR;
	std::wstring pdata_WSTR;

	std::wstring auth;
	if (meth == http::get) {
		if (url_WSTR.size()>0) { ppro_->debugLogW(L"**SLURP::GET - we have a URL: %s", url_WSTR); }
		if (consumerKey_.size()>0) { ppro_->debugLogA("**SLURP::GET - we have a consumerKey"); }
		if (consumerSecret_.size()>0) { ppro_->debugLogA("**SLURP::GET - we have a consumerSecret"); }
		if (oauthAccessToken_.size()>0) { ppro_->debugLogA("**SLURP::GET - we have a oauthAccessToken"); }
		if (oauthAccessTokenSecret_.size()>0) { ppro_->debugLogA("**SLURP::GET - we have a oauthAccessTokenSecret"); }
		if (pin_.size()>0) { ppro_->debugLogA("**SLURP::GET - we have a pin"); }
		//debugLogW("consumerSEcret is %s", consumerSecret_);
		//debugLogW("oauthAccessTok is %s", oauthAccessToken_);
		//debugLogW("oautAccessTokSEc is %s", oauthAccessTokenSecret_);
		//debugLogW("pin is %s", pin_);
		
		auth = OAuthWebRequestSubmit(url_WSTR, L"GET", NULL, consumerKey_, consumerSecret_, 
			oauthAccessToken_, oauthAccessTokenSecret_, pin_);
	}
	else if (meth == http::post) {

		//OAuthParameters postParams;
		if (url_WSTR.size()>0) { ppro_->debugLogW(L"**SLURP::POST - we have a URL: %s", url_WSTR); }
		if (consumerKey_.size()>0) { ppro_->debugLogA("**SLURP::POST - we have a consumerKey"); }
		if (consumerSecret_.size()>0) { ppro_->debugLogA("**SLURP::POST - we have a consumerSecret"); }
		if (oauthAccessToken_.size()>0) { ppro_->debugLogA("**SLURP::POST - we have a oauthAccessToken"); }
		if (oauthAccessTokenSecret_.size()>0) { ppro_->debugLogA("**SLURP::POST - we have a oauthAccessTokenSecret"); }
		if (pin_.size()>0) { ppro_->debugLogA("**SLURP::POST - we have a pin"); }

		//debugLogW("consumerKey is %s", consumerKey_);
		//debugLogW("consumerSEcret is %s", consumerSecret_);
		//debugLogW("oauthAccessTok is %s", oauthAccessToken_);
		//debugLogW("oautAccessTokSEc is %s", oauthAccessTokenSecret_);

		//std::wstring pdata_WSTR(post_data.length(),L' ');
		//std::copy(post_data.begin(), post_data.end(), pdata_WSTR.begin());

		//postParams[L"status"] = UrlEncode(pdata_WSTR);
		//postParams[L"source"] = L"mirandang";

		pdata_WSTR = BuildQueryString(postParams);

		ppro_->debugLogW(L"**SLURP::POST - post data is: %s", pdata_WSTR); 

		auth = OAuthWebRequestSubmit(url_WSTR, L"POST", &postParams, consumerKey_, consumerSecret_, 
			oauthAccessToken_, oauthAccessTokenSecret_);
		//debugLogW("**SLURP::POST auth is %s", auth);
	}
	else {
		ppro_->debugLogA("**SLURP - There is something really wrong.. the http method was neither get or post.. WHY??");
	}

	//std::string auth_STR(auth.length(), ' ');
	//std::copy(auth.begin(), auth.end(), auth_STR.begin());

	std::string auth_STR = WideToUTF8(auth);

	NETLIBHTTPHEADER hdr[3];
	hdr[0].szName = "Authorization";
	hdr[0].szValue = const_cast<char*>(auth_STR.c_str());

	req.headers = hdr;
	req.headersCount = 1;

	if(meth == http::post)
	{
		hdr[1].szName = "Content-Type";
		hdr[1].szValue = "application/x-www-form-urlencoded";
		hdr[2].szName  = "Cache-Control";
		hdr[2].szValue = "no-cache";

		//char *pdata_STR = new char[pdata_WSTR.length() + 1];
		//sprintf(pdata_STR,"%ls",pdata_WSTR.c_str());

		pdata_STR = WideToUTF8(pdata_WSTR);

		req.headersCount = 3;
		req.dataLength = (int)pdata_STR.size();
		req.pData = const_cast<char*>(pdata_STR.c_str());
		ppro_->debugLogA("**SLURP::POST - req.pdata is %s", req.pData);
	}

	req.flags = NLHRF_HTTP11 | NLHRF_PERSISTENT | NLHRF_REDIRECT;
	req.nlc = httpPOST_;
	http::response resp_data;
	ppro_->debugLogA("**SLURP - just before calling HTTPTRANSACTION");
	NETLIBHTTPREQUEST *resp = reinterpret_cast<NETLIBHTTPREQUEST*>(CallService(MS_NETLIB_HTTPTRANSACTION,
		reinterpret_cast<WPARAM>(handle_), reinterpret_cast<LPARAM>(&req)));
	ppro_->debugLogA("**SLURP - HTTPTRANSACTION complete.");
	if(resp)
	{
		ppro_->debugLogA("**SLURP - the server has responded!");
		httpPOST_ = resp->nlc;
		resp_data.code = resp->resultCode;
		resp_data.data = resp->pData ? resp->pData:"";

		CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT,0,(LPARAM)resp);
	}
	else { 
		httpPOST_ = NULL; 
		ppro_->debugLogA("SLURP - there was no response!"); 
	}

	return resp_data;
}
Esempio n. 27
0
 std::wstring UTF8ToWide(const char* in)
 {
     std::string inString(in);
     return UTF8ToWide(inString);
 }
Esempio n. 28
0
bool UTF8ToWide(const std::string& utf8, std::wstring* utf16) {
  // Use the stored length of the string which allows embedded NULL characters
  // to be converted.
  return UTF8ToWide(utf8.c_str(), utf8.length(), utf16);
}
Esempio n. 29
0
Wtroka Modality2Str(EModality Modality)
{
    YASSERT(Modality >= 0 && Modality < ModalityCount);
    return UTF8ToWide(ModalityStr[Modality]);
}
Esempio n. 30
0
FILE *OpenRead(const char *inUtf8Name)
{
   WString wide = UTF8ToWide(inUtf8Name);
   return OpenRead( wide.c_str() );
}