ShoptimizaWebClient.cs 13.1 KB
Newer Older
1 2 3 4 5 6
using Newtonsoft.Json;
using Shoptimiza;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
7 8
using System.Runtime.Serialization;
using System.Text;
9 10 11

namespace ShoptimizaSalesFileExporter
{
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
    public class ShoptimizaUnableToFetchMappings : Exception
    {
        public ShoptimizaUnableToFetchMappings()
        {
        }

        public ShoptimizaUnableToFetchMappings(string message) : base(message)
        {
        }

        public ShoptimizaUnableToFetchMappings(string message, Exception innerException) : base(message, innerException)
        {
        }

        protected ShoptimizaUnableToFetchMappings(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }
    }
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
    public class ShoptimizaInvalidSignatureException : Exception
    {
        public ShoptimizaInvalidSignatureException() { }
        public ShoptimizaInvalidSignatureException(string message) : base(message) { }
        public ShoptimizaInvalidSignatureException(string message, Exception inner) : base(message, inner) { }
    }
    public class ShoptimizaInvalidAPIKeyException : Exception
    {
        public ShoptimizaInvalidAPIKeyException() { }
        public ShoptimizaInvalidAPIKeyException(string message) : base(message) { }
        public ShoptimizaInvalidAPIKeyException(string message, Exception inner) : base(message, inner) { }
    }
    public class ShoptimizaNotFoundException : Exception
    {
        public ShoptimizaNotFoundException() { }
        public ShoptimizaNotFoundException(string message) : base(message) { }
        public ShoptimizaNotFoundException(string message, Exception inner) : base(message, inner) { }
47 48
    }
    public class ShoptimizaTooManyErroredRequests : Exception
49
    {
50
        public List<Tuple<HttpStatusCode, string>> ErrorSummary;
51

52 53 54
        public ShoptimizaTooManyErroredRequests() { }
        public ShoptimizaTooManyErroredRequests(string message) : base(message) { }
        public ShoptimizaTooManyErroredRequests(string message, Exception inner) : base(message, inner) { }
55

56
        public ShoptimizaTooManyErroredRequests(List<Tuple<HttpStatusCode, string>> errorSummary)
57
        {
58
            this.ErrorSummary = errorSummary;
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
        }
    }

    sealed class ShoptimizaWebClient
    {
        public string apiKey;
        public string sharedSecret;

        public ShoptimizaWebClient(string apiKey, string sharedSecret)
        {
            this.apiKey = apiKey;
            this.sharedSecret = sharedSecret;
        }
        private bool IsInvalidSignature(Dictionary<string, string> input)
        {
            if (input.TryGetValue("reason", out string reason))
            {
                return reason.Equals("invalid signature");
            }
            return false;
        }
        private bool IsInvalidAPIKey(Dictionary<string, string> input)
        {
            if (input.TryGetValue("reason", out string reason))
            {
                return reason.Equals("invalid apiKey");
            }
            return false;
        }
88
        private int? ExtractTimeDelta(Dictionary<string, string> input, DateTime ourTime)
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
        {
            string reason = "";
            string timeAsString = "";
            if (!input.TryGetValue("reason", out reason))
            {
                return null;
            }
            if (!reason.Equals("timeout"))
            {
                return null;
            }
            if (!input.TryGetValue("time", out timeAsString))
            {
                return null;
            }

            if (Int32.TryParse(timeAsString, out Int32 time))
            {
107
                return time - AuthHeader.DateTimeToUnixTimeStamp(ourTime);
108 109 110
            }
            return null;
        }
111
        private static string GetResponseString(HttpWebResponse response)
112
        {
113
            if (response.ContentLength == 0)
114 115 116 117
            {
                return null;
            }

118
            Encoding encoding = Encoding.GetEncoding(response.CharacterSet);
119 120 121 122 123 124 125 126 127 128
            using (var responseStream = response.GetResponseStream())
            using (var reader = new StreamReader(responseStream, encoding))
            {
                return reader.ReadToEnd();
            }

        }
        public string DoGetRequest(string url)
        {
            url = url.Replace("$apiKey", this.apiKey);
129
            Console.WriteLine("Http request {0}", url);
130 131 132 133
            double timeDelta = 0;
            HttpWebRequest req;
            string authHeaderValue;
            DateTime now;
134
            List<Tuple<HttpStatusCode, string>> errorSummary = new List<Tuple<HttpStatusCode, string>>();
135 136 137 138

            for (int i = 0; i < 5; i++)
            {
                req = (HttpWebRequest)WebRequest.Create(url);
139
                req.UserAgent = "Shoptimiza Sales File Exporter";
140
                req.Accept = "application/json";
141

142 143
                now = DateTime.Now.AddSeconds(timeDelta);
                authHeaderValue = AuthHeader.SignatureForGetRequest(this.apiKey, now, url, this.sharedSecret);
144
                Console.WriteLine("auth header {1}:{0}", Shoptimiza.AuthHeader.Header, authHeaderValue);
145
                req.Headers.Add(Shoptimiza.AuthHeader.Header, authHeaderValue);
146 147 148
                req.Timeout = 10 * 1000;
                try
                {
149 150
                    using (var response = (HttpWebResponse)req.GetResponse())
                    {
151
                        if (response.StatusCode == HttpStatusCode.OK)
152
                        {
153
                            return GetResponseString(response);
154 155 156
                        }
                    }
                }
157
                catch (WebException ex)
158 159 160 161 162 163 164 165
                {
                    if (ex.Status == WebExceptionStatus.ProtocolError)
                    {
                        var response = ex.Response as HttpWebResponse;
                        if (response != null)
                        {
                            handleErrors(response);
                        }
166
                        continue;
167
                    }
168
                    throw ex;
169 170

                }
171 172
                // TODO: add exponential backoff
                System.Threading.Thread.Sleep(2 * 1000);
173
            }
174 175 176 177 178
            if (errorSummary.Count > 0)
            {
                throw new ShoptimizaTooManyErroredRequests(errorSummary);
            }
            return null;
179 180 181

            void handleErrors(HttpWebResponse input)
            {
182 183 184 185 186 187 188 189 190 191
                /* A request can lead to 3 results
                 * a) Everything fine, it returs some json
                 * b) The other end does not expect this and returns a 404, a 500, a 302 or wathever. Die.
                 * c) The other end understands our request but there is something wrong with it. It can be a mismatch between times, signature
                 * error, etc.
                 * 
                 * We only care about a) and c). C should tell us more about the error. We might retry in case of time mismatch
                 * There is no point in retrying a 404.
                 */
                Dictionary<string, string> error = null;
192 193 194
                Stream stream = input.GetResponseStream();
                StreamReader reader = new StreamReader(stream);
                string body = reader.ReadToEnd();
195 196 197 198 199 200
                errorSummary.Add(new Tuple<HttpStatusCode, string>(input.StatusCode, body));
                if (body == "" || !input.ContentType.ToLower().Contains("json"))
                {
                    // nothing we can do here
                    return;
                }
201

202 203
                if (input.StatusCode != HttpStatusCode.Forbidden)
                {
204 205
                    return;
                }
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227


                try
                {
                    error = JsonConvert.DeserializeObject<Dictionary<string, string>>(body);
                }
                catch (Exception ex)
                {
                    // If we can 
                    return;
                }

                if (IsInvalidSignature(error))
                {
                    throw new ShoptimizaInvalidSignatureException();
                }

                if (IsInvalidAPIKey(error))
                {
                    throw new ShoptimizaInvalidAPIKeyException();
                }

228
                int? newDelta = ExtractTimeDelta(error, now);
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
                if (newDelta.HasValue)
                {
                    timeDelta = newDelta.Value;
                }
            }

        }

        internal string DoPutRequest(string filePath, string url)
        {

            string fileHash = null;
            int fileLength = 0;
            if (!string.IsNullOrEmpty(filePath))
            {
                fileHash = AuthHeader.GetFileHash(filePath);
            }
            var now = new DateTime();



            //------
            url = url.Replace("$apiKey", this.apiKey);
            double timeDelta = 0;
            HttpWebRequest req;
            string authHeaderValue;
            List<Tuple<HttpStatusCode, string>> errorSummary = new List<Tuple<HttpStatusCode, string>>();

            for (int i = 0; i < 5; i++)
            {
                req = (HttpWebRequest)WebRequest.Create(url);
                req.UserAgent = "Shoptimiza Sales File Exporter";
                req.Accept = "application/json";
                now = DateTime.Now.AddSeconds(timeDelta);
                if (string.IsNullOrEmpty(fileHash))
                {
                    authHeaderValue = AuthHeader.SignatureForGetRequest(this.apiKey, now, url, this.sharedSecret);
                    req.Method = "GET";
                }
                else
                {
                    authHeaderValue = AuthHeader.SignatureForPutRequest(this.apiKey, now, url, this.sharedSecret, fileHash);
                    req.Method = "PUT";
                }

                req.Headers.Add(Shoptimiza.AuthHeader.Header, authHeaderValue);
                if (!string.IsNullOrEmpty(filePath))
                {
                    using (var stream = File.OpenRead(filePath))
                    {
                        stream.CopyTo(req.GetRequestStream());
                    }
                }

                req.Timeout = 10 * 1000;
                try
                {
                    using (var response = (HttpWebResponse)req.GetResponse())
                    {
                        int statusCode = (int)response.StatusCode - 200;
                        if (statusCode >= 0 && statusCode <= 99)
                        {
                            return GetResponseString(response);
                        }
                    }
                }
                catch (WebException ex)
                {
                    if (ex.Status == WebExceptionStatus.ProtocolError)
                    {
                        var response = ex.Response as HttpWebResponse;
                        if (response != null)
                        {
                            handleErrors(response);
                        }
                    }

                }
            }
            if (errorSummary.Count > 0)
            {
                throw new ShoptimizaTooManyErroredRequests(errorSummary);
            }
            return null;

            void handleErrors(HttpWebResponse input)
            {
                /* A request can lead to 3 results
                 * a) Everything fine, it returs some json
                 * b) The other end does not expect this and returns a 404, a 500, a 302 or wathever. Die.
                 * c) The other end understands our request but there is something wrong with it. It can be a mismatch between times, signature
                 * error, etc.
                 * 
                 * We only care about a) and c). C should tell us more about the error. We might retry in case of time mismatch
                 * There is no point in retrying a 404.
                 */
                Dictionary<string, string> error = null;
                Stream stream = input.GetResponseStream();
                StreamReader reader = new StreamReader(stream);
                string body = reader.ReadToEnd();
                errorSummary.Add(new Tuple<HttpStatusCode, string>(input.StatusCode, body));
                if (body == "" || !input.ContentType.ToLower().Contains("json"))
                {
                    // nothing we can do here
                    return;
                }

                if (input.StatusCode != HttpStatusCode.Forbidden)
                {
                    return;
                }


                try
                {
                    error = JsonConvert.DeserializeObject<Dictionary<string, string>>(body);
                }
                catch (Exception ex)
                {
                    // If we can 
                    return;
                }

352 353 354 355 356 357 358 359 360 361
                if (IsInvalidSignature(error))
                {
                    throw new ShoptimizaInvalidSignatureException();
                }

                if (IsInvalidAPIKey(error))
                {
                    throw new ShoptimizaInvalidAPIKeyException();
                }

362
                int? newDelta = ExtractTimeDelta(error, now);
363 364 365 366 367 368 369 370 371
                if (newDelta.HasValue)
                {
                    timeDelta = newDelta.Value;
                }
            }

        }
    }
}