using Model.Notice;
using ZmajService.User;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TF.Common.Tools;
using TF.Config;
using TF.JiguangPush;
using TF.JiguangPush.Model;
using TF.Logger;
namespace ZmajService.Service.Message
{
public class UserActiveMessage
{
///
/// 用户登录之后发送消息
///
///
public async void Send(string clientId)
{
if (string.IsNullOrEmpty(clientId))
{
return;
}
DeviceInfo info = UserManager.Get(clientId);
if (info == null || string.IsNullOrEmpty(info.UserId))
{
return;
}
MessageDataManager data = new MessageDataManager();
List models = await data.GetMessageByUid(info.UserId);
if (models == null || models.Count <= 0)
{
return;
}
//等待3s,页面加载完成
await Task.Delay(3000);
foreach (var item in models)
{
try
{
bool sendState = await PublishSupport.Publish(item);
if (sendState)
{
UpdatePublishState(item);
}
await Task.Delay(30);
}
catch (Exception ex)
{
Log.Error($"Send message to login user failed, userid is {item.UserId}. {ex.Message}", ex);
return;
}
}
}
///
/// 发布消息之后马上发送
///
///
public async void Send(List models)
{
if (models == null || models.Count == 0)
{
return;
}
MessageDataManager data = new MessageDataManager();
List infos = UserManager.GetAll();
foreach (var item in models)
{
try
{
if (item.StartTime > TimeUtil.Timestamp())
{
continue;
}
bool sendState = false;
if (infos.Count > 0)
{
List temp = infos.Where(p => p.UserId == item.UserId).ToList();
if (temp != null && temp.Count > 0)
{
sendState = await PublishSupport.Publish(item);
}
}
if (item.IsNoticeApp && !item.AppState)
{
JPush jPush = new JPush(ConfigManager.Now.AppSettings.AppPushKey, ConfigManager.Now.AppSettings.AppPushMasterSecret);
JPushResult result = jPush.PushNotification("系统通知", item.Content, new ArrayList() {
item.UserId
},
new Dictionary
{
{ "payload", item}
});
if (result.StatusCode == "200" && result.Error.Code == 0)
{
sendState = true;
}
await data.SetAppPublishState(item);
}
if (sendState)
{
UpdatePublishState(item);
}
await Task.Delay(30);
}
catch (Exception ex)
{
Log.Error($"Send new message to user failed, userid is {item.UserId}. {ex.Message}", ex);
return;
}
}
}
private async void UpdatePublishState(MessageModel model)
{
int now = TimeUtil.Timestamp();
if (model.BlankTime == 0)
{
model.NextTime = model.StopTime + 1;
}
else
{
model.NextTime = now + model.BlankTime;
if (model.NextTime > model.StopTime & model.StopTime != 0)
{
model.NextTime = model.StopTime;
}
}
model.LastTime = now;
MessageDataManager data = new MessageDataManager();
if (!await data.SetPublishState(model))
{
//更新状态失败
Log.Warn($"Set message publish state failed. Message id: {model.Id}");
}
}
}
}