Initial Commit.
[KerbalStuffWrapper.git] /
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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
88
89
90
91
92
93
94
95
using MiniJSON;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;

namespace KerbalStuffWrapper
{
	public static class KerbalStuffWrapper
	{
		private static HttpWebRequest currentRequest;
		private static HttpWebResponse currentResponse;
		private static CookieContainer cookies;

		private static void ExecuteRequest(string uri, string method, bool assignCookies)
		{
			if (uri == string.Empty)
			{
				throw new ArgumentOutOfRangeException("KerbalStuffWrapper.ExecuteRequest: uri must not be empty.");
			}

			method = method.ToUpper();

			if (method != "POST" && method != "GET")
			{
				throw new ArgumentOutOfRangeException("KerbalStuffWrapper.ExecuteRequest: method must be POST or GET.");
			}

			currentRequest = (HttpWebRequest)WebRequest.Create(uri);
			currentRequest.Method = method;

			if (assignCookies)
			{
				if (cookies == null)
				{
					throw new ArgumentNullException("KerbalStuffWrapper.ExecuteRequest: cookies must not be null.");
				}

				currentRequest.CookieContainer = cookies;
			}


		}

		public static List<Dictionary<string, object>> Search(string query)
		{
			// ServicePointManager.ServerCertificateValidationCallback
			string uri = string.Format(KerbalStuffAction.Search.UriFormat, query);

			HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
			req.Method = KerbalStuffAction.Search.RequestMethod;

			var responseReader = new StreamReader(req.GetResponse().GetResponseStream());

			string json = responseReader.ReadToEnd();

			Console.WriteLine(json);

			object jsonObj = Json.Deserialize(json);

			return (List<Dictionary<string, object>>)jsonObj;
		}
	}

	public struct KerbalStuffAction
	{
		public static readonly KerbalStuffAction Search = new KerbalStuffAction("search", "search/mod?query=%s", "GET");
		public static readonly KerbalStuffAction ModInfo = new KerbalStuffAction("modinfo", "mod/%d", "GET");

		public const string APIUri = "https://www.kerbalstuff.com/api/";

		public string Action;

		public string UriPathFormat;

		public string RequestMethod;

		public string UriFormat
		{
			get
			{
				return string.Format("{0}{1}", APIUri, this.UriPathFormat);
			}
		}

		public KerbalStuffAction(string action, string uriFormat, string requestMethod) : this()
		{
			this.Action = action;
			this.UriPathFormat = uriFormat;
			this.RequestMethod = requestMethod;
		}
	}
}