public Task <int> Create(CookieEntity entity) { entity.Id = _cookieList.Count + 1; _cookieList.Add(entity); return(Task.FromResult(entity.Id)); }
private Timer CreateTimer(CookieEntity cookie, long lContacterID) { Timer timer = new Timer(); timer.Interval = 1 * 60 * 1000; timer.Elapsed += (s, e) => { //20分钟后 关闭此次会话 List <string> lstParamsForEndCookie = new List <string>(); lstParamsForEndCookie.Add(cookie.CookieID.ToString()); lstParamsForEndCookie.Add(session.UserID.ToString()); lstParamsForEndCookie.Add(lContacterID.ToString()); try { iClient.EndCookieByID(lstParamsForEndCookie); } catch { } timer.Stop(); cookie.ResourceID = 0; cookie.CookieID = 0; cookie.CookieCreated = 0; }; return(timer); }
/// <summary> /// 设置资源(会话从一个资源 切换到另一个资源 使得本次聊天的内容与该资源关联) /// </summary> /// <param name="strContacterName">联系人的名字</param> /// <param name="lContacterID">联系人的ID</param> /// <param name="lResourceID">要关联的资源ID</param> public OperationReturn SetResource(string strContacterName, long lContacterID, long lResourceID) { OperationReturn optReturn = new OperationReturn(); List <ContacterInListBox> lstContacterByID = lstContacters.Where(p => p.UserID == lContacterID).ToList(); if (lstContacterByID.Count <= 0) { optReturn.Result = false; optReturn.Code = (int)S1600WcfError.NotInContacterList; return(optReturn); } ContacterInListBox con = lstContacterByID.First(); CookieEntity currCookie = null; //判断是否有未读消息 有未读消息 说明窗口没有打开 将创建新的cookie信息和聊天窗口 List <ChatMessage> lstUnReadMsgByID = lstUnReadMsg.Where(p => p.SenderID == lContacterID).ToList(); if (lstUnReadMsgByID.Count > 0) { currCookie = new CookieEntity(); //有未读消息 判断对方是否在线 如果在线 再判断最后一条消息所属的会话是否关闭 //如果关闭 则之前的会话视为无效 新会话的资源ID为新传入的ID, 反之 则接收最后一条消息的cookieID和ResourceID作为本次会话的cookieID和ResourceID if (con.Status == "0") //离线 { currCookie.ResourceID = lResourceID; currCookie.CookieCreated = 0; currCookie.CookieID = 0; } else { //判断最后一条消息的会话是否关闭 long lLastResID = long.Parse(lstUnReadMsgByID.Last().ResourceID.ToString()); string strLastCookieID = lstUnReadMsgByID.Last().CookieID.ToString(); bool boCookieEffective = GetCookieStatusByID(strLastCookieID); currCookie.ResourceID = boCookieEffective ? lLastResID : lResourceID; currCookie.CookieCreated = boCookieEffective ? 2 : 0; currCookie.CookieID = boCookieEffective ? long.Parse(strLastCookieID) : 0; } currCookie.UserID = lContacterID; currCookie.UserName = strContacterName; //创建聊天窗口 currCookie.ChatTab = CreateChatWindow(con); (currCookie.ChatTab.Content as ChartWindow).cookie = currCookie; dicCookies.Add(lContacterID, currCookie); //将消息写入聊天窗口 并让头像停止闪烁 WriteUnReadMsgToWin(lContacterID, currCookie.ChatTab.Content as ChartWindow); dicImgThread[con.UserID].Stop(); dicImgThread[con.UserID].Dispose(); dicImgThread[con.UserID].Close(); dicImgThread.Remove(con.UserID); con.IMGOpacity = "1"; if (currCookie.CookieID == 0) { //如果会话ID是0 证明前一次会话已经结束 可能会开启一次新的会话 所以需要给timer赋值 currCookie.CookieTimer = CreateTimer(currCookie, lContacterID); } optReturn.Result = true; return(optReturn); } //如果没有未读消息 判断窗口是否被打开了 List <string> lstParamsForEndCookie = new List <string>(); if (dicCookies.Keys.Contains(lContacterID)) { //如果聊天窗口已经打开了 需要结束上一个会话 资源ID改为传入的ID 如果timer不为null 需要停掉timer重新开始计时 currCookie = dicCookies[lContacterID]; lstParamsForEndCookie.Clear(); lstParamsForEndCookie.Add(currCookie.CookieID.ToString()); lstParamsForEndCookie.Add(session.UserID.ToString()); lstParamsForEndCookie.Add(lContacterID.ToString()); if (currCookie.CookieID != 0) { iClient.EndCookieByID(lstParamsForEndCookie); } dicCookies[lContacterID].CookieID = 0; dicCookies[lContacterID].CookieCreated = 0; dicCookies[lContacterID].ResourceID = 0; dicCookies[lContacterID].CookieTimer = null; //dicCookies.Remove(lContacterID); } else { currCookie = new CookieEntity(); currCookie.ChatTab = CreateChatWindow(con); currCookie.UserID = lContacterID; currCookie.UserName = strContacterName; } currCookie.CookieID = 0; currCookie.CookieCreated = 0; if (currCookie.CookieTimer != null) { currCookie.CookieTimer.Stop(); } else { currCookie.CookieTimer = CreateTimer(currCookie, lContacterID); } currCookie.ResourceID = lResourceID; currCookie.ChatTab.IsSelected = true; (currCookie.ChatTab.Content as ChartWindow).cookie = currCookie; if (dicCookies.Keys.Contains(lContacterID)) { dicCookies.Remove(lContacterID); } dicCookies.Add(lContacterID, currCookie); return(optReturn); }
public async Task <int> CreateCookie(CookieEntity cookie) { return(await _mediator.Send(new CreateCookie.Command { Cookie = cookie })); }
/// <summary> /// /// </summary> /// <param name="loginUrl">Login url</param> /// <param name="userName">User's login name</param> /// <param name="password">User's password</param> /// <param name="formParams">Optional string which contains any additional form params</param> /// <returns></returns> public bool LoginToSite(String userName, String password) { ////////////////////////////////////////////////////////////////////////////// // // local variables // TODO: Review if there is a better solution to hard-coding these // string formParams = string.Format("language=en&affiliateName=espn&parentLocation=®istrationFormId=espn"); string loginUrl = "https://r.espn.go.com/members/util/loginUser"; CookieCollection cookies; string leagueId = ""; string teamId = ""; string season = ""; string userTable = "ausers00"; string teamTable = "ateams00"; string cookieTable = "acookies00"; bool newUser = true; ///////////////////////////////////////////////////////////////////////////// // // Lookup / Store user in storage. // // Encrypt the user password for safe persistence // TODO: Store the key somewhere safe. Also, it may be better to store password on the device? // string passwordHash = Crypto.EncryptStringAES(password, "foobar"); // Retrieve storage account from connection string CloudStorageAccount storageAccount = CloudStorageAccount.Parse( CloudConfigurationManager.GetSetting("StorageConnectionString")); // // Create the table client // CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); // // Create the user/team/cookie tables if they don't exist // tableClient.CreateTableIfNotExist(userTable); tableClient.CreateTableIfNotExist(teamTable); tableClient.CreateTableIfNotExist(cookieTable); // Get the data service context TableServiceContext serviceContext = tableClient.GetDataServiceContext(); // // Look up the user in the storage tables // UserEntity specificEntity = (from e in serviceContext.CreateQuery <UserEntity>(userTable) where e.RowKey == userName select e).FirstOrDefault(); // // Check to see if password is correct // if (specificEntity != null) { string userPassword = Crypto.DecryptStringAES(specificEntity.PasswordHash, "foobar"); if (userPassword == password) { newUser = false; } } // // If this is a new user add them to the users databse // if (newUser) { // // Setup formUrl string // string formUrl = ""; if (!String.IsNullOrEmpty(formParams)) { formUrl = formParams + "&"; } formUrl += string.Format("username={0}&password={1}", userName, password); // // Now setup the POST request // HttpWebRequest req = (HttpWebRequest)WebRequest.Create(loginUrl); req.CookieContainer = new CookieContainer(); req.ContentType = "application/x-www-form-urlencoded"; req.Method = "POST"; byte[] bytes = Encoding.ASCII.GetBytes(formUrl); req.ContentLength = bytes.Length; using (Stream os = req.GetRequestStream()) { os.Write(bytes, 0, bytes.Length); } // // Read the response // string respString = ""; using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse()) { // // Gather cookie info // cookies = resp.Cookies; // // Read the response stream to determine if login was successful. // using (StreamReader reader = new StreamReader(resp.GetResponseStream())) { Char[] buffer = new Char[256]; int count = reader.Read(buffer, 0, 256); while (count > 0) { respString += new String(buffer, 0, count); count = reader.Read(buffer, 0, 256); } } // reader is disposed here } //writeLog(respString); // // If response string contains "login":"******" this indicates success // if (!respString.Contains("{\"login\":\"true\"}")) { throw new InvalidOperationException("Failed to login with given credentials"); } // // Login success - Now save user to databse // TODO: Figure out a better partition key other than "key" // UserEntity user = new UserEntity("key", userName); user.PasswordHash = passwordHash; // Add the new team to the teams table serviceContext.AddObject(userTable, user); ////////////////////////////////////////////////////////////////////////////////// // // Now that we have logged in, extract user info from the page // string url2 = "http://games.espn.go.com/frontpage/football"; HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create(url2); req2.CookieContainer = new CookieContainer(); req2.ContentType = "application/x-www-form-urlencoded"; req2.Method = "POST"; // // Add the login cookies // foreach (Cookie cook in cookies) { //writeLog("**name = " + cook.Name + " value = " + cook.Value); CookieEntity newCook = new CookieEntity(userName, cook.Name); newCook.Value = cook.Value; newCook.Path = cook.Path; newCook.Domain = cook.Domain; // Add the new cookie to the cookies table serviceContext.AddObject(cookieTable, newCook); req2.CookieContainer.Add(cook); } // // Read the response // using (HttpWebResponse resp = (HttpWebResponse)req2.GetResponse()) { // // Do something with the response stream. As an example, we'll // stream the response to the console via a 256 character buffer using (StreamReader reader = new StreamReader(resp.GetResponseStream())) { HtmlDocument doc = new HtmlDocument(); doc.Load(reader); // // Build regEx for extracting legue info from link address // string pattern = @"(clubhouse\?leagueId=)(\d+)(&teamId=)(\d+)(&seasonId=)(\d+)"; Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase); foreach (HtmlNode hNode in doc.DocumentNode.SelectNodes("//a[@href]")) { HtmlAttribute att = hNode.Attributes["href"]; Match match = rgx.Match(att.Value); // // If our regEx finds a match then we have leagueId, teamId, and seasonId // if (match.Success) { //writeLog("NODE> Name: " + hNode.Name + ", ID: " + hNode.Id + "attr: " + att.Value); GroupCollection groups = match.Groups; leagueId = groups[2].Value; teamId = groups[4].Value; season = groups[6].Value; // // Create a new team entity // TeamEntity team = new TeamEntity(leagueId, teamId); team.Season = season; team.UserId = userName; // Add the new team to the teams table serviceContext.AddObject(teamTable, team); } } } // reader is disposed here } // Submit the operation to the table service serviceContext.SaveChangesWithRetries(); } return(true); }