<commit_before>﻿/*
 * Copyright © 2018 EDDiscovery development team
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
 * file except in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 * 
 * EDDiscovery is not affiliated with Frontier Developments plc.
 */
using EliteDangerousCore.JournalEvents;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Linq;

namespace EliteDangerousCore.Inara
{
    public partial class InaraClass : BaseUtils.HttpCom
    {
        // use if you need an API/name pair to get info from Inara.  Not all queries need it
        public bool ValidCredentials { get { return !string.IsNullOrEmpty(commanderName) && !string.IsNullOrEmpty(apiKey); } }

        private string commanderName;
        private string commanderFrontierID;
        private string apiKey;

        private readonly string fromSoftwareVersion;
        private readonly string fromSoftware;
        static private Dictionary<long, List<JournalScan>> DictEDSMBodies = new Dictionary<long, List<JournalScan>>();

        private string InaraAPI = "inapi/v1/";      // Action end point

        private InaraClass()
        {
            fromSoftware = "EDDiscovery";
            var assemblyFullName = Assembly.GetEntryAssembly().FullName;
            fromSoftwareVersion = assemblyFullName.Split(',')[1].Split('=')[1];

            base.httpserveraddress = @"https://inara.cz/";

            apiKey = EDCommander.Current.InaraAPIKey;
            commanderName = string.IsNullOrEmpty(EDCommander.Current.InaraName) ? EDCommander.Current.Name : EDCommander.Current.InaraName;

            MimeType = "application/json";      // sets Content-type
        }

        public InaraClass(EDCommander cmdr, string cmdrfid) : this()
        {
            if (cmdr != null)
            {
                apiKey = cmdr.InaraAPIKey;
                commanderFrontierID = cmdrfid;
                commanderName = string.IsNullOrEmpty(cmdr.InaraName) ? cmdr.Name : cmdr.InaraName;
            }
        }

        #region Send and receive

        public string ToJSONString(List<JToken> events)
        {
            JToken finaljson = Request(events.ToArray());
            return finaljson.ToString(Newtonsoft.Json.Formatting.Indented);
        }

        public string Send(List<JToken> events)
        {
            return Send(events, out List<JObject> datalist);
        }

        public string Send(List<JToken> events, out List<JObject> datalist) // string returned is errors, null if none..
        {
            datalist = new List<JObject>();

            if (!ValidCredentials)
                return "No valid Inara Credentials" + Environment.NewLine;

            string request = ToJSONString(events);

            //File.WriteAllText(@"c:\code\json.txt", request); 
            System.Diagnostics.Debug.WriteLine("Send inara " + request);

            var response = RequestPost(request, InaraAPI, handleException: true);

            if (response.Error)
                return "No Response" + Environment.NewLine;

            string ret = "";

            try
            {
                JObject resp = JObject.Parse(response.Body);

                JObject header = (JObject)resp["header"];
                int headerstatus = header["eventStatus"].Int();     // this is the response to the input header - error if user credentials bad etc

                if (headerstatus >= 300 || headerstatus < 200)      // 2xx good
                {
                    ret += "Rejected Send: " + header["eventStatusText"].Str() + Environment.NewLine;
                }
                else
                {
                    JArray responses = (JArray)resp["events"];

                    for( int i = 0; i < responses.Count;  i++)      // for each event.. check response..
                    {
                        JObject ro = (JObject)responses[i];
                        int eventstate = ro["eventStatus"].Int();

                        datalist.Add(ro["eventData"] as JObject);       // may be null!  if no data is returned by Inara.. Only a few data requestes exists

                        if ( i >= events.Count )            // inara is giving more event responses than what we asked for!
                            ret += "Too many responses to events requested" + Environment.NewLine;
                        else if (eventstate >= 300 || eventstate < 200 )         // 2xx good
                            ret += "Error to request " + (events[i])["eventName"].Str() + " " + events[i].ToString() + " with " + ro["eventStatusText"].Str() + Environment.NewLine;
                    }
                }<commit_msg>Add/Del friends reports if friend is not known to inara so cannot be added<commit_after>﻿/*
 * Copyright © 2018 EDDiscovery development team
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
 * file except in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 * 
 * EDDiscovery is not affiliated with Frontier Developments plc.
 */
using EliteDangerousCore.JournalEvents;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Linq;

namespace EliteDangerousCore.Inara
{
    public partial class InaraClass : BaseUtils.HttpCom
    {
        // use if you need an API/name pair to get info from Inara.  Not all queries need it
        public bool ValidCredentials { get { return !string.IsNullOrEmpty(commanderName) && !string.IsNullOrEmpty(apiKey); } }

        private string commanderName;
        private string commanderFrontierID;
        private string apiKey;

        private readonly string fromSoftwareVersion;
        private readonly string fromSoftware;
        static private Dictionary<long, List<JournalScan>> DictEDSMBodies = new Dictionary<long, List<JournalScan>>();

        private string InaraAPI = "inapi/v1/";      // Action end point

        private InaraClass()
        {
            fromSoftware = "EDDiscovery";
            var assemblyFullName = Assembly.GetEntryAssembly().FullName;
            fromSoftwareVersion = assemblyFullName.Split(',')[1].Split('=')[1];

            base.httpserveraddress = @"https://inara.cz/";

            apiKey = EDCommander.Current.InaraAPIKey;
            commanderName = string.IsNullOrEmpty(EDCommander.Current.InaraName) ? EDCommander.Current.Name : EDCommander.Current.InaraName;

            MimeType = "application/json";      // sets Content-type
        }

        public InaraClass(EDCommander cmdr, string cmdrfid) : this()
        {
            if (cmdr != null)
            {
                apiKey = cmdr.InaraAPIKey;
                commanderFrontierID = cmdrfid;
                commanderName = string.IsNullOrEmpty(cmdr.InaraName) ? cmdr.Name : cmdr.InaraName;
            }
        }

        #region Send and receive

        public string ToJSONString(List<JToken> events)
        {
            JToken finaljson = Request(events.ToArray());
            return finaljson.ToString(Newtonsoft.Json.Formatting.Indented);
        }

        public string Send(List<JToken> events)
        {
            return Send(events, out List<JObject> datalist);
        }

        public string Send(List<JToken> events, out List<JObject> datalist) // string returned is errors, null if none..
        {
            datalist = new List<JObject>();

            if (!ValidCredentials)
                return "No valid Inara Credentials" + Environment.NewLine;

            string request = ToJSONString(events);

            //File.WriteAllText(@"c:\code\json.txt", request); 
            System.Diagnostics.Debug.WriteLine("Send inara " + request);

            var response = RequestPost(request, InaraAPI, handleException: true);

            if (response.Error)
                return "No Response" + Environment.NewLine;

            string ret = "";

            try
            {
                JObject resp = JObject.Parse(response.Body);

                JObject header = (JObject)resp["header"];
                int headerstatus = header["eventStatus"].Int();     // this is the response to the input header - error if user credentials bad etc

                if (headerstatus >= 300 || headerstatus < 200)      // 2xx good
                {
                    ret += "Rejected Send: " + header["eventStatusText"].Str() + Environment.NewLine;
                }
                else
                {
                    JArray responses = (JArray)resp["events"];

                    for( int i = 0; i < responses.Count;  i++)      // for each event.. check response..
                    {
                        JObject ro = (JObject)responses[i];
                        int eventstate = ro["eventStatus"].Int();

                        datalist.Add(ro["eventData"] as JObject);       // may be null!  if no data is returned by Inara.. Only a few data requestes exists

                        if (i >= events.Count)            // inara is giving more event responses than what we asked for!
                            ret += "Too many responses to events requested" + Environment.NewLine;
                        else if (eventstate == 204 && ro["eventStatusText"].Str("").Contains("in-game name"))       // add/del friends can 
                        {
                            string cmdr = events[i]["eventData"]["commanderName"].Str("Unknown");
                            ret += "Inara reports commander " + cmdr + " is not known to it" + Environment.NewLine;
                        }
                        else if (eventstate >= 300 || eventstate < 200)         // 2xx good
                            ret += "Error to request " + (events[i])["eventName"].Str() + " " + events[i].ToString() + " with " + ro["eventStatusText"].Str() + Environment.NewLine;
                    }
                }
{'fraction_non_alphanumeric': 0.09599627560521415, 'fraction_numerical': 0.005121042830540037, 'mean_word_length': 2.0036353467561523, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 29, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4796686', 'n_tokens_mistral': 2808, 'n_tokens_neox': 2659, 'n_words': 823}