<commit_before>﻿using DW.ELA.Controller;
using DW.ELA.Interfaces;
using DW.ELA.Interfaces.Settings;
using DW.ELA.Plugin.EDDN.Model;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using Utility;

namespace DW.ELA.Plugin.EDDN
{
    public class EddnPlugin : AbstractPlugin<EddnEvent,EddnSettings>
    {
        private static readonly IRestClient RestClient = new ThrottlingRestClient("https://eddn.edcd.io:4430/upload/");
        private static readonly ILogger logger = LogManager.GetCurrentClassLogger();
        private readonly ISettingsProvider settingsProvider;
        private readonly IPlayerStateHistoryRecorder playerStateRecorder;

        private readonly IEddnApiFacade apiFacade = new EddnApiFacade(RestClient);
        private readonly EddnEventConverter eventConverter;
        private readonly EventSchemaValidator schemaManager = new EventSchemaValidator();

        protected override IEventConverter<EddnEvent> EventConverter => eventConverter;

        public EddnPlugin(ISettingsProvider settingsProvider, IPlayerStateHistoryRecorder playerStateRecorder) : base(settingsProvider)
        {
            this.settingsProvider = settingsProvider ?? throw new ArgumentNullException(nameof(settingsProvider));
            this.playerStateRecorder = playerStateRecorder ?? throw new ArgumentNullException(nameof(playerStateRecorder));
            eventConverter = new EddnEventConverter() { UploaderID = settingsProvider.Settings.CommanderName };
            settingsProvider.SettingsChanged += (o, e) => ReloadSettings();
            ReloadSettings();
        }

        public override string PluginName => "EDDN";
        public override string PluginId => "EDDN";
        // EDDN accepts events one-by-one, so no need to batch
        public override TimeSpan FlushInterval => TimeSpan.FromSeconds(1); 

        public override AbstractSettingsControl GetPluginSettingsControl(GlobalSettings settings) => null;
        public override async void FlushEvents(ICollection<EddnEvent> events)
        {
            foreach (var @event in events)
                schemaManager.ValidateSchema(@event);
            await apiFacade.PostEventsAsync(events.ToArray());
        }

        public override void ReloadSettings() => eventConverter.UploaderID = settingsProvider.Settings.CommanderName;
    }
}<commit_msg>Avoid sending same EDDN messages over and over again (board flipping) #32<commit_after>﻿using DW.ELA.Controller;
using DW.ELA.Interfaces;
using DW.ELA.Interfaces.Settings;
using DW.ELA.Plugin.EDDN.Model;
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Utility;

namespace DW.ELA.Plugin.EDDN
{
    public class EddnPlugin : AbstractPlugin<EddnEvent, EddnSettings>
    {
        private static readonly IRestClient RestClient = new ThrottlingRestClient("https://eddn.edcd.io:4430/upload/");
        private static readonly ILogger logger = LogManager.GetCurrentClassLogger();
        private readonly ISettingsProvider settingsProvider;
        private readonly IPlayerStateHistoryRecorder playerStateRecorder;

        private readonly IEddnApiFacade apiFacade = new EddnApiFacade(RestClient);
        private readonly EddnEventConverter eventConverter;
        private readonly EventSchemaValidator schemaManager = new EventSchemaValidator();

        protected override IEventConverter<EddnEvent> EventConverter => eventConverter;

        public EddnPlugin(ISettingsProvider settingsProvider, IPlayerStateHistoryRecorder playerStateRecorder) : base(settingsProvider)
        {
            this.settingsProvider = settingsProvider ?? throw new ArgumentNullException(nameof(settingsProvider));
            this.playerStateRecorder = playerStateRecorder ?? throw new ArgumentNullException(nameof(playerStateRecorder));
            eventConverter = new EddnEventConverter() { UploaderID = settingsProvider.Settings.CommanderName };
            settingsProvider.SettingsChanged += (o, e) => ReloadSettings();
            ReloadSettings();
        }

        public override string PluginName => "EDDN";
        public override string PluginId => "EDDN";
        // EDDN accepts events one-by-one, so no need to batch
        public override TimeSpan FlushInterval => TimeSpan.FromSeconds(1);

        public override AbstractSettingsControl GetPluginSettingsControl(GlobalSettings settings) => null;
        public override async void FlushEvents(ICollection<EddnEvent> events)
        {
            foreach (var @event in events)
                schemaManager.ValidateSchema(@event);
            await apiFacade.PostEventsAsync(events.Where(IsUnique).ToArray());
        }

        private readonly ConcurrentQueue<JObject> lastPushedEvents = new ConcurrentQueue<JObject>(); // stores

        /// <summary>
        /// Check event against list of last few sent events, excluding timestamp from comparison
        /// </summary>
        /// <param name="e"></param>
        /// <returns>true if event wasn't sent before</returns>
        private bool IsUnique(EddnEvent e)
        {
            try
            {
                JObject jObject;
                while (lastPushedEvents.Count > 10)
                    lastPushedEvents.TryDequeue(out jObject);

                jObject = JObject.FromObject(e);
                var messageObject = jObject.Property("message")?.Value as JObject;
                messageObject?.Property("timestamp")?.Remove();

                foreach (var recent in lastPushedEvents)
                    if (JToken.DeepEquals(jObject,recent))
                        return false;

                lastPushedEvents.Enqueue(jObject);
                return true;
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Error in deduplication");
                return true; // by default, we consider any message unique and so will send it
            }
        }


        public override void ReloadSettings() => eventConverter.UploaderID = settingsProvider.Settings.CommanderName;
    }
}
{'fraction_non_alphanumeric': 0.07878391631252044, 'fraction_numerical': 0.002288329519450801, 'mean_word_length': 3.0442828816920025, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 32, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '499203', 'n_tokens_mistral': 1533, 'n_tokens_neox': 1477, 'n_words': 383}