void operator()(boost::system::error_code ec, std::size_t bytes_transfered)
	{
		pt::ptree	jsonobj;
		std::istream jsondata( m_buffer.get() );

		/**
		* Here, we got a json object like this:
		* {"retcode":0,"result":{"uiuin":"","account":615050000,"uin":954663841}}
		*
		*/
		//处理!
		try {
			pt::json_parser::read_json( jsondata, jsonobj );

			//TODO, group members
			if( jsonobj.get<int>( "retcode" ) == 0 ) {
				m_this_group->qqnum = jsonobj.get<std::string>( "result.account" );
				BOOST_LOG_TRIVIAL(debug) <<  "qq number of group "
					<<  utf8_to_local_encode(m_this_group->name) << " is " <<  m_this_group->qqnum;

				m_webqq->siggroupnumber(m_this_group);

				m_handler(boost::system::error_code());

				return ;
			}else{
				BOOST_LOG_TRIVIAL(error) << literal_to_localstr("获取群的QQ号码失败");
				pt::json_parser::write_json(std::cerr, jsonobj);
			}
		} catch( const pt::ptree_error & jserr ) {
		}

		// 返回错误
		m_handler(error::make_error_code(error::failed_to_fetch_group_qqnumber));
	}
Beispiel #2
0
	void operator()( const boost::system::error_code& ec, std::size_t bytes_transfered)
	{
		std::string msg;
		pt::ptree json;
		std::istream response( buf.get() );

		if (!ec){
		// 登录步骤.
		//处理!
		try {
			js::read_json( response, json );
			js::write_json( std::cout, json );

			if( json.get<std::string>( "retcode" ) == "0" ) {
				m_webqq->m_psessionid = json.get_child( "result" ).get<std::string>( "psessionid" );
				m_webqq->m_vfwebqq = json.get_child( "result" ).get<std::string>( "vfwebqq" );
				m_webqq->m_status = LWQQ_STATUS_ONLINE;

				m_handler(boost::system::error_code());
				return;
			}
		} catch( const pt::json_parser_error & jserr ) {
			BOOST_LOG_TRIVIAL(error) <<  __FILE__ << " : " <<__LINE__ << " :" <<  "parse json error :" <<  jserr.what();
		} catch( const pt::ptree_bad_path & jserr ) {
			BOOST_LOG_TRIVIAL(error) <<  __FILE__ << " : " <<__LINE__ << " :" << "parse bad path error : " <<  jserr.what();
		}
		}

		m_handler(boost::system::errc::make_error_code(boost::system::errc::protocol_error));
	}
	void operator()(boost::system::error_code ec, std::size_t bytes_transfered)
	{
		pt::ptree	jsonobj;
		std::istream jsondata( m_buffer.get() );

		/**
		* Here, we got a json object like this:
		* {"retcode":0,"result":{"uiuin":"","account":615050000,"uin":954663841}}
		*
		*/
		//处理!
		try {
			pt::json_parser::read_json( jsondata, jsonobj );

			//TODO, group members
			if( jsonobj.get<int>( "retcode" ) == 0 ) {
				m_this_group->qqnum = jsonobj.get<std::string>( "result.account" );
				BOOST_LOG_TRIVIAL(debug) <<  "qq number of group " <<  console_out_str(m_this_group->name) << " is " <<  m_this_group->qqnum;
				// 写缓存
				pt::json_parser::write_json(std::string("cache/group_qqnumber") + m_this_group->gid, jsonobj);
				//start polling messages, 2 connections!
				BOOST_LOG_TRIVIAL(info) << "start polling messages";

				m_webqq->siggroupnumber(m_this_group);

				m_handler(boost::system::error_code());

				return ;
			}else{
				BOOST_LOG_TRIVIAL(error) << console_out_str("获取群的QQ号码失败");
				pt::json_parser::write_json(std::cerr, jsonobj);
			}
		} catch( const pt::ptree_error & jserr ) {
		}

		try{
		// 读取缓存
			pt::json_parser::read_json(std::string("cache/group_qqnumber") + m_this_group->gid, jsonobj);

			m_this_group->qqnum = jsonobj.get<std::string>( "result.account" );
			BOOST_LOG_TRIVIAL(debug) <<  "(cached) qq number of group" <<  console_out_str(m_this_group->name) << "is" <<  m_this_group->qqnum << std::endl;

			// 向用户报告一个 group 出来了.
			m_webqq->siggroupnumber(m_this_group);
			m_handler(boost::system::error_code());
			return;
		}catch (const pt::ptree_error & jserr){
			boost::delayedcallsec( m_webqq->get_ioservice() , 500 + boost::rand48()() % 100 ,
				boost::bind( &make_update_group_qqnumber_op, m_webqq, m_this_group, m_handler)
			);
		}
	}
Beispiel #4
0
 /**
  * Thread of the receiver socket. It handles all incoming data
  * and forwards it to the main event loop.
  */
 void receiverThread() {
     // hold a reference count of the context
     auto context = m_context;
     zmq::socket_t receiver(*context, zmq::socket_type::sub);
     receiver.connect(m_addr.makeReceiverAddress());
     receiver.setsockopt(ZMQ_SUBSCRIBE, "", 0);
     int timeout = 200;
     receiver.setsockopt(ZMQ_RCVTIMEO, &timeout, sizeof(timeout));
     bool cancel = false;
     auto last_connect = std::chrono::system_clock::now();
     while (!cancel) {
         zmq::message_t zmq_msg;
         bool again = !receiver.recv(&zmq_msg);
         if (again) {
             if (m_cancel) {
                 return;
             }
             capnqml::Message msg;
             msg.setType(capnqml::Message::Type::Connect);
             push(msg);
             auto now = std::chrono::system_clock::now();
             if (now - last_connect > std::chrono::milliseconds(m_timeout)
                     && m_state == Channel::State::Connected) {
                 // timeout
                 m_state = Channel::State::Disconnected;
                 m_loop.invoke([this]() {
                     if (m_disconnect) {
                         m_disconnect();
                     }
                 });
             }
             continue;
         }
         auto message = _::unpack(zmq_msg);
         if (message.type() == Message::Type::Connect) {
             last_connect = std::chrono::system_clock::now();
             if (m_state == Channel::State::Disconnected && m_connect) {
                 m_state = Channel::State::Connected;
                 m_loop.invoke([this]() {
                     m_connect();
                 });
             }
             m_state = Channel::State::Connected;
         }
         auto fun = [this, msg = std::move(message)] {
             if (m_handler) {
                 m_handler(msg);
             }
         };
         m_loop.invoke(std::move(fun));
         if (message.type() == Message::Type::Disconnect) {
             m_state = Channel::State::Disconnected;
             m_loop.invoke([this]() {
                 if (m_disconnect) {
                     m_disconnect();
                 }
             });
         }
     }
 }
Beispiel #5
0
	void operator()( const boost::system::error_code& ec, std::size_t bytes_transfered)
	{
		std::string msg;
		pt::ptree json;
		std::istream response( buf.get() );

		if (!ec){
		// 登录步骤.
		//处理!
		try {
			js::read_json( response, json );

			if( json.get<std::string>( "retcode" ) == "0" ) {
				m_webqq->m_psessionid = json.get<std::string>( "result.psessionid" );
				m_webqq->m_vfwebqq = json.get<std::string>( "result.vfwebqq" );
				m_webqq->m_myself_uin = json.get<std::string>("result.uin");

				m_webqq->m_cookie_mgr.save_cookie("psession.qq.com", "/", "vfwebqq", m_webqq->m_vfwebqq, "session");
				m_webqq->m_cookie_mgr.save_cookie("psession.qq.com", "/", "psessionid", m_webqq->m_psessionid, "session");
				m_webqq->m_cookie_mgr.save_cookie("psession.qq.com", "/", "uin", m_webqq->m_myself_uin, "session");

				m_webqq->m_status = LWQQ_STATUS_ONLINE;

				m_webqq->get_ioservice().post(
					boost::asio::detail::bind_handler(m_handler,boost::system::error_code())
				);
				return;
			}
		} catch( const pt::ptree_error & jserr ) {
			BOOST_LOG_TRIVIAL(error) <<  __FILE__ << " : " <<__LINE__ << " :" << "parse bad path error : " <<  jserr.what();
		}
		}

		m_handler(error::make_error_code(error::failed_to_change_status));
	}
Beispiel #6
0
void http_connection::on_assign_bandwidth(asio::error_code const& e)
{
	if ((e == asio::error::operation_aborted
		&& m_limiter_timer_active)
		|| !m_sock.is_open())
	{
		if (!m_bottled || !m_called)
			m_handler(e, m_parser, 0, 0);
		return;
	}
	m_limiter_timer_active = false;
	if (e) return;

	if (m_download_quota > 0) return;

	m_download_quota = m_rate_limit / 4;

	int amount_to_read = m_recvbuffer.size() - m_read_pos;
	if (amount_to_read > m_download_quota)
		amount_to_read = m_download_quota;

	m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
		, amount_to_read)
		, bind(&http_connection::on_read
		, shared_from_this(), _1, _2));

	m_limiter_timer_active = true;
	m_limiter_timer.expires_from_now(milliseconds(250));
	m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth
		, shared_from_this(), _1));
}
Beispiel #7
0
void http_connection::on_write(asio::error_code const& e)
{
	if (e)
	{
		close();
		if (m_bottled && m_called) return;
		m_called = true;
		m_handler(e, m_parser, 0, 0);
		return;
	}

	std::string().swap(sendbuffer);
	m_recvbuffer.resize(4096);

	int amount_to_read = m_recvbuffer.size() - m_read_pos;
	if (m_rate_limit > 0 && amount_to_read > m_download_quota)
	{
		amount_to_read = m_download_quota;
		if (m_download_quota == 0)
		{
			if (!m_limiter_timer_active)
				on_assign_bandwidth(asio::error_code());
			return;
		}
	}
	m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
		, amount_to_read)
		, bind(&http_connection::on_read
		, shared_from_this(), _1, _2));
}
Beispiel #8
0
void http_connection::on_connect(asio::error_code const& e
	/*, tcp::resolver::iterator i*/)
{
	if (!e)
	{ 
		m_last_receive = time_now();
		asio::async_write(m_sock, asio::buffer(sendbuffer)
			, bind(&http_connection::on_write, shared_from_this(), _1));
	}
/*	else if (i != tcp::resolver::iterator())
	{
		// The connection failed. Try the next endpoint in the list.
		m_sock.close();
		m_cc.enqueue(bind(&http_connection::connect, shared_from_this(), _1, *i)
			, bind(&http_connection::on_connect_timeout, shared_from_this())
			, m_timeout);
	} 
*/	else
	{ 
		close();
		if (m_bottled && m_called) return;
		m_called = true;
		m_handler(e, m_parser, 0, 0);
	}
}
Beispiel #9
0
void		CPackMgr::PullData(uint32 linkid , uint8*pdata , uint32 datalen)
{
    std::map<uint32,std::vector<uint8>*>::iterator iter = m_streams.find(linkid);
    if(iter != m_streams.end())
    {
        std::vector<uint8>*p	=	iter->second;
        for (uint32 k = 0 ; k < datalen ; k ++)
            p->insert(p->end(),pdata, pdata + datalen );

        uint32 ll = sizeof(uint32);
        while ((uint32)p->size() > ll)
        {
            uint32 packlen = 0;
            uint8*	packdata	=	&p->operator [](0);
            uint32	packdatalen	=	(uint32)p->size();
            if( !UnPackLen(packdata,packdatalen,packlen) )
                break;
            if((uint32)p->size() - ll >= packlen)
            {
                if(m_handler)
                    m_handler(linkid,&p->operator [](ll),packlen);
                std::vector<uint8>::iterator bit = p->begin();
                std::vector<uint8>::iterator eit = bit + ll + packlen;
                p->erase(bit,eit);
            }
        }
    }
}
Beispiel #10
0
void
COverlappedOperation::HandleCompletion()
{
	if (!m_completionHandled)
	{
		m_completionHandled = true;
		m_handler(this);
	}
}
Beispiel #11
0
void http_connection::on_connect_timeout()
{
	if (m_connection_ticket > -1) m_cc.done(m_connection_ticket);
	m_connection_ticket = -1;

	if (m_bottled && m_called) return;
	m_called = true;
	m_handler(asio::error::timed_out, m_parser, 0, 0);
	close();
}
Beispiel #12
0
	void operator()(boost::system::error_code ec, size_t bytes_transfered)
	{
		if ((coro=(!coro)))
		{
			boost::asio::async_write(m_stream, m_streambuf.data(), *this);
		}
		else
		{
			m_handler(ec, bytes_transfered);
		}
	}
Beispiel #13
0
void Receiver::handle_receive_from(const boost::system::error_code& err,
    size_t bytes_recvd)
{
    // Send the raw data to the handler
    if (!err && bytes_recvd > 0) {
        m_handler(m_data);
    }

    // Start new accept
    start_receive();
}
Beispiel #14
0
void Comm::process_wire()
{
    byte val = wire_get();
    if (val != m_addr) {
        wire_drain();
        return;
    }
    byte num = wire_get();
    m_handler(num);
    wire_drain();
}
Beispiel #15
0
    void Notifier::onEvent(IOLoop* loop, int events)
    {
        NotifierPtr_t notifier = shared_from_this();
        eventfd_t value;
        
        if(eventfd_read(m_fd, &value) < 0)
        {
            LOG_ERROR("eventfd read error");
            return;    
        }    

        m_handler(notifier);
    } 
	void operator()(boost::system::error_code ec, std::size_t bytes_transfered)
	{
		m_webqq->m_cookie_mgr.save_cookie(*m_stream);

		std::string vcimg;
		vcimg.resize(bytes_transfered);

		m_buffer->sgetn(&vcimg[0], bytes_transfered);

		if (ec)
			ec = error::fetch_verifycode_failed;
		m_handler(ec, vcimg);
	}
Beispiel #17
0
 ~ScopeWatcher()
 {
     if (m_handler)
     {
         try
         {
             m_handler();
         }
         catch (...)
         {
         }
     }
 }
Beispiel #18
0
void generic_bus< PBus >::platform_handler(bus_channel ch, bus_event type, size_t total)
{
    // Transfer complete accross all channels
    bool last_event = (ch == bus_channel::meta && type == bus_event::tc);

    if (type == bus_event::err) {
        m_state |= xfer_error;
    }

    if (last_event) {
        // Spurious events are not allowed
        ecl_assert(!(m_state & xfer_served));

        m_state |= xfer_served;
    }

    if (m_state & async_mode) {
        m_handler(ch, type, total);

        // Bus unlocked, it is time to check if bus cleaned.
        if (last_event && !(m_state & bus_locked)) {

            // It is possible that bus_handler() is executed in thread context
            // rather in ISR context. This means that context switch can occur
            // right after unlock flag is set inside unlock() but before
            // cleanup will occur. Atomic test_and_set will protect important
            // call with lock-free critical section.
            // In case if handler is executed in ISR context, this check
            // is almost meaningless, besides that setting a flag is required
            // to inform rest of the system that cleanup already done.
            if (!m_cleaned.test_and_set()) {
                cleanup();
            }
        }
    } else {
        // In blocking mode a bus is responcible for bytes counting
        if (ch == bus_channel::tx) {
            m_sent = total;
        } else if (ch == bus_channel::rx) {
            m_received = total;
        }

        // Don't do anything for 'meta' channel
    }

    if (last_event) {
        // Inform rest of the bus about event handling
        m_complete.signal();
    }
}
Beispiel #19
0
void LogMessage::Log
(
    LogMessage::Severity sev,       ///< Message severity
    const char          *file,      ///< Filename where log occurs
    int                  lineNum    ///< Line number where log occurs
)
{
    if ( m_handler != NULL )
    {
        std::string str = m_stream.str();

        m_handler( sev, str.c_str(), file, lineNum );
    }

} // Log
Beispiel #20
0
void http_connection::on_resolve(asio::error_code const& e
		, tcp::resolver::iterator i)
{
	if (e)
	{
		close();
		if (m_bottled && m_called) return;
		m_called = true;
		m_handler(e, m_parser, 0, 0);
		return;
	}
	assert(i != tcp::resolver::iterator());
	m_cc.enqueue(bind(&http_connection::connect, shared_from_this(), _1, *i)
		, bind(&http_connection::on_connect_timeout, shared_from_this())
		, m_timeout);
}
void
title_presence_change_subscription::on_event_received(
    _In_ const web::json::value& data
    )
{
    if (m_handler && !data.is_null())
    {
        std::error_code errc;
        auto titlePresenceValue = utils::extract_json_as_string(data, errc);

        title_presence_state titlePresenceState = title_presence_state::unknown;
        if (!errc)
        {
            if (utils::str_icmp(titlePresenceValue, _T("started")) == 0)
            {
                titlePresenceState = title_presence_state::started;
            }
            else if (utils::str_icmp(titlePresenceValue, _T("ended")) == 0)
            {
                titlePresenceState = title_presence_state::ended;
            }
        }
        else
        {
            if(m_subscriptionErrorHandler != nullptr)
            {
                m_subscriptionErrorHandler(
                    xbox::services::real_time_activity::real_time_activity_subscription_error_event_args(
                        *this,
                        xbox_live_error_code::json_error,
                        "JSON deserialization failure"
                        )
                    );
            }

            return;
        }

        auto presenceEventArgs = title_presence_change_event_args(
            m_xboxUserId,
            m_titleId,
            std::move(titlePresenceState)
            );

        m_handler(presenceEventArgs);
    }
}
Beispiel #22
0
void LogMessage::PrintStr
(
    LogMessage::Severity sev,   ///< Message severity
    const char          *str    ///< String to print
)
{
    if ( m_handler == NULL )
    {
        return;
    }

    static  char    line[ 512 ] = { 0 };
    char *endLine = &line[ sizeof( line ) - 1];
    const char *src = str;
    
    do
    {
        int lineLen = strlen( line );

        char *dst = &line[ lineLen ];

        while (( *src != '\0' ) && ( *src != '\n' ) && ( dst < endLine ))
        {
            *dst++ = *src++;
        }
        *dst = '\0';

        if (( *src == '\n' ) || ( dst >= endLine ))
        {
            // Don't use the LOG macro, since it may cause memory allocation
            // to occur, and this routine is often called as part of the
            // process of dumping memory leaks

            m_handler( sev, line, __FILE__, __LINE__ );

            line[ 0 ] = '\0';

            if ( *src == '\n' )
            {
                src++;
            }
        }

    } while ( *src != '\0' );

} // Printf
Beispiel #23
0
void Log::CloseLog( BOOL result, char* message )
{
    char buffer[40];

    char* result_s = ConvertResult( result );

    if(message)
    {
        hal_snprintf( buffer, sizeof(buffer), "%12s, %4s", message, result_s );
    }
    else
    {
        hal_snprintf( buffer, sizeof(buffer), "%12s, %4s", m_logBuffer, result_s );
    }

    m_handler( buffer, NULL );
}
Beispiel #24
0
 /**
  * Process events in the queue.
  */
 bool process() {
     decltype(m_buffer) local_buffer;
     decltype(m_invokes) local_invoke_buffer;
     {
         std::lock_guard<std::mutex> lock(m_data_lock);
         if (m_state == State::Cancelling) {
             return false;
         }
         m_state = State::Processing;
         for (auto &msg : m_buffer) {
             local_buffer.push_back(std::move(msg));
         }
         for (auto &fun : m_invokes) {
             local_invoke_buffer.push_back(std::move(fun));
         }
         m_buffer.clear();
         m_invokes.clear();
     }
     if (m_handler) {
         for (auto &msg : local_buffer) {
             m_handler(std::move(msg));
         }
     }
     for (auto &fun : local_invoke_buffer) {
         if(fun) {
             fun();
         }
     }
     {
         std::lock_guard<std::mutex> lock(m_data_lock);
         if (m_state == State::Cancelling) {
             return false;
         }
         m_state = State::Idle;
     }
     return true;
 }
Beispiel #25
0
void Comm::process_serial()
{
    if (! Serial.available()) {
        return;
    }

    byte addr = serial_get();
    byte pkt = serial_get();
    byte num = serial_get();

    bool okay = false;
    if (!addr) {                // handle by master
        if (m_handler) {
            okay = m_handler(num);
            serial_drain();
        }
        else {
            okay = drain(num);
        }
    }
    else {                      // send to slave
        okay = transmit(addr,num);
        serial_drain();
    }

    if (okay) {
        Serial.print("OK");
    }
    else {
        Serial.print("NO");
    }
    Serial.print(pkt);
    Serial.print(addr);
    Serial.print(num);
    Serial.print('\0');
}
Beispiel #26
0
	void handle(const RouteMatch& m) const { m_handler(m); }
Beispiel #27
0
ScopeExit::~ScopeExit() {
  if (!m_cancelled) {
    m_handler();
  }
}
Beispiel #28
0
void
xw::WaylandSurfaceListener::SurfaceCreated(xw::Surface &surface)
{
  if (!m_handler.empty())
    m_handler(surface);
}
Beispiel #29
0
 static void invoke(channel ch, event e, size_t total)
 {
     m_handler(ch, e, total);
 }
Beispiel #30
0
void Button::update()
{
    if(m_sprite.getGlobalBounds().contains(m_app.inputmanager.getMousePos()) && m_app.inputmanager.isButtonHit(sf::Mouse::Left))
        m_handler();
}