private async Task <IResult> SetGroup(long chatId, string group, ConsumerType consumerType) { if (!int.TryParse(group, out var intGroup)) { return(new FailedResult("Укажите корректный номер группы.")); } var isExists = _narfuApi.Students.IsCorrectGroup(intGroup); if (!isExists) { return(new FailedResult($"Группа с номером {intGroup} не найдена.")); } var groupName = _narfuApi.Students.GetGroupByRealId(intGroup).Name; var job = await _context.CronJobs.FirstOrDefaultAsync(x => x.ChatId == chatId); if (job is null) { var time = new CronTime("0", "6"); await _context.CronJobs.AddAsync(new CronJob(chatId.ToString(), chatId, intGroup, string.Empty, time, consumerType, CronType.Weather)); } else { job.CronType |= CronType.Schedule; job.SetNarfuGroup(intGroup); } await _context.SaveChangesAsync(); return(new SuccessfulResult($"Группа успешно установлена на {intGroup} ({groupName})")); }
public Remind(long chatId, string text, DateTimeOffset date, ConsumerType type) { SetChatId(chatId); SetText(text); SetDateTime(date); SetConsumerType(type); }
private async Task <IResult> RemoveMailing(long chatId, string whatToRemove, ConsumerType consumerType) { if (whatToRemove.Contains("расписани", StringComparison.InvariantCultureIgnoreCase)) { var job = await _context.CronJobs.FirstOrDefaultAsync(x => x.ChatId == chatId && x.ConsumerType == consumerType); job.SetNarfuGroup(0); job.CronType &= ~CronType.Schedule; await _context.SaveChangesAsync(); return(new SuccessfulResult("Рассылка расписания удалена. Установите группу для возобновления рассылки.")); } if (whatToRemove.Contains("погод", StringComparison.InvariantCultureIgnoreCase)) { var job = await _context.CronJobs.FirstOrDefaultAsync(x => x.ChatId == chatId && x.ConsumerType == consumerType); job.SetWeatherCity(string.Empty); job.CronType &= ~CronType.Weather; await _context.SaveChangesAsync(); return(new SuccessfulResult("Рассылка погоды удалена. Установите город для возобновления рассылки.")); } return(new FailedResult($"Параметр '{whatToRemove}' отсутствует. Пожалуйста, прочитайте справку.")); }
private IConsumerHolder Start(string topicPattern, string groupId, IMessageListener listener, MessageListenerConfig listenerConfig, ConsumerType consumerType) { ISubscribeHandle subscribeHandle = engine.Start(new Subscriber(topicPattern, groupId, listener, listenerConfig, consumerType)); return new DefaultConsumerHolder(subscribeHandle); }
/// <summary> /// <para>Events:</para> /// <para>@emits transportclose</para> /// <para>@emits producerclose</para> /// <para>@emits producerpause</para> /// <para>@emits producerresume</para> /// <para>@emits score - (score: ConsumerScore)</para> /// <para>@emits layerschange - (layers: ConsumerLayers | undefined)</para> /// <para>@emits trace - (trace: ConsumerTraceEventData)</para> /// <para>@emits @close</para> /// <para>@emits @producerclose</para> /// <para>Observer events:</para> /// <para>@emits close</para> /// <para>@emits pause</para> /// <para>@emits resume</para> /// <para>@emits score - (score: ConsumerScore)</para> /// <para>@emits layerschange - (layers: ConsumerLayers | undefined)</para> /// <para>@emits rtp - (packet: Buffer)</para> /// <para>@emits trace - (trace: ConsumerTraceEventData)</para> /// </summary> /// <param name="loggerFactory"></param> /// <param name="consumerInternalData"></param> /// <param name="kind"></param> /// <param name="rtpParameters"></param> /// <param name="type"></param> /// <param name="channel"></param> /// <param name="appData"></param> /// <param name="paused"></param> /// <param name="producerPaused"></param> /// <param name="score"></param> /// <param name="preferredLayers"></param> public Consumer(ILoggerFactory loggerFactory, ConsumerInternalData consumerInternalData, MediaKind kind, RtpParameters rtpParameters, ConsumerType type, Channel channel, PayloadChannel payloadChannel, Dictionary <string, object>?appData, bool paused, bool producerPaused, ConsumerScore?score, ConsumerLayers?preferredLayers ) { _logger = loggerFactory.CreateLogger <Consumer>(); // Internal _internal = consumerInternalData; // Data Kind = kind; RtpParameters = rtpParameters; Type = type; _channel = channel; _payloadChannel = payloadChannel; AppData = appData; _paused = paused; ProducerPaused = producerPaused; Score = score; PreferredLayers = preferredLayers; HandleWorkerNotifications(); }
private async Task <IResult> SetTime(long chatId, string time, ConsumerType consumerType) { var splittedTime = time.Split(':'); if (splittedTime.Length != 2) { return(new FailedResult("Укажите время в формате часы:минуты (например, 11:30)")); } try { var cronTime = new CronTime(splittedTime[1], splittedTime[0]); var job = await _context.CronJobs.FirstOrDefaultAsync(x => x.ChatId == chatId); if (job is null) { await _context.CronJobs.AddAsync(new CronJob(chatId.ToString(), chatId, 0, string.Empty, cronTime, consumerType, CronType.Schedule)); } else { job.SetCronTime(cronTime); } await _context.SaveChangesAsync(); return(new SuccessfulResult($"Время успешно установлено на {time}")); } catch (Exception e) { return(new FailedResult(e.Message)); } }
private async Task <IResult> SetCity(long chatId, string city, ConsumerType consumerType) { var isCityExist = await _openWeatherMapApi.IsCityExists(city); if (!isCityExist) { return(new FailedResult("Указанный город не найден")); } var job = await _context.CronJobs.FirstOrDefaultAsync(x => x.ChatId == chatId); if (job is null) { var time = new CronTime("0", "6"); await _context.CronJobs.AddAsync(new CronJob(chatId.ToString(), chatId, 0, city, time, consumerType, CronType.Weather)); } else { job.CronType |= CronType.Weather; job.SetWeatherCity(city); } await _context.SaveChangesAsync(); return(new SuccessfulResult($"Город успешно установлен на {city}")); }
public void RegisterListener(ConsumerType consumerType, IConsumer consumer) { if (!_listenerList.ContainsKey(consumerType)) { _listenerList.Add(consumerType, consumer); ItemAdded += consumer.OnItemAdded; } }
public Subscriber(String topicPattern, String groupId, IMessageListener consumer, MessageListenerConfig messageListenerConfig, ConsumerType consumerType) { TopicPattern = topicPattern; GroupId = groupId; Consumer = consumer; ConsumerType = consumerType; MessageListenerConfig = messageListenerConfig; }
public ConsumerContext(Topic topic, String groupId, IMessageListener consumer, Type messageClazz, ConsumerType consumerType, MessageListenerConfig messageListenerConfig) { Topic = topic; GroupId = groupId; Consumer = consumer; MessageClazz = messageClazz; ConsumerType = consumerType; SessionId = Guid.NewGuid().ToString(); MessageListenerConfig = messageListenerConfig; }
public DataItem GetNextItem(ConsumerType consumerType) { foreach (DataItem currentItem in _dataQueue) { if (currentItem.ConsumerType == consumerType) { _dataQueue.Remove(currentItem); return(currentItem); } } return(null); }
public LogConsumer(string name) { if (name == "stdout") _mode = ConsumerType.Stdout; else if (name == "net") _mode = ConsumerType.Network; else { _mode = ConsumerType.LocalFile; var fs = new FileStream(name + ".PID." + Process.GetCurrentProcess().Id + ".log", FileMode.Create); _localWriter = new StreamWriter(fs); } }
private static void RunProducer(object obj) { int delay; StreamReader input = File.OpenText(_inputFileInfo.FullName); try { delay = (int)obj; } catch (InvalidCastException) { delay = 5000; } while (_runThread) { string currentLine = input.ReadLine(); if (currentLine != null) { List <string> lineSplit = new List <string>(currentLine.Split(',')); if (lineSplit.Count != 2) { continue; } string lineType = lineSplit[0].ToLower(); ConsumerType currentType = ConsumerType.CONSOLE; if (lineType.Equals("console")) { currentType = ConsumerType.CONSOLE; } else if (lineType.Equals("file")) { currentType = ConsumerType.FILE; } else { continue; } DataItem currentItem = new DataItem(currentType, lineSplit[1]); _dataQueue.AddItem(currentItem); } Thread.Sleep(delay); } Thread.Sleep(0); }
public void CheckDataQueueDequeueTypeCorrect() { IDataQueue dataQueue = new DataQueue(); var consumer = new Mock <IConsumer>(); ConsumerType inType = ConsumerType.CONSOLE; ConsumerType outType = ConsumerType.FILE; consumer.Setup(c => c.OnItemAdded()).Callback(() => outType = dataQueue.GetNextItem(inType).ConsumerType); dataQueue.RegisterListener(inType, consumer.Object); dataQueue.AddItem(new DataItem(inType, "DUMMY")); Assert.That(inType.Equals(outType), $"Expected type to be {inType} but was {outType}"); }
public LogConsumer(string name) { if (name == "stdout") { _mode = ConsumerType.Stdout; } else if (name == "net") { _mode = ConsumerType.Network; } else { _mode = ConsumerType.LocalFile; var fs = new FileStream(name + ".PID." + Process.GetCurrentProcess().Id + ".log", FileMode.Create); _localWriter = new StreamWriter(fs); } }
public IConsumer GetConsumer(ConsumerType type, MailSettings settings = null) { switch (type) { case ConsumerType.OrderConsumer: { var notifier = new MailNotifier(settings); return((IConsumer) new OrderMessageConsumer(_channel, notifier)); } case ConsumerType.NotificationConsumer: return((IConsumer) new NotificationMessageConsumer(_channel, new SmsNotifier())); default: throw new NotSupportedException(); } }
private async Task <BotUser> GetBotUser(long userId, ConsumerType type) { var user = await _context.BotUsers.FindAsync(userId, type); if (user is not null) { return(user); } var entity = new BotUser(userId) { ConsumerType = type }; user = (await _context.BotUsers.AddAsync(entity)).Entity; await _context.SaveChangesAsync(); return(user); }
/// <summary> /// Adds a consumer to the specified video channel with parameters /// </summary> /// <param name="consumer"></param> /// <param name="consumerIndex"></param> /// <param name="parameters"></param> /// <returns></returns> public virtual bool Add(ConsumerType consumer, uint?consumerIndex = null, string parameters = null) { var stringBuilder = new StringBuilder(); stringBuilder.Append($"{AMCPCommand.ADD.ToAmcpValue()} {ID}"); if (consumerIndex != null) { stringBuilder.Append($"-{consumerIndex}"); } stringBuilder.Append($" {consumer.ToAmcpValue()}"); if (!string.IsNullOrEmpty(parameters)) { stringBuilder.Append($" {parameters}"); } return(_amcpTcpParser.SendCommand(stringBuilder.ToString())); }
private async Task <IResult> GenerateCronInfo(long chatId, ConsumerType consumerType) { var job = await _context.CronJobs.FirstOrDefaultAsync(x => x.ChatId == chatId && x.ConsumerType == consumerType); if (job is null) { return(new FailedResult("Рассылка для данной беседы не настроена")); } var strBuilder = new StringBuilder($"Информация по беседе #{chatId}:"); strBuilder.AppendLine(); if (job.NarfuGroup != 0) { strBuilder.AppendFormat("Группа САФУ: {0}", job.NarfuGroup); } else { strBuilder.Append("Группа для рассылки расписания не установлена"); } strBuilder.AppendLine(); if (!string.IsNullOrWhiteSpace(job.WeatherCity)) { strBuilder.AppendFormat("Город: {0}", job.WeatherCity); } else { strBuilder.Append("Город для рассылки погоды не установлен"); } strBuilder.AppendLine(); strBuilder.AppendFormat("Время рассылки: {0}:{1}", job.Time.Hour, job.Time.Minute); return(new SuccessfulResult(strBuilder.ToString())); }
public async Task Execute(long chatId, ConsumerType consumerType, CronType cronType, string city, int group, string text) { var sender = _senders.FirstOrDefault(x => x.ConsumerType == consumerType); await Send(responseText => sender.Send(chatId, responseText)); async Task Send(Func <string, Task> func) { if (cronType.HasFlag(CronType.Schedule) && group != 0) { await SendSchedule(chatId, group, func); } if (cronType.HasFlag(CronType.Weather) && !string.IsNullOrWhiteSpace(city)) { await SendWeather(chatId, city, func); } if (cronType.HasFlag(CronType.Text) && !string.IsNullOrWhiteSpace(text)) { await SendText(text, func); } } }
public Alcholic(string ConsName, ConsumerType consType) : base(ConsName, consType) { }
public async Task SendToId(long chatId, string text, ICollection <string> attachments, ConsumerType type) { var sender = _senders.FirstOrDefault(x => x.ConsumerType == type); await sender.Send(chatId, text, attachments : attachments); }
//Constructor public Consumer(string ConsName, ConsumerType consType) { Name = ConsName; }
public ConsumerTypeViewModel CreateFromExisting(ConsumerType consumerType) { return(new ConsumerTypeViewModel(consumerType)); }
private void SetConsumerType(ConsumerType type) { ConsumerType = type; }
public Subscriber(String topicPattern, String groupId, IMessageListener consumer, ConsumerType consumerType) : this(topicPattern, groupId, consumer, DEFAULT_MESSAGE_LISTENER_CONFIG, consumerType) { }
public Kid(string ConsName, ConsumerType consType) : base(ConsName, consType) { }
private async Task AddRemind(long chatId, ConsumerType consumerType, string remindText, DateTimeOffset dateTime) { await _db.Reminds.AddAsync(new Remind(chatId, remindText, dateTime, consumerType)); await _db.SaveChangesAsync(); }
public CronJob(string name, long chatId, int narfuGroup, string weatherCity, CronTime time, ConsumerType consumerType, CronType cronType, string text = "") { SetName(name); SetChatId(chatId); SetNarfuGroup(narfuGroup); SetWeatherCity(weatherCity); SetConsumerType(consumerType); SetCronTime(time); SetCronType(cronType); SetText(text); }
public DataItem GetNextItem(ConsumerType consumerType) { return(new DataItem(consumerType, "DUMMY")); }
public void RegisterListener(ConsumerType consumerType, IConsumer consumer) { Console.Out.WriteLine($"Attempted to register {consumer.ToString()} as {consumerType}"); }
public ConsumerTypeViewModel(ConsumerType model) { m_Model = model; }
public static Consumer CreateConsumer(string p1, Distributor d1, ConsumerGroup cg1, ConsumerType ct1) { return(new Consumer { Name = p1, Distributor = d1, ConsumerGroup = cg1, ConsumerType = ct1 }); }
/// <summary> /// Adds a consumer to the specified video channel. /// </summary> /// <param name="consumerIndex"></param> /// <param name="consumer">overrides the index that the consumer itself decides and can later be </param> /// <returns></returns> public virtual bool Add(ConsumerType consumer, uint consumerIndex) { return(_amcpTcpParser.SendCommand($"{AMCPCommand.ADD.ToAmcpValue()} {ID} {consumer.ToAmcpValue()} {consumerIndex}")); }
/// <inheritdoc/> public override int GetHashCode() => ConsumerType.GetHashCode();
public IConsumingStrategy FindStrategy(ConsumerType consumerType) { return CollectionUtil.TryGet(Strategies, consumerType); }