00001 /* 00002 * Copyright (C) 2008 Emweb bvba, Heverlee, Belgium. 00003 * 00004 * See the LICENSE file for terms of use. 00005 */ 00006 00007 #include "SimpleChatServer.h" 00008 00009 #include <iostream> 00010 #include <boost/lexical_cast.hpp> 00011 00012 using namespace Wt; 00013 00014 const WString ChatEvent::formattedHTML(const WString& user) const 00015 { 00016 switch (type_) { 00017 case Login: 00018 return "<span class='chat-info'>" 00019 + user_ + " joined the conversation.</span>"; 00020 case Logout: 00021 return "<span class='chat-info'>" 00022 + ((user == user_) ? "You" : user_) 00023 + " logged out.</span>"; 00024 case Message:{ 00025 WString result; 00026 00027 result = WString("<span class='") 00028 + ((user == user_) ? "chat-self" : "chat-user") 00029 + "'>" + user_ + ":</span>"; 00030 00031 if (message_.toUTF8().find(user.toUTF8()) != std::string::npos) 00032 return result + "<span class='chat-highlight'>" + message_ + "</span>"; 00033 else 00034 return result + message_; 00035 } 00036 default: 00037 return ""; 00038 } 00039 } 00040 00041 00042 SimpleChatServer::SimpleChatServer() 00043 : chatEvent_(this) 00044 { } 00045 00046 bool SimpleChatServer::login(const WString& user) 00047 { 00048 boost::mutex::scoped_lock lock(mutex_); 00049 00050 if (users_.find(user) == users_.end()) { 00051 users_.insert(user); 00052 00053 chatEvent_.emit(ChatEvent(ChatEvent::Login, user)); 00054 00055 return true; 00056 } else 00057 return false; 00058 } 00059 00060 void SimpleChatServer::logout(const WString& user) 00061 { 00062 boost::mutex::scoped_lock lock(mutex_); 00063 00064 UserSet::iterator i = users_.find(user); 00065 00066 if (i != users_.end()) { 00067 users_.erase(i); 00068 00069 chatEvent_.emit(ChatEvent(ChatEvent::Logout, user)); 00070 } 00071 } 00072 00073 WString SimpleChatServer::suggestGuest() 00074 { 00075 boost::mutex::scoped_lock lock(mutex_); 00076 00077 for (int i = 1;; ++i) { 00078 std::string s = "guest " + boost::lexical_cast<std::string>(i); 00079 WString ss = s; 00080 00081 if (users_.find(ss) == users_.end()) 00082 return ss; 00083 } 00084 } 00085 00086 void SimpleChatServer::sendMessage(const WString& user, const WString& message) 00087 { 00088 boost::mutex::scoped_lock lock(mutex_); 00089 00090 chatEvent_.emit(ChatEvent(user, message)); 00091 } 00092 00093 SimpleChatServer::UserSet SimpleChatServer::users() 00094 { 00095 return users_; 00096 }