protected PrivateMessage GetMyMsg(PrivateMessage[] msgs) { PrivateMessage returnValue; PrivateMessage result = null; int idx; try { if ((msgs != null) && (msgs.Length > 0)) { for (idx = 0; idx <= msgs.Length - 1; idx++) { if ((msgs[idx].IsARecipient(m_userId)) || (Ektron.Cms.Common.EkFunctions.IsNumeric(m_msgUserId) && msgs[idx].IsARecipient(Convert.ToInt64(m_msgUserId)))) { result = msgs[idx]; break; } } } } catch (Exception) { result = null; } finally { if (result == null) { result = new Ektron.Cms.Content.PrivateMessage(); } returnValue = result; } return returnValue; }
/// <summary> /// Add a private message /// </summary> /// <param name="message"></param> /// <returns></returns> public PrivateMessage Add(PrivateMessage message) { // This is the message that the other user sees message = SanitizeMessage(message); message.DateSent = DateTime.UtcNow; message.IsSentMessage = false; var e = new PrivateMessageEventArgs { PrivateMessage = message }; EventManager.Instance.FireBeforePrivateMessage(this, e); if (!e.Cancel) { message = _context.PrivateMessage.Add(message); // We create a sent message that sits in the users sent folder, this is // so that if the receiver deletes the message - The sender still has a record of it. var sentMessage = new PrivateMessage { IsSentMessage = true, DateSent = message.DateSent, Message = message.Message, UserFrom = message.UserFrom, UserTo = message.UserTo }; _context.PrivateMessage.Add(sentMessage); EventManager.Instance.FireAfterPrivateMessage(this, new PrivateMessageEventArgs { PrivateMessage = message }); } // Return the main message return message; }
public bool SendMessage(string msgSubject, string msgText) { bool returnValue; bool result = true; CommonApi refCommonAPI = new CommonApi(); PrivateMessage objPM = new PrivateMessage(refCommonAPI.RequestInformationRef); UserData[] aUsers; string[] userIds = null; int idx = 0; try { if (! (Request.Form["ektouserid" + m_uniqueId] == null)) { userIds = Request.Form["ektouserid" + m_uniqueId].Split(",".ToCharArray()); } if ((userIds == null) || (userIds.Length == 0) || ("" == userIds[0])) { // no recipients selected! result = false; } else { aUsers = (UserData[])Array.CreateInstance(typeof(Ektron.Cms.UserData), userIds.Length); if (0 == msgSubject.Length) { msgSubject = m_refMsg.GetMessage("lbl no subject"); } objPM.Subject = msgSubject; objPM.Message = msgText; objPM.FromUserID = refCommonAPI.RequestInformationRef.UserId; for (idx = 0; idx <= userIds.Length - 1; idx++) { aUsers[idx] = new Ektron.Cms.UserData(); aUsers[idx].Id = Convert.ToInt64((userIds[idx].Trim())); } objPM.Send(aUsers); } } catch (Exception) { result = false; } finally { returnValue = result; refCommonAPI = null; objPM = null; } return returnValue; }
public ActionResult Create(PrivateMessage privatemessage) { if (ModelState.IsValid) { Guid id = (Guid)Membership.GetUser().ProviderUserKey; User user = db.Users.Single(u => u.UserId == id); privatemessage.isRead = false; user.Messages.Add(privatemessage); db.Entry(user).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.WriterId = new SelectList(db.Users, "UserId", "Username", privatemessage.WriterId); return View(privatemessage); }
public ActionResult Create(PNModel pn) { if (ModelState.IsValid) { PrivateMessage p = new PrivateMessage(); p.created = pn.created; p.content = pn.Content; p.title = pn.Headline; p.UserId = pn.UserId; p.WriterId = pn.WriterId; p.isRead = false; db.Messages.Add(p); db.SaveChanges(); return PartialView("Success"); } return PartialView(pn); }
public ActionResult Create(PNModel pn) { if (ModelState.IsValid) { PrivateMessage p = new PrivateMessage(); p.title = pn.Headline; p.content = pn.Content; p.created = pn.created; p.isRead = false; p.UserId = pn.UserId; p.WriterId = pn.WriterId; db.Messages.Add(p); db.SaveChanges(); return RedirectToAction("Index", "Dashboard"); } return View(pn); }
public List<PrivateMessage> Receive(string to) { var privateMessages = new List<PrivateMessage>(); //foreach (var message in database.privateMessages) //{ // if (message.To == to) // { // privateMessages.Add(new PrivateMessage(message.From, message.To, message.Text)); // database.privateMessages.Remove(message); // } //} for (int i = 0; i < database.privateMessages.Count; i++) { if (database.privateMessages[i].To == to) { var message = new PrivateMessage(database.privateMessages[i].From, database.privateMessages[i].To, database.privateMessages[i].Text); privateMessages.Add(message); database.privateMessages.RemoveAt(i); } } return privateMessages; }
public void HoyreFill() { //Viser meldinger fra valgt bruker LoginLib login = new LoginLib(); int useID = login.GetUserID(); Dictionary<String, object> parameter = new Dictionary<string, object>(); parameter.Add("@UserID", useID); DataTable dt = ManageDB.query(@" SELECT Text,Time,Read FROM PrivateMessage WHERE [From]=@UserID AND [To]=@klikkID", parameter, debug: true); PrivateMessage pm = new PrivateMessage(); //if (pm.Text == "Friend request") //{ // MeldingerGV. //} }
internal static PrivateMessage Create(IDataStore dataStore, IApplicationSettings applicationSettings, IApplication application , IUserBasic author, Folder folder, Random random) { PrivateMessageManager manager = new PrivateMessageManager(dataStore); PrivateMessage privateMessage = new PrivateMessage( author , folder , DebugUtility.GetRandomEnum <MessageStatus>(random) , DebugUtility.GetRandomEnum <MessageType>(random) , "PrivateMessage Subject" + random.Next(1000000, 10000000) , "PrivateMessage Body" + random.Next(1000000, 10000000)); BusinessObjectActionReport <DataRepositoryActionStatus> report = manager.Create(privateMessage); Assert.AreEqual(DataRepositoryActionStatus.Success, report.Status); Assert.Greater(privateMessage.PrivateMessageId, 0); PrivateMessage dsPrivateMessage = manager.GetPrivateMessage(privateMessage.PrivateMessageId); Assert.IsNotNull(dsPrivateMessage); return(dsPrivateMessage); }
/// <summary> /// Prepare the private message model /// </summary> /// <param name="pm">Private message</param> /// <returns>Private message model</returns> public virtual PrivateMessageModel PreparePrivateMessageModel(PrivateMessage pm) { if (pm == null) { throw new ArgumentNullException(nameof(pm)); } var model = new PrivateMessageModel { Id = pm.Id, FromCustomerId = pm.FromCustomer.Id, CustomerFromName = pm.FromCustomer.FormatUserName(), AllowViewingFromProfile = _customerSettings.AllowViewingProfiles && pm.FromCustomer != null && !pm.FromCustomer.IsGuest(), ToCustomerId = pm.ToCustomer.Id, CustomerToName = pm.ToCustomer.FormatUserName(), AllowViewingToProfile = _customerSettings.AllowViewingProfiles && pm.ToCustomer != null && !pm.ToCustomer.IsGuest(), Subject = pm.Subject, Message = pm.FormatPrivateMessageText(), CreatedOn = _dateTimeHelper.ConvertToUserTime(pm.CreatedOnUtc, DateTimeKind.Utc), IsRead = pm.IsRead, }; return(model); }
/// <summary> /// Add a private message /// </summary> /// <param name="message"></param> /// <returns></returns> public PrivateMessage Add(PrivateMessage message) { // This is the message that the other user sees message = SanitizeMessage(message); message.DateSent = DateTime.UtcNow; message.IsSentMessage = false; var origMessage = _privateMessageRepository.Add(message); // We create a sent message that sits in the users sent folder, this is // so that if the receiver deletes the message - The sender still has a record of it. var sentMessage = new PrivateMessage { IsSentMessage = true, DateSent = message.DateSent, Message = message.Message, UserFrom = message.UserFrom, UserTo = message.UserTo }; _privateMessageRepository.Add(sentMessage); // Return the main message return(origMessage); }
private void OpenPrivateMessage(string privateMessageId) { ResetAll(); divList.Visible = false; hidPrivateMessageId.Value = privateMessageId; PrivateMessage msg = PrivateMessagesManager.GetPrivateMessage(privateMessageId); if (msg != null) { User currentUser = MembershipManager.GetUserByName(Page.User.Identity.Name); if (currentUser.Id == msg.Recipient.Id || currentUser.Id == msg.Sender.Id) { if (msg.ReadDate == null) { PrivateMessagesManager.MarkAsRead(msg); } divViewPrivateMessage.Visible = true; lblDateSent.Text = PrivateMessagesManager.FormatDateForDisplay(msg.SentDate); lblTo.Text = msg.Recipients; lblFrom.Text = msg.Sender.Name; lblSubject.Text = msg.Subject; txtBody.Text = msg.Body; } else { ((IFeedback)Page.Master).SetError(GetType(), ErrorPermissionDenied); } } else { ((IFeedback)Page.Master).SetError(GetType(), ErrorUnableToOpen); } }
public void Raises_PrivateMessageRecieved_Event_On_ServerPrivateMessage(int id, int timeOffset, string username, string message, bool isAdmin) { var options = new SoulseekClientOptions(autoAcknowledgePrivateMessages: false); var conn = new Mock <IMessageConnection>(); conn.Setup(m => m.WriteMessageAsync(It.IsAny <Message>(), null)) .Returns(Task.CompletedTask); var epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var timestamp = epoch.AddSeconds(timeOffset).ToLocalTime(); var msg = new MessageBuilder() .Code(MessageCode.ServerPrivateMessage) .WriteInteger(id) .WriteInteger(timeOffset) .WriteString(username) .WriteString(message) .WriteByte((byte)(isAdmin ? 1 : 0)) .Build(); using (var s = new SoulseekClient("127.0.0.1", 1, options: options, serverConnection: conn.Object)) { PrivateMessage response = null; s.PrivateMessageReceived += (_, privateMessage) => response = privateMessage; s.InvokeMethod("ServerConnection_MessageRead", null, msg); Assert.NotNull(response); Assert.Equal(id, response.Id); Assert.Equal(timestamp, response.Timestamp); Assert.Equal(username, response.Username); Assert.Equal(message, response.Message); Assert.Equal(isAdmin, response.IsAdmin); } }
public void MarkPMRead(User user, PrivateMessage pm) { PrivateMessageRepository.SetLastViewTime(pm.PMID, user.UserID, DateTime.UtcNow); }
void prot_Update(object sender, FmdcEventArgs e) { switch (e.Action) { case Actions.TransferRequest: if (e.Data is TransferRequest) { TransferRequest req = (TransferRequest)e.Data; if (transferManager.GetTransferReq(req.Key) == null) { transferManager.AddTransferReq(req); } } break; case Actions.TransferStarted: Transfer trans = e.Data as Transfer; if (trans != null) { #if !COMPACT_FRAMEWORK // Security, Windows Mobile doesnt support SSLStream so we disable this feature for it. trans.SecureUpdate += new FmdcEventHandler(trans_SecureUpdate); #endif transferManager.StartTransfer(trans); trans.ProtocolChange += new FmdcEventHandler(trans_ProtocolChange); trans.Protocol.ChangeDownloadItem += new FmdcEventHandler(Protocol_ChangeDownloadItem); trans.Protocol.RequestTransfer += new FmdcEventHandler(Protocol_RequestTransfer); trans.Protocol.Error += new FmdcEventHandler(Protocol_Error); if (Program.DEBUG) { trans.Protocol.MessageReceived += new FmdcEventHandler(Trans_Protocol_MessageReceived); trans.Protocol.MessageToSend += new FmdcEventHandler(Trans_Protocol_MessageToSend); } } break; case Actions.MainMessage: MainMessage msgMain = e.Data as MainMessage; if (CommandHandler.TryHandleMsg(this, msgMain.From, msgMain.Content, Actions.MainMessage)) { // message will here be converted to right format and then be sent. //UpdateBase(this, new FlowLib.Events.FmdcEventArgs(FlowLib.Events.Actions.MainMessage, new MainMessage(hubConnection.Me.ID, msg))); } else { if (!Program.DEBUG) { Program.Write(string.Format("[{0}] <{1}> {2}\r\n", System.DateTime.Now.ToLongTimeString(), msgMain.From, msgMain.Content)); } } break; case Actions.PrivateMessage: PrivateMessage msgPriv = e.Data as PrivateMessage; if (CommandHandler.TryHandleMsg(this, msgPriv.From, msgPriv.Content.Replace("<" + msgPriv.From + "> ", string.Empty), Actions.PrivateMessage)) { // message will here be converted to right format and then be sent. //UpdateBase(this, new FlowLib.Events.FmdcEventArgs(FlowLib.Events.Actions.PrivateMessage, new PrivateMessage(msgPriv.From, hubConnection.Me.ID, msgPM))); } else { if (!Program.DEBUG) { Program.Write(string.Format("[{0}] PM:{1}\r\n", System.DateTime.Now.ToLongTimeString(), msgPriv.Content)); } } break; } }
public PrivateMessage SanitizeMessage(PrivateMessage privateMessage) { privateMessage.Message = StringUtils.GetSafeHtml(privateMessage.Message); return(privateMessage); }
public SendPrivateMessageCommandHandler(PrivateMessage message) { this.message = message; }
public ActionResult Edit(PrivateMessage privatemessage) { if (ModelState.IsValid) { db.Entry(privatemessage).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.WriterId = new SelectList(db.Users, "UserId", "Username", privatemessage.WriterId); return View(privatemessage); }
private void detach_PrivateMessages1(PrivateMessage entity) { this.SendPropertyChanging(); entity.User1 = null; }
public ActionResult Create(CreatePrivateMessageViewModel createPrivateMessageViewModel) { if (!SettingsService.GetSettings().EnablePrivateMessages || LoggedOnUser.DisablePrivateMessages == true) { return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage"))); } using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { if (ModelState.IsValid) { var userTo = createPrivateMessageViewModel.UserToUsername; // first check they are not trying to message themself! if (userTo.ToLower() != LoggedOnUser.UserName.ToLower()) { // Map the view model to message var privateMessage = new PrivateMessage { UserFrom = LoggedOnUser, Subject = createPrivateMessageViewModel.Subject, Message = createPrivateMessageViewModel.Message, }; // now get the user its being sent to var memberTo = MembershipService.GetUser(userTo); // check the member if (memberTo != null) { // Check in box size for both var receiverCount = _privateMessageService.GetAllReceivedByUser(memberTo.Id).Count; if (receiverCount > SettingsService.GetSettings().MaxPrivateMessagesPerMember) { ModelState.AddModelError(string.Empty, string.Format(LocalizationService.GetResourceString("PM.ReceivedItemsOverCapcity"), memberTo.UserName)); } else { // If the receiver is about to go over the allowance them let then know too if (receiverCount > (SettingsService.GetSettings().MaxPrivateMessagesPerMember - SiteConstants.PrivateMessageWarningAmountLessThanAllowedSize)) { // Send user a warning they are about to exceed var sb = new StringBuilder(); sb.AppendFormat("<p>{0}</p>", LocalizationService.GetResourceString("PM.AboutToExceedInboxSizeBody")); var email = new Email { EmailFrom = SettingsService.GetSettings().AdminEmailAddress, EmailTo = memberTo.Email, NameTo = memberTo.UserName, Subject = LocalizationService.GetResourceString("PM.AboutToExceedInboxSizeSubject") }; email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString()); _emailService.SendMail(email); } // Good to go send the message! privateMessage.UserTo = memberTo; _privateMessageService.Add(privateMessage); try { TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("PM.MessageSent"), MessageType = GenericMessages.success }; unitOfWork.Commit(); // Finally send an email to the user so they know they have a new private message // As long as they have not had notifications disabled if (memberTo.DisableEmailNotifications != true) { var email = new Email { EmailFrom = SettingsService.GetSettings().NotificationReplyEmail, EmailTo = memberTo.Email, Subject = LocalizationService.GetResourceString("PM.NewPrivateMessageSubject"), NameTo = memberTo.UserName }; var sb = new StringBuilder(); sb.AppendFormat("<p>{0}</p>", string.Format(LocalizationService.GetResourceString("PM.NewPrivateMessageBody"), LoggedOnUser.UserName)); email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString()); _emailService.SendMail(email); } return(RedirectToAction("Index")); } catch (Exception ex) { unitOfWork.Rollback(); LoggingService.Error(ex); ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage")); } } } else { // Error send back to user ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("PM.UnableFindMember")); } } else { ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("PM.TalkToSelf")); } } TempData[AppConstants.MessageViewBagName] = null; return(View(createPrivateMessageViewModel)); } }
protected void LoadMsg() { try { if ((m_id.Length > 0) && (Ektron.Cms.Common.EkFunctions.IsNumeric(m_id))) { PrivateMessage aMsg = new PrivateMessage(); CommonApi refCommonAPI = new CommonApi(); PrivateMessage objPM = new PrivateMessage(refCommonAPI.RequestInformationRef); objPM.GetByMessageID(Convert.ToInt64(m_id)); aMsg = IsMyMessage(objPM); if (aMsg.FromUserDeleted) { m_bCanReply = false; } StringBuilder msgHeader = new StringBuilder(); msgHeader.AppendLine("<table class=\"ViewMsgHeader ektronGrid\" cellspacing=\"0\">"); msgHeader.AppendLine("<tbody>"); // Add From and Sent msgHeader.AppendLine("<tr>"); msgHeader.AppendLine("<td class=\"ViewMsgLabel label\">" + m_refMsg.GetMessage("generic from label") + "</td>"); msgHeader.AppendLine("<td><div class=\"ViewMsgDate\"><span class=\"ViewMsgLabel\">" + m_refMsg.GetMessage("generic sent label") + "</span>" + aMsg.DateCreated + "</div>" + aMsg.FromUserDisplayName + "</td>"); msgHeader.AppendLine("</tr>"); // Add To msgHeader.AppendLine("<tr>"); msgHeader.Append("<td class=\"ViewMsgLabel label\">" + m_refMsg.GetMessage("generic to label") + "</td>"); msgHeader.Append("<td>" + aMsg.GetFormattedRecipientList(";") + "</td>"); msgHeader.AppendLine("</tr>"); // Add Subject msgHeader.AppendLine("<tr>"); msgHeader.Append("<td class=\"ViewMsgLabel label\">" + m_refMsg.GetMessage("generic subject label") + "</td>"); msgHeader.Append("<td>" + aMsg.Subject + "</td>"); msgHeader.AppendLine("</tr>"); msgHeader.AppendLine("</tbody>"); msgHeader.AppendLine("</table>"); ltrMsgView.Text = "<div class=\"ViewMsgContainer\">"; ltrMsgView.Text += msgHeader.ToString(); ltrMsgView.Text += "<hr class=\"ViewMsgHR\"/>"; ltrMsgView.Text += "<div class=\"ViewMsgMessage\">" + HttpUtility.UrlDecode(aMsg.Message) + "</div>"; ltrMsgView.Text += "</div>"; aMsg.MarkAsRead(); } } catch (Exception) { } finally { } }
protected PrivateMessage IsMyMessage(PrivateMessage msg) { PrivateMessage returnValue; PrivateMessage result = null; try { if (msg.FromUserID == m_userId || (msg.IsARecipient(m_userId)) || (Ektron.Cms.Common.EkFunctions.IsNumeric(m_msgUserId) && msg.IsARecipient(Convert.ToInt64(m_msgUserId)))) { result = msg; } } catch (Exception) { result = null; } finally { if (result == null) { result = new PrivateMessage(); } returnValue = result; } return returnValue; }
public PrivateMessageVM() { PrivateMessage PM = new PrivateMessage(); }
partial void DeletePrivateMessage(PrivateMessage instance);
partial void UpdatePrivateMessage(PrivateMessage instance);
partial void InsertPrivateMessage(PrivateMessage instance);
public List <PrivateMessagePost> GetPosts(PrivateMessage pm) { return(PrivateMessageRepository.GetPosts(pm.PMID)); }
protected void Page_Load(object sender, System.EventArgs e) { CommonApi refCommonAPI = new CommonApi(); m_userId = refCommonAPI.RequestInformationRef.UserId; m_refMsg = (new CommonApi()).EkMsgRef; RegisterResources(); if (! (Request.QueryString["id"] == null)) { m_id = (string) (Request.QueryString["id"].ToLower()); } if (! (Request.QueryString["userid"] == null)) { m_msgUserId = (string) (Request.QueryString["userid"].ToLower().Trim()); } else { m_msgUserId = m_userId.ToString(); } if (! (Request.QueryString["mode"] == null)) { m_mode = (string) (Request.QueryString["mode"].ToLower()); } if ("prev" == m_mode) { m_prev = true; } else if ("next" == m_mode) { m_next = true; } if (("del" == m_mode) && (m_id.Trim().Length > 0) && Ektron.Cms.Common.EkFunctions.IsNumeric(m_id)) { long[] delList = new long[] {(Convert.ToInt64(m_id))}; PrivateMessage objPM = new PrivateMessage(refCommonAPI.RequestInformationRef); objPM.DeleteMessageList(delList, m_sentMode); refCommonAPI = null; objPM = null; Response.ClearContent(); Response.Redirect((string) ("CommunityMessaging.aspx?action=" + (SentMode ? "viewallsent" : "viewall")), false); } else { LoadMsg(); LoadToolBar(); } refCommonAPI = null; m_refMsg = null; }
public SendPrivateRequest(PrivateMessage message) { this.message = message; }
public PrivateMessageEventArgs(IrcMessage ircMessage) { IrcMessage = ircMessage; PrivateMessage = new PrivateMessage(IrcMessage); }
private void Protocol_Update(object sender, FmdcEventArgs e) { switch (e.Action) { case Actions.MainMessage: { MainMessage zprava = e.Data as MainMessage; if (zprava.Content.StartsWith(HandlerPrikazu.PrikazPrefix) && zprava.Content.Length > 1) { ThreadPool.QueueUserWorkItem(m_ThreadPoolCallback, new ArgumentyHandleru(zprava.Content.Remove(0, 1).Trim(), zprava.From, this)); } #if DEBUG if (zprava.From == "AdminChar" || zprava.From == "VerliHub") { m_Gui.VypisRadek(zprava.Content); } #endif break; } case Actions.PrivateMessage: { PrivateMessage zprava = e.Data as PrivateMessage; if (zprava.From == m_Hub.HubSetting.DisplayName) //tohle je od novй verze 4 FlowLibu nutnй protoЮe on si posнlб jakoby vlastnн PMka { break; } string text = zprava.Content.Replace(string.Format("<{0}> ", zprava.From), ""); if (text.StartsWith(HandlerPrikazu.PrikazPrefix) && text.Length > 1) { ThreadPool.QueueUserWorkItem(m_ThreadPoolCallback, new ArgumentyHandleru(text.Remove(0, 1).Trim(), zprava.From, this)); } else if (zprava.From != "AdminChar" && zprava.From != "VerliHub") { PrivateZprava(zprava.From, string.Concat("Jsem jen tupэ bot. Pro seznam pшнkazщ napiЪ ", HandlerPrikazu.PrikazPrefix, "help")); } #if DEBUG if (zprava.From == "AdminChar" || zprava.From == "VerliHub") { m_Gui.VypisRadek(text); } #endif break; } case Actions.SearchResult: case Actions.Search: { m_Gui.VypisRadek("SEARCH"); if (e.Data is SearchInfo) { SearchInfo info = e.Data as SearchInfo; } if (e.Data is SearchResultInfo) { SearchResultInfo info = e.Data as SearchResultInfo; } break; } case Actions.TransferStarted: Transfer trans = e.Data as Transfer; if (trans != null) { //m_Gui.VypisRadek(trans.RemoteAddress.Address.ToString()); m_TransferManager.StartTransfer(trans); } break; } }
protected string FormatByStatus(ref PrivateMessage msg, bool sendingMode) { string result = LimitSubjectLength(msg.Subject); if (! sendingMode) { if (HasRead(msg)) { result = "<i>" + result + "</i>"; } else { result = "<b>" + result + "</b><img src=\'images\\UI\\Icons\\email.png\' style=\'margin-left: 15px;\' />"; } } return result; }
protected PrivateMessage IsMyMessage(PrivateMessage msg) { PrivateMessage returnValue; PrivateMessage result = null; try { if (msg.FromUserID == m_userId || msg.IsARecipient(m_userId)) { result = msg; } } catch (Exception) { result = null; } finally { if (result == null) { result = new Ektron.Cms.Content.PrivateMessage(); } returnValue = result; } return returnValue; }
protected bool HasRead(PrivateMessage msg) { bool result = false; foreach (Ektron.Cms.PrivateMessageRecipientData target in msg.Recipients) { if (target.ToUserID == this.m_userId) { result = target.Read; break; } } return result; }
public ActionResult Create(CreatePrivateMessageViewModel createPrivateMessageViewModel) { if (!Settings.AllowPrivateMessages || CurrentMember.DisablePrivateMessages) { return(ErrorToHomePage(Lang("Errors.GenericMessage"))); } using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { if (ModelState.IsValid) { var userTo = createPrivateMessageViewModel.UserToUsername; // first check they are not trying to message themself! if (!string.Equals(userTo, CurrentMember.UserName, StringComparison.CurrentCultureIgnoreCase)) { // Map the view model to message var privateMessage = new PrivateMessage { MemberFrom = CurrentMember, MemberFromId = CurrentMember.Id, Subject = createPrivateMessageViewModel.Subject, Message = createPrivateMessageViewModel.Message }; // now get the user its being sent to var memberTo = MemberService.Get(userTo); // check the member if (memberTo != null) { // Check in box size // First check sender var receiverCount = PrivateMessageService.GetAllReceivedByUser(memberTo.Id).Count; if (receiverCount > Settings.PrivateMessageInboxSize) { ModelState.AddModelError(string.Empty, string.Format(Lang("PM.ReceivedItemsOverCapcity"), memberTo.UserName)); } else { // Good to go send the message! privateMessage.MemberTo = memberTo; privateMessage.MemberToId = memberTo.Id; PrivateMessageService.Add(privateMessage); try { ShowMessage(new GenericMessageViewModel { Message = Lang("PM.MessageSent"), MessageType = GenericMessages.Success }); unitOfWork.Commit(); // Finally send an email to the user so they know they have a new private message // As long as they have not had notifications disabled if (memberTo.DisableEmailNotifications != true) { var email = new Email { EmailFrom = Settings.NotificationReplyEmailAddress, EmailTo = memberTo.Email, Subject = Lang("PM.NewPrivateMessageSubject"), NameTo = memberTo.UserName }; var sb = new StringBuilder(); sb.AppendFormat("<p>{0}</p>", string.Format(Lang("PM.NewPrivateMessageBody"), CurrentMember.UserName)); email.Body = EmailService.EmailTemplate(email.NameTo, sb.ToString()); EmailService.SendMail(email); } return(Redirect(Urls.GenerateUrl(Urls.UrlType.MessageInbox))); } catch (Exception ex) { unitOfWork.Rollback(); LogError(ex); ModelState.AddModelError(string.Empty, Lang("Errors.GenericMessage")); } } } else { // Error send back to user ModelState.AddModelError(string.Empty, Lang("PM.UnableFindMember")); } } else { ModelState.AddModelError(string.Empty, Lang("PM.TalkToSelf")); } } ShowMessage(); return(Redirect(Urls.GenerateUrl(Urls.UrlType.MessageCreate))); } }
protected void Page_Load(object sender, System.EventArgs e) { CommonApi refCommonAPI = new CommonApi(); m_userId = refCommonAPI.RequestInformationRef.UserId; m_refMsg = (new CommonApi()).EkMsgRef; RegisterResources(); if (! (Request.QueryString["mode"] == null)) { m_mode = (string) (Request.QueryString["mode"].ToLower()); } if (! (Request.QueryString["action"] == null)) { m_action = (string) (Request.QueryString["action"].ToLower()); } if (("del" == m_mode) && (! (Request.Form["MsgInboxSelCBHdn"] == null) ) && (Request.Form["MsgInboxSelCBHdn"].Trim().Length > 0)) { string[] sDelList = Request.Form["MsgInboxSelCBHdn"].Trim().Split(",".ToCharArray()); int idx; long[] delList = new long[sDelList.Length]; //long[] delList = Array.CreateInstance(typeof(long), sDelList.Length); for (idx = 0; idx <= sDelList.Length - 1; idx++) { if (Ektron.Cms.Common.EkFunctions.IsNumeric(sDelList[idx])) { delList.SetValue(Convert.ToInt64(sDelList[idx]), idx); } } PrivateMessage objPM = new PrivateMessage(refCommonAPI.RequestInformationRef); objPM.DeleteMessageList(delList, _SentMode); refCommonAPI = null; objPM = null; Response.ClearContent(); if (m_action.Length == 0) { m_action = "viewall"; } Response.Redirect((string) ("CommunityMessaging.aspx?action=" + m_action), false); } else { LoadToolBar(); LoadGrid(); } }
/// <summary> /// Delete a private message /// </summary> /// <param name="message"></param> public void DeleteMessage(PrivateMessage message) { _context.PrivateMessage.Remove(message); }
protected ICollection CreateMsgData() { ICollection returnValue; DataTable dt = new DataTable(); DataRow dr; string ListCheckboxes = ""; string Name = ""; string msgUserId = ""; try { // header: dt.Columns.Add(new DataColumn("fDelete", typeof(string))); dt.Columns.Add(new DataColumn("fFrom", typeof(string))); dt.Columns.Add(new DataColumn("fSubject", typeof(string))); dt.Columns.Add(new DataColumn("fDate", typeof(string))); // data: CommonApi m_refCommonAPI = new CommonApi(); PrivateMessage objPM = new PrivateMessage(m_refCommonAPI.RequestInformationRef); PrivateMessage[] aMessages = new PrivateMessage[0]; //PrivateMessage[] aMessages = Array.CreateInstance(typeof(Ektron.Cms.Content.PrivateMessage), 0); aMessages = objPM.GetMessagesForMe(SentMode ? 1 : 0, 0); // inbox=0/sent=1. int idx = 0; for (idx = 0; idx <= aMessages.Length - 1; idx++) { dr = dt.NewRow(); Name = (string) ("MsgInboxCB_" + idx.ToString()); if (ListCheckboxes.Length > 0) { ListCheckboxes = ListCheckboxes + "," + Name; } else { ListCheckboxes = Name; } dr[0] = "<input type=\"checkbox\" onclick=\"MsgInboxToggleCB(this);\" className=\"inboxRowCB\" name=\"" + Name + "\" value=\"" + aMessages[idx].ID.ToString() + "\" runat=\"Server\"/>"; if (SentMode) { dr[1] = aMessages[idx].GetFormattedRecipientList(";"); } else { dr[1] = aMessages[idx].FromUserDisplayName; } // msgUserId = aMessages(idx).ToUserID.ToString() dr[2] = "<a href=\"CommunityMessaging.aspx?action=" + (SentMode ? "viewsentmsg" : "viewmsg") + "&id=" + aMessages[idx].ID.ToString() + "&userid=" + msgUserId + "\" target=\"_self\" >" + FormatByStatus(ref aMessages[idx], SentMode) + "</a>"; dr[3] = aMessages[idx].DateCreated; dt.Rows.Add(dr); } } catch (Exception) { } finally { returnValue = new DataView(dt); } return returnValue; }
public BusinessObjectActionReport <DataRepositoryActionStatus> Delete(PrivateMessage privateMessage) { return(_CMSContentManager.Delete(privateMessage.CMSContent, false)); }
public void SendRequest(int userID) { if (userID < 0) { // FEIL } LoginLib login = new LoginLib(); int visitedUserId = -1; if (userID != login.GetUserID()) { visitedUserId = userID; } GaymerLINQDataContext db = new GaymerLINQDataContext(); //var meldinger = (from pm in db.PrivateMessages // where pm.From == login.GetUserID() // select pm).FirstOrDefault(); PrivateMessage pmeld = new PrivateMessage(); int userId= login.GetUserID(); pmeld.To = visitedUserId; pmeld.Text = "Friend request"; DateTime Time = System.DateTime.Now; pmeld.Read = false; var p = new Dictionary<string, object>(); p.Add("@UserId", userId); p.Add("@VisitUserId", visitedUserId); p.Add("@Time",Time); int nyrequest = ManageDB.nonQuery(@" INSERT INTO PrivateMessage([From],[To],[Text],Time,[Read]) VALUES (@UserId,@VisitUserId,'Friend request',@Time,'False')",p,debug:true); //db.PrivateMessages.InsertOnSubmit(meldinger); //try //{ // db.SubmitChanges(); //} //catch (Exception ab) //{ // Response.Redirect("UserPage.aspx?db_feil"); //} }
public bool IsUserInPM(User user, PrivateMessage pm) { var pmUsers = PrivateMessageRepository.GetUsers(pm.PMID); return(pmUsers.Where(p => p.UserID == user.UserID).Count() != 0); }
public ActionResult Create(CreatePrivateMessageViewModel createPrivateMessageViewModel) { var settings = SettingsService.GetSettings(); if (!settings.EnablePrivateMessages || LoggedOnReadOnlyUser.DisablePrivateMessages == true) { throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage")); } using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { if (ModelState.IsValid) { var loggedOnUser = MembershipService.GetUser(LoggedOnReadOnlyUser.Id); var memberTo = MembershipService.GetUser(createPrivateMessageViewModel.To); // Check the user they are trying to message hasn't blocked them if (loggedOnUser.BlockedByOtherUsers.Any(x => x.Blocker.Id == memberTo.Id)) { return(Content(PmAjaxError(LocalizationService.GetResourceString("PM.BlockedMessage")))); } // Check flood control var lastMessage = _privateMessageService.GetLastSentPrivateMessage(LoggedOnReadOnlyUser.Id); // If this message they are sending now, is to the same person then ignore flood control if (lastMessage != null && createPrivateMessageViewModel.To != lastMessage.UserTo.Id) { if (DateUtils.TimeDifferenceInSeconds(DateTime.UtcNow, lastMessage.DateSent) < settings.PrivateMessageFloodControl) { return(Content(PmAjaxError(LocalizationService.GetResourceString("PM.SendingToQuickly")))); } } // first check they are not trying to message themself! if (memberTo != null) { // Map the view model to message var privateMessage = new PrivateMessage { UserFrom = loggedOnUser, Message = createPrivateMessageViewModel.Message, }; // Check settings if (settings.EnableEmoticons == true) { privateMessage.Message = _configService.Emotify(privateMessage.Message); } // check the member if (!String.Equals(memberTo.UserName, LoggedOnReadOnlyUser.UserName, StringComparison.CurrentCultureIgnoreCase)) { // Check in box size for both var receiverCount = _privateMessageService.GetAllReceivedByUser(memberTo.Id).Count; if (receiverCount > settings.MaxPrivateMessagesPerMember) { return(Content(string.Format(LocalizationService.GetResourceString("PM.ReceivedItemsOverCapcity"), memberTo.UserName))); } // If the receiver is about to go over the allowance them let then know too if (receiverCount > (settings.MaxPrivateMessagesPerMember - SiteConstants.Instance.PrivateMessageWarningAmountLessThanAllowedSize)) { // Send user a warning they are about to exceed var sb = new StringBuilder(); sb.Append($"<p>{LocalizationService.GetResourceString("PM.AboutToExceedInboxSizeBody")}</p>"); var email = new Email { EmailTo = memberTo.Email, NameTo = memberTo.UserName, Subject = LocalizationService.GetResourceString("PM.AboutToExceedInboxSizeSubject") }; email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString()); _emailService.SendMail(email); } // Good to go send the message! privateMessage.UserTo = memberTo; _privateMessageService.Add(privateMessage); try { // Finally send an email to the user so they know they have a new private message // As long as they have not had notifications disabled if (memberTo.DisableEmailNotifications != true) { var email = new Email { EmailTo = memberTo.Email, Subject = LocalizationService.GetResourceString("PM.NewPrivateMessageSubject"), NameTo = memberTo.UserName }; var sb = new StringBuilder(); sb.Append($"<p>{string.Format(LocalizationService.GetResourceString("PM.NewPrivateMessageBody"), LoggedOnReadOnlyUser.UserName)}</p>"); sb.Append(AppHelpers.ConvertPostContent(createPrivateMessageViewModel.Message)); email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString()); _emailService.SendMail(email); } unitOfWork.Commit(); return(PartialView("_PrivateMessage", privateMessage)); } catch (Exception ex) { unitOfWork.Rollback(); LoggingService.Error(ex); return(Content(PmAjaxError(LocalizationService.GetResourceString("Errors.GenericMessage")))); } } else { return(Content(PmAjaxError(LocalizationService.GetResourceString("PM.TalkToSelf")))); } } else { // Error send back to user return(Content(PmAjaxError(LocalizationService.GetResourceString("PM.UnableFindMember")))); } } return(Content(PmAjaxError(LocalizationService.GetResourceString("Errors.GenericMessage")))); } }
public void Unarchive(User user, PrivateMessage pm) { PrivateMessageRepository.SetArchive(pm.PMID, user.UserID, false); }
private static void Client_OnPrivateMessage(PrivateMessage msg) { ConsoleHelper.WriteLine("收到私信:{0}", msg.Content); }
public void Configure( IApplicationBuilder app, IWebHostEnvironment env, IApiVersionDescriptionProvider provider, ITransferTracker tracker, IBrowseTracker browseTracker, IConversationTracker conversationTracker, IRoomTracker roomTracker) { if (!env.IsDevelopment()) { app.UseHsts(); } app.UseCors("AllowAll"); BasePath = BasePath ?? "/"; BasePath = BasePath.StartsWith("/") ? BasePath : $"/{BasePath}"; app.UsePathBase(BasePath); // remove any errant double forward slashes which may have been introduced // by a reverse proxy or having the base path removed app.Use(async(context, next) => { var path = context.Request.Path.ToString(); if (path.StartsWith("//")) { context.Request.Path = new string(path.Skip(1).ToArray()); } await next(); }); WebRoot = WebRoot ?? Path.Combine(Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).AbsolutePath), "wwwroot"); Console.WriteLine($"Serving static content from {WebRoot}"); var fileServerOptions = new FileServerOptions { FileProvider = new PhysicalFileProvider(WebRoot), RequestPath = "", EnableDirectoryBrowsing = false, EnableDefaultFiles = true }; app.UseFileServer(fileServerOptions); app.UseAuthentication(); app.UseMvc(); app.UseSwagger(); app.UseSwaggerUI(options => provider.ApiVersionDescriptions.ToList() .ForEach(description => options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName))); // if we made it this far and the route still wasn't matched, return the index // this is required so that SPA routing (React Router, etc) can work properly app.Use(async(context, next) => { // exclude API routes which are not matched or return a 404 if (!context.Request.Path.StartsWithSegments("/api")) { context.Request.Path = "/"; } await next(); }); app.UseFileServer(fileServerOptions); // --------------------------------------------------------------------------------------------------------------------------------------------- // begin SoulseekClient implementation // --------------------------------------------------------------------------------------------------------------------------------------------- var connectionOptions = new ConnectionOptions( readBufferSize: ReadBufferSize, writeBufferSize: WriteBufferSize, connectTimeout: ConnectTimeout, inactivityTimeout: InactivityTimeout); // create options for the client. // see the implementation of Func<> and Action<> options for detailed info. var clientOptions = new SoulseekClientOptions( listenPort: ListenPort, userEndPointCache: new UserEndPointCache(), distributedChildLimit: DistributedChildLimit, enableDistributedNetwork: EnableDistributedNetwork, minimumDiagnosticLevel: DiagnosticLevel, autoAcknowledgePrivateMessages: false, serverConnectionOptions: connectionOptions, peerConnectionOptions: connectionOptions, transferConnectionOptions: connectionOptions, userInfoResponseResolver: UserInfoResponseResolver, browseResponseResolver: BrowseResponseResolver, directoryContentsResponseResolver: DirectoryContentsResponseResolver, enqueueDownloadAction: (username, endpoint, filename) => EnqueueDownloadAction(username, endpoint, filename, tracker), searchResponseResolver: SearchResponseResolver); Client = new SoulseekClient(options: clientOptions); // bind the DiagnosticGenerated event so we can trap and display diagnostic messages. this is optional, and if the event // isn't bound the minimumDiagnosticLevel should be set to None. Client.DiagnosticGenerated += (e, args) => { lock (ConsoleSyncRoot) { if (args.Level == DiagnosticLevel.Debug) { Console.ForegroundColor = ConsoleColor.DarkGray; } if (args.Level == DiagnosticLevel.Warning) { Console.ForegroundColor = ConsoleColor.Yellow; } Console.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] [DIAGNOSTIC:{e.GetType().Name}] [{args.Level}] {args.Message}"); Console.ResetColor(); } }; // bind transfer events. see TransferStateChangedEventArgs and TransferProgressEventArgs. Client.TransferStateChanged += (e, args) => { var direction = args.Transfer.Direction.ToString().ToUpper(); var user = args.Transfer.Username; var file = Path.GetFileName(args.Transfer.Filename); var oldState = args.PreviousState; var state = args.Transfer.State; var completed = args.Transfer.State.HasFlag(TransferStates.Completed); Console.WriteLine($"[{direction}] [{user}/{file}] {oldState} => {state}{(completed ? $" ({args.Transfer.BytesTransferred}/{args.Transfer.Size} = {args.Transfer.PercentComplete}%) @ {args.Transfer.AverageSpeed.SizeSuffix()}/s" : string.Empty)}"); }; Client.TransferProgressUpdated += (e, args) => { // this is really verbose. // Console.WriteLine($"[{args.Transfer.Direction.ToString().ToUpper()}] [{args.Transfer.Username}/{Path.GetFileName(args.Transfer.Filename)}] {args.Transfer.BytesTransferred}/{args.Transfer.Size} {args.Transfer.PercentComplete}% {args.Transfer.AverageSpeed}kb/s"); }; // bind BrowseProgressUpdated to track progress of browse response payload transfers. // these can take a while depending on number of files shared. Client.BrowseProgressUpdated += (e, args) => { browseTracker.AddOrUpdate(args.Username, args); }; // bind UserStatusChanged to monitor the status of users added via AddUserAsync(). Client.UserStatusChanged += (e, args) => { // Console.WriteLine($"[USER] {args.Username}: {args.Status}"); }; Client.PrivateMessageReceived += (e, args) => { conversationTracker.AddOrUpdate(args.Username, PrivateMessage.FromEventArgs(args)); }; Client.RoomMessageReceived += (e, args) => { var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow); roomTracker.AddOrUpdateMessage(args.RoomName, message); }; Client.RoomJoined += (e, args) => { if (args.Username != Username) // this will fire when we join a room; track that through the join operation. { roomTracker.TryAddUser(args.RoomName, args.UserData); } }; Client.RoomLeft += (e, args) => { roomTracker.TryRemoveUser(args.RoomName, args.Username); }; Client.Disconnected += async(e, args) => { Console.WriteLine($"Disconnected from Soulseek server: {args.Message}"); // don't reconnect if the disconnecting Exception is either of these types. // if KickedFromServerException, another client was most likely signed in, and retrying will cause a connect loop. // if ObjectDisposedException, the client is shutting down. if (!(args.Exception is KickedFromServerException || args.Exception is ObjectDisposedException)) { Console.WriteLine($"Attepting to reconnect..."); await Client.ConnectAsync(Username, Password); } }; Task.Run(async() => { await Client.ConnectAsync(Username, Password); }).GetAwaiter().GetResult(); Console.WriteLine($"Connected and logged in."); }
protected PrivateMessage GetMyMsg(PrivateMessage[] msgs) { PrivateMessage returnValue; PrivateMessage result = null; int idx; try { if (m_forwarding) { if ((msgs != null) && (msgs.Length > 0)) { for (idx = 0; idx <= msgs.Length - 1; idx++) { if (msgs[idx].IsARecipient(Convert.ToInt64( Request.QueryString["userid"]))) { result = msgs[idx]; break; } } } } if (m_forwarding == false) { if ((msgs != null) && (msgs.Length > 0)) { for (idx = 0; idx <= msgs.Length - 1; idx++) { if (msgs[idx].IsARecipient(m_userId)) { result = msgs[idx]; break; } } } } } catch (Exception) { result = null; } finally { if (result == null) { result = new PrivateMessage(); } returnValue = result; } return returnValue; }
/// <summary> /// Prepare the send private message model /// </summary> /// <param name="customerTo">Customer, recipient of the message</param> /// <param name="replyToPM">Private message, pass if reply to a previous message is need</param> /// <returns>Send private message model</returns> public virtual SendPrivateMessageModel PrepareSendPrivateMessageModel(Customer customerTo, PrivateMessage replyToPM) { if (customerTo == null) { throw new ArgumentNullException(nameof(customerTo)); } var model = new SendPrivateMessageModel { ToCustomerId = customerTo.Id, CustomerToName = _customerService.FormatUserName(customerTo), AllowViewingToProfile = _customerSettings.AllowViewingProfiles && !customerTo.IsGuest() }; if (replyToPM == null) { return(model); } if (replyToPM.ToCustomerId == _workContext.CurrentCustomer.Id || replyToPM.FromCustomerId == _workContext.CurrentCustomer.Id) { model.ReplyToMessageId = replyToPM.Id; model.Subject = $"Re: {replyToPM.Subject}"; } return(model); }
/// <summary> /// Finds a message type to handle the message. /// </summary> public ReceivableMessage Process() { // Named messages. if (NickMessage.CanProcess(this)) { return(new NickMessage(this)); } if (QuitMessage.CanProcess(this)) { return(new QuitMessage(this)); } if (JoinMessage.CanProcess(this)) { return(new JoinMessage(this)); } if (PartMessage.CanProcess(this)) { return(new PartMessage(this)); } if (PrivateMessage.CanProcess(this)) { return(new PrivateMessage(this)); } if (PingMessage.CanProcess(this)) { return(new PingMessage(this)); } if (NoticeMessage.CanProcess(this)) { return(new NoticeMessage(this)); } if (UserModeMessage.CanProcess(this)) { return(new UserModeMessage(this)); } if (ChannelModeMessage.CanProcess(this)) { return(new ChannelModeMessage(this)); } if (KickMessage.CanProcess(this)) { return(new KickMessage(this)); } if (InviteMessage.CanProcess(this)) { return(new InviteMessage(this)); } if (OperwallMessage.CanProcess(this)) { return(new OperwallMessage(this)); } if (Receive.TopicMessage.CanProcess(this)) { return(new Receive.TopicMessage(this)); } // IRCv3 messages. if (Receive.v3.CapabilityMessage.CanProcess(this)) { return(new Receive.v3.CapabilityMessage(this)); } if (Receive.v3.AwayMessage.CanProcess(this)) { return(new Receive.v3.AwayMessage(this)); } // Numerics. if (NumericMessage.CanProcess(this)) { // Pass all numeric messages to NumericMessage so an event can be fired, then pass it to more specific instances. // ReSharper disable once ObjectCreationAsStatement new NumericMessage(this); if (WelcomeMessage.CanProcess(this)) { return(new WelcomeMessage(this)); } if (YourHostMessage.CanProcess(this)) { return(new YourHostMessage(this)); } if (CreatedMessage.CanProcess(this)) { return(new CreatedMessage(this)); } if (MyInfoMessage.CanProcess(this)) { return(new MyInfoMessage(this)); } if (SupportMessage.CanProcess(this)) { return(new SupportMessage(this)); } if (BounceMessage.CanProcess(this)) { return(new BounceMessage(this)); } if (MOTDEndMessage.CanProcess(this)) { return(new MOTDEndMessage(this)); } if (MOTDStartMessage.CanProcess(this)) { return(new MOTDStartMessage(this)); } if (MOTDMessage.CanProcess(this)) { return(new MOTDMessage(this)); } if (LUserMessage.CanProcess(this)) { return(new LUserMessage(this)); } if (NamesMessage.CanProcess(this)) { return(new NamesMessage(this)); } if (EndOfNamesMessage.CanProcess(this)) { return(new EndOfNamesMessage(this)); } if (TopicMessage.CanProcess(this)) { return(new TopicMessage(this)); } if (TopicWhoTimeMessage.CanProcess(this)) { return(new TopicWhoTimeMessage(this)); } if (ListMessage.CanProcess(this)) { return(new ListMessage(this)); } if (ListEndMessage.CanProcess(this)) { return(new ListEndMessage(this)); } if (YoureOperMessage.CanProcess(this)) { return(new YoureOperMessage(this)); } if (AwayMessage.CanProcess(this)) { return(new AwayMessage(this)); } if (UnAwayMessage.CanProcess(this)) { return(new UnAwayMessage(this)); } if (NowAwayMessage.CanProcess(this)) { return(new NowAwayMessage(this)); } if (ChannelModeIsMessage.CanProcess(this)) { return(new ChannelModeIsMessage(this)); } if (UModeIsMessage.CanProcess(this)) { return(new UModeIsMessage(this)); } if (VersionMessage.CanProcess(this)) { return(new VersionMessage(this)); } if (TimeMessage.CanProcess(this)) { return(new TimeMessage(this)); } if (WhoMessage.CanProcess(this)) { return(new WhoMessage(this)); } if (WhoisMessage.CanProcess(this)) { return(new WhoisMessage(this)); } if (EndOfWhoMessage.CanProcess(this)) { return(new EndOfWhoMessage(this)); } if (EndOfWhoisMessage.CanProcess(this)) { return(new EndOfWhoisMessage(this)); } if (BanListMessage.CanProcess(this)) { return(new BanListMessage(this)); } if (EndOfBanListMessage.CanProcess(this)) { return(new EndOfBanListMessage(this)); } if (InviteListMessage.CanProcess(this)) { return(new InviteListMessage(this)); } if (EndOfInviteListMessage.CanProcess(this)) { return(new EndOfInviteListMessage(this)); } if (ExceptListMessage.CanProcess(this)) { return(new ExceptListMessage(this)); } if (EndOfExceptListMessage.CanProcess(this)) { return(new EndOfExceptListMessage(this)); } if (IsOnMessage.CanProcess(this)) { return(new IsOnMessage(this)); } // Catch all for unhandled error messages. if (ErrorMessage.CanProcess(this)) { return(new ErrorMessage(this)); } } Console.WriteLine("Message handler for \"" + Text + "\" not found."); return(null); }
public virtual IActionResult SendPM(SendPrivateMessageModel model) { if (!_forumSettings.AllowPrivateMessages) { return(RedirectToRoute("Homepage")); } if (_workContext.CurrentCustomer.IsGuest()) { return(Challenge()); } Customer toCustomer; var replyToPM = _forumService.GetPrivateMessageById(model.ReplyToMessageId); if (replyToPM != null) { //reply to a previous PM if (replyToPM.ToCustomerId == _workContext.CurrentCustomer.Id || replyToPM.FromCustomerId == _workContext.CurrentCustomer.Id) { //Reply to already sent PM (by current customer) should not be sent to yourself toCustomer = replyToPM.FromCustomerId == _workContext.CurrentCustomer.Id ? replyToPM.ToCustomer : replyToPM.FromCustomer; } else { return(RedirectToRoute("PrivateMessages")); } } else { //first PM toCustomer = _customerService.GetCustomerById(model.ToCustomerId); } if (toCustomer == null || toCustomer.IsGuest()) { return(RedirectToRoute("PrivateMessages")); } if (ModelState.IsValid) { try { var subject = model.Subject; if (_forumSettings.PMSubjectMaxLength > 0 && subject.Length > _forumSettings.PMSubjectMaxLength) { subject = subject.Substring(0, _forumSettings.PMSubjectMaxLength); } var text = model.Message; if (_forumSettings.PMTextMaxLength > 0 && text.Length > _forumSettings.PMTextMaxLength) { text = text.Substring(0, _forumSettings.PMTextMaxLength); } var nowUtc = DateTime.UtcNow; var privateMessage = new PrivateMessage { StoreId = _storeContext.CurrentStore.Id, ToCustomerId = toCustomer.Id, FromCustomerId = _workContext.CurrentCustomer.Id, Subject = subject, Text = text, IsDeletedByAuthor = false, IsDeletedByRecipient = false, IsRead = false, CreatedOnUtc = nowUtc }; _forumService.InsertPrivateMessage(privateMessage); //activity log _customerActivityService.InsertActivity("PublicStore.SendPM", string.Format(_localizationService.GetResource("ActivityLog.PublicStore.SendPM"), toCustomer.Email), toCustomer); return(RedirectToRoute("PrivateMessages", new { tab = "sent" })); } catch (Exception ex) { ModelState.AddModelError("", ex.Message); } } model = _privateMessagesModelFactory.PrepareSendPrivateMessageModel(toCustomer, replyToPM); return(View(model)); }
internal PrivateMessageEventArgs(IrcClient client, IrcMessage ircMessage, ServerInfo serverInfo) { IrcMessage = ircMessage; PrivateMessage = new PrivateMessage(client, IrcMessage, serverInfo); }
public PrivateMessage SanitizeMessage(PrivateMessage privateMessage) { privateMessage.Message = StringUtils.GetSafeHtml(privateMessage.Message); return privateMessage; }
private void attach_PrivateMessages(PrivateMessage entity) { this.SendPropertyChanging(); entity.User = this; }
static void Main(string[] args) { Reddit reddit = null; var authenticated = false; while (!authenticated) { Console.Write("OAuth? (y/n) [n]: "); var oaChoice = Console.ReadLine(); if (!string.IsNullOrEmpty(oaChoice) && oaChoice.ToLower()[0] == 'y') { Console.Write("OAuth token: "); var token = Console.ReadLine(); reddit = new Reddit(token); reddit.InitOrUpdateUser(); authenticated = reddit.User != null; if (!authenticated) { Console.WriteLine("Invalid token"); } } else { Console.Write("Username: "******"Password: "******"Logging in..."); reddit = new Reddit(username, password); authenticated = reddit.User != null; } catch (AuthenticationException) { Console.WriteLine("Incorrect login."); authenticated = false; } } } /*Console.Write("Create post? (y/n) [n]: "); * var choice = Console.ReadLine(); * if (!string.IsNullOrEmpty(choice) && choice.ToLower()[0] == 'y') * { * Console.Write("Type a subreddit name: "); * var subname = Console.ReadLine(); * var sub = reddit.GetSubreddit(subname); * Console.WriteLine("Making test post"); * var post = sub.SubmitTextPost("RedditSharp test", "This is a test post sent from RedditSharp"); * Console.WriteLine("Submitted: {0}", post.Url); * } * else * { * Console.Write("Type a subreddit name: "); * var subname = Console.ReadLine(); * var sub = reddit.GetSubreddit(subname); * foreach (var post in sub.GetTop(FromTime.Week).Take(10)) * Console.WriteLine("\"{0}\" by {1}", post.Title, post.Author); * }*/ Comment comment = (Comment)reddit.GetThingByFullname("t1_ciif2g7"); Post post = (Post)reddit.GetThingByFullname("t3_298g7j"); PrivateMessage pm = (PrivateMessage)reddit.GetThingByFullname("t4_20oi3a"); // Use your own PM here, as you don't have permission to view this one Console.WriteLine(comment.Body); Console.WriteLine(post.Title); Console.WriteLine(pm.Body); Console.WriteLine(post.Comment("test").FullName); Console.ReadKey(true); }
public ActionResult Send(SendPrivateMessageModel model) { if (!AllowPrivateMessages()) { return(HttpNotFound()); } if (_workContext.CurrentCustomer.IsGuest()) { return(new HttpUnauthorizedResult()); } Customer toCustomer = null; var replyToPM = _forumService.GetPrivateMessageById(model.ReplyToMessageId); if (replyToPM != null) { if (replyToPM.ToCustomerId == _workContext.CurrentCustomer.Id || replyToPM.FromCustomerId == _workContext.CurrentCustomer.Id) { toCustomer = replyToPM.FromCustomer; } else { return(RedirectToRoute("PrivateMessages")); } } else { toCustomer = _customerService.GetCustomerById(model.ToCustomerId); } if (toCustomer == null || toCustomer.IsGuest()) { return(RedirectToRoute("PrivateMessages")); } model.ToCustomerId = toCustomer.Id; model.CustomerToName = toCustomer.FormatUserName(); model.AllowViewingToProfile = _customerSettings.AllowViewingProfiles && !toCustomer.IsGuest(); if (ModelState.IsValid) { try { string subject = model.Subject; if (_forumSettings.PMSubjectMaxLength > 0 && subject.Length > _forumSettings.PMSubjectMaxLength) { subject = subject.Substring(0, _forumSettings.PMSubjectMaxLength); } var text = model.Message; if (_forumSettings.PMTextMaxLength > 0 && text.Length > _forumSettings.PMTextMaxLength) { text = text.Substring(0, _forumSettings.PMTextMaxLength); } var nowUtc = DateTime.UtcNow; var privateMessage = new PrivateMessage { StoreId = _storeContext.CurrentStore.Id, ToCustomerId = toCustomer.Id, FromCustomerId = _workContext.CurrentCustomer.Id, Subject = subject, Text = text, IsDeletedByAuthor = false, IsDeletedByRecipient = false, IsRead = false, CreatedOnUtc = nowUtc }; _forumService.InsertPrivateMessage(privateMessage); //activity log _customerActivityService.InsertActivity("PublicStore.SendPM", _localizationService.GetResource("ActivityLog.PublicStore.SendPM"), toCustomer.Email); return(RedirectToRoute("PrivateMessages", new { tab = "sent" })); } catch (Exception ex) { ModelState.AddModelError("", ex.Message); } } return(View(model)); }
public void AddMessage(PrivateMessage newMessage) { MessageList.Add(newMessage); }
public void ActOnInMessage(IConMessage comMsg) { HubMessage message = (HubMessage)comMsg; if (message is MainChat) { MainChat main = (MainChat)message; MainMessage msg = new MainMessage(main.From, main.Content); Update(hub, new FmdcEventArgs(Actions.MainMessage, msg)); } else if (message is To) { To to = (To)message; PrivateMessage pm = new PrivateMessage(to.To, to.From, to.Content); Update(hub, new FmdcEventArgs(Actions.PrivateMessage, pm)); } else if (message is SR) { SR searchResult = (SR)message; SearchResultInfo srinfo = new SearchResultInfo(searchResult.Info, searchResult.From); Update(hub, new FmdcEventArgs(Actions.SearchResult, srinfo)); } else if (message is Search) { Search search = (Search)message; if (hub.Share == null) { return; } int maxReturns = 5; bool active = false; if (search.Address != null) { maxReturns = 10; active = true; } System.Collections.Generic.List <ContentInfo> ret = new System.Collections.Generic.List <ContentInfo>(maxReturns); // TODO : This lookup can be done nicer lock (hub.Share) { foreach (System.Collections.Generic.KeyValuePair <string, Containers.ContentInfo> var in hub.Share) { if (var.Value == null) { continue; } bool foundEnough = false; string ext = search.Info.Get(SearchInfo.EXTENTION); string sch = search.Info.Get(SearchInfo.SEARCH); if (ext != null && sch != null) { ContentInfo contentInfo = new ContentInfo(); if (search.Info.ContainsKey(SearchInfo.TYPE)) { switch (search.Info.Get(SearchInfo.TYPE)) { case "2": contentInfo.Set(ContentInfo.TTH, search.Info.Get(SearchInfo.SEARCH)); if (hub.Share.ContainsContent(ref contentInfo)) { ret.Add(contentInfo); } // We are looking through whole share here. // If no TTH matching. Ignore. foundEnough = true; break; case "1": default: if (var.Value.ContainsKey(ContentInfo.VIRTUAL) && (System.IO.Path.GetDirectoryName(var.Value.Get(ContentInfo.VIRTUAL)).IndexOf(sch, System.StringComparison.OrdinalIgnoreCase) != -1)) { ret.Add(var.Value); } break; } } if (!foundEnough) { string infoExt = System.IO.Path.GetExtension(var.Value.Get(ContentInfo.VIRTUAL)).TrimStart('.'); if ( var.Value.ContainsKey(ContentInfo.VIRTUAL) && (var.Value.Get(ContentInfo.VIRTUAL).IndexOf(sch, System.StringComparison.OrdinalIgnoreCase) != -1) && (ext.Length == 0 || ext.Contains(infoExt)) ) { ret.Add(var.Value); } } } if (foundEnough || ret.Count >= maxReturns) { break; } } } // Test against size restrictions for (int i = 0; i < ret.Count; i++) { bool send = true; long size = -1; try { size = int.Parse(search.Info.Get(SearchInfo.SIZE)); } catch { } if (search.Info.ContainsKey(SearchInfo.SIZETYPE) && size != -1) { switch (search.Info.Get(SearchInfo.SIZETYPE)) { case "1": // Min Size send = (size <= ret[i].Size); break; case "2": // Max Size send = (size >= ret[i].Size); break; case "3": // Equal Size send = (size == ret[i].Size); break; } } // Should this be sent? if (send) { SR sr = new SR(hub, ret[i], (search.Info.ContainsKey(SearchInfo.EXTENTION) ? search.Info.Get(SearchInfo.EXTENTION).Equals("$0") : false), search.From); if (active) { // Send with UDP UdpConnection.Send(sr, search.Address); } else { // Send through hub hub.Send(sr); } } } } else if (message is Lock) { hub.Send(new Supports(hub)); hub.Send(new Key(hub, ((Lock)message).Key)); hub.Send(new ValidateNick(hub)); } else if (message is HubNmdc.HubName) { HubNmdc.HubName hubname = (HubNmdc.HubName)message; Containers.HubName name = null; if (hubname.Topic != null) { name = new Containers.HubName(hubname.Name, hubname.Topic); } else { name = new Containers.HubName(hubname.Content); } Update(hub, new FmdcEventArgs(Actions.Name, name)); } else if (message is NickList) { NickList nicks = (NickList)message; foreach (string userid in nicks.List) { UserInfo userInfo = new UserInfo(); userInfo.DisplayName = userid; userInfo.Set(UserInfo.STOREID, hub.HubSetting.Address + hub.HubSetting.Port.ToString() + userid); if (hub.GetUserById(userid) == null) { Update(hub, new FmdcEventArgs(Actions.UserOnline, userInfo)); } } } else if (message is OpList) { OpList ops = (OpList)message; foreach (string userid in ops.List) { UserInfo userInfo = new UserInfo(); userInfo.DisplayName = userid; userInfo.Set(UserInfo.STOREID, hub.HubSetting.Address + hub.HubSetting.Port.ToString() + userid); userInfo.IsOperator = true; User usr = null; if ((usr = hub.GetUserById(userid)) == null) { Update(hub, new FmdcEventArgs(Actions.UserOnline, userInfo)); } else { usr.UserInfo = userInfo; Update(hub, new FmdcEventArgs(Actions.UserInfoChange, usr.UserInfo)); } } } else if (message is Quit) { Quit quit = (Quit)message; User usr = null; if ((usr = hub.GetUserById(quit.From)) != null) { Update(hub, new FmdcEventArgs(Actions.UserOffline, usr.UserInfo)); } } else if (message is LogedIn) { hub.RegMode = 2; } else if (message is ValidateDenide) { Update(hub, new FmdcEventArgs(Actions.StatusChange, new HubStatus(HubStatus.Codes.Disconnected))); } else if (message is GetPass) { hub.RegMode = 1; if (hub.HubSetting.Password.Length == 0) { Update(hub, new FmdcEventArgs(Actions.Password, null)); } else { hub.Send(new MyPass(hub)); } } else if (message is MyINFO) { MyINFO myinfo = (MyINFO)message; User usr = null; if ((usr = hub.GetUserById(message.From)) == null) { Update(hub, new FmdcEventArgs(Actions.UserOnline, myinfo.UserInfo)); } else { bool op = usr.IsOperator; usr.UserInfo = myinfo.UserInfo; usr.UserInfo.IsOperator = op; Update(hub, new FmdcEventArgs(Actions.UserInfoChange, usr.UserInfo)); } } else if (message is Hello) { if (hub.HubSetting.DisplayName.Equals(message.From)) { hub.Send(new Version(hub)); hub.Send(new GetNickList(hub)); if (hub.RegMode < 0) { hub.RegMode = 0; } UpdateMyInfo(); } } else if (message is ConnectToMe) { ConnectToMe conToMe = (ConnectToMe)message; Transfer trans = new Transfer(conToMe.Address, conToMe.Port); trans.Share = this.hub.Share; trans.Me = hub.Me; trans.Source = new Source(hub.RemoteAddress.ToString(), null); // Protocol has to be set last. trans.Protocol = new TransferNmdcProtocol(trans); #if !COMPACT_FRAMEWORK if (conToMe.TLS && hub.Me.ContainsKey(UserInfo.SECURE)) { trans.SecureProtocol = SecureProtocols.TLS; } #endif Update(hub, new FmdcEventArgs(Actions.TransferStarted, trans)); } else if (message is RevConnectToMe) { RevConnectToMe revConToMe = (RevConnectToMe)message; User usr = null; usr = hub.GetUserById(revConToMe.From); if (hub.Me.Mode == FlowLib.Enums.ConnectionTypes.Passive) { if (usr != null) { // If user are not set as passive. Set it as it and respond with a revconnect. if (usr.UserInfo.Mode != FlowLib.Enums.ConnectionTypes.Passive) { usr.UserInfo.Mode = FlowLib.Enums.ConnectionTypes.Passive; hub.Send(new RevConnectToMe(revConToMe.From, hub)); } } } else { if (usr != null) { Update(hub, new FmdcEventArgs(Actions.TransferRequest, new TransferRequest(usr.ID, hub, usr.UserInfo))); #if !COMPACT_FRAMEWORK // Security, Windows Mobile doesnt support SSLStream so we disable this feature for it. if ( usr.UserInfo.ContainsKey(UserInfo.SECURE) && hub.Me.ContainsKey(UserInfo.SECURE) && !string.IsNullOrEmpty(hub.Me.Get(UserInfo.SECURE)) ) { hub.Send(new ConnectToMe(usr.ID, hub.Share.Port, hub, SecureProtocols.TLS)); } else #endif hub.Send(new ConnectToMe(usr.ID, hub.Share.Port, hub)); } } } else if (message is ForceMove) { ForceMove forceMove = (ForceMove)message; hub.Disconnect(); Update(hub, new FmdcEventArgs(Actions.Redirect, new RedirectInfo(forceMove.Address))); } }
public PrivateMessageEventArgs(IrcMessage ircMessage, ServerInfo serverInfo) { IrcMessage = ircMessage; PrivateMessage = new PrivateMessage(IrcMessage, serverInfo); }
private static void OnClientSentPrivateMessage(object sender, PrivateMessage message) { }
public IHttpActionResult Post() { var httpRequest = HttpContext.Current.Request; var file = httpRequest.Files[0]; var fileExtension = file.FileName.Split('.').Last(); var uniqueName = this.CurrentUserId + Guid.NewGuid() + "." + fileExtension; byte[] buffer = null; using (var fs = file.InputStream) { buffer = new byte[fs.Length]; fs.Read(buffer, 0, (int)fs.Length); } var task = Task.Run(() => DropBoxManager.Upload(uniqueName, buffer)); task.Wait(); var link = "http://viber.azurewebsites.net/api/File?fileName=" + uniqueName; var receiverId = this.CurrentUser.CurrentChatId; var receiver = this.Data.Users.All() .FirstOrDefault(u => u.Id == receiverId); var message = new PrivateMessage() { Text = link, ReceiverId = receiverId, SenderId = this.CurrentUserId, IsFileLink = true }; var currentUsers = ConnectionManager.Users.Keys; if (currentUsers.Contains(receiver.UserName) && receiver.CurrentChatId == this.CurrentUser.Id) { message.Status = MessageStatus.Seen; } else if (currentUsers.Contains(receiver.UserName)) { message.Status = MessageStatus.Sent; } else { message.Status = MessageStatus.NotDelivered; } this.Data.Messages.Add(message); this.Data.SaveChanges(); var messageView = new { message.Id, message.Text, Sender = this.CurrentUserUserName, Receiver = receiver.UserName, Status = message.Status.ToString(), SenderId = this.CurrentUserId, ReceiverId = receiver.Id, MessageId = message.Id, IsFileLink = true }; this.HubContex.Clients.User(receiver.UserName).pushMessageToClient(messageView); this.HubContex.Clients.User(this.CurrentUserUserName).pushSelfMessage(messageView); return(this.Ok()); }