-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathMarketInfoItem.cs
More file actions
260 lines (236 loc) · 9.36 KB
/
MarketInfoItem.cs
File metadata and controls
260 lines (236 loc) · 9.36 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
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
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using Utilities;
namespace EddiDataDefinitions
{
// EDDN Schema reference: https://github.com/EDSM-NET/EDDN/blob/master/schemas/commodity-v3.0.json
/// <summary> This class is designed to be deserialized from market.json or from the Frontier API.
/// This class is designed to be serialized and passed to the commodity schema on EDDN. </summary>
public class MarketInfoItem
{
[JsonProperty("name")]
public string edName
{
get => _edName;
set => _edName = value.ToLowerInvariant()
.Replace("$", "")
.Replace("_name;", "");
}
[JsonIgnore]
private string _edName;
// Station prices
[JsonProperty, JsonConverter(typeof(DecimalToIntPriceConverter))]
public int buyPrice { get; set; }
[JsonProperty, JsonConverter(typeof(DecimalToIntPriceConverter))]
public int meanPrice { get; set; }
[JsonProperty, JsonConverter(typeof(DecimalToIntPriceConverter))]
public int sellPrice { get; set; }
// Station in-stock parameter
[JsonProperty]
public int stock
{
get => _stock;
set
{
if (value > 0)
{
statusFlags.Add("Producer");
}
_stock = value;
}
}
[JsonIgnore]
private int _stock;
[JsonConverter(typeof(NullableCommodityBracketConverter))]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate, NullValueHandling = NullValueHandling.Include)]
public CommodityBracket? stockBracket { get; set; } // Possible values are 0, 1, 2, 3, or "" so we use an optional enum
// Station in-demand parameters
[JsonProperty]
public int demand
{
get => _demand;
set
{
if (value > 1)
{
statusFlags.Add("Consumer");
}
_demand = value;
}
}
[JsonIgnore]
private int _demand;
[JsonConverter(typeof(NullableCommodityBracketConverter))]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate, NullValueHandling = NullValueHandling.Include)]
public CommodityBracket? demandBracket { get; set; } // Possible values are 0, 1, 2, 3, or "" so we use an optional enum
// Implement conditional property serialization for select properties (ref. https://www.newtonsoft.com/json/help/html/ConditionalProperties.htm)
// This allows properties to be deserialized to the class but not serialized to EDDN.
[JsonProperty("id")]
public long EliteID { get; set; }
public static bool ShouldSerializeEliteID () => false;
// The EDDN schema does not currently permit category.
[JsonProperty]
public string category
{
get => _category;
set => _category = value.ToLowerInvariant()
.Replace("$market_category", "")
.Replace("_", "")
.Replace(";", "");
}
[JsonIgnore]
private string _category;
// The Frontier API uses `categoryName` rather than `category`, we normalize that here.
[JsonProperty] // As a private property, it can be deserialized but shall not be serialized to EDDN.
private protected string categoryName { set => category = value; }
public static bool ShouldSerializecategory () => false;
[JsonProperty]
public bool rare
{
get => _rare;
set
{
if (value)
{
statusFlags.Add("Rare");
}
_rare = value;
}
}
[JsonIgnore]
private bool _rare;
public static bool ShouldSerializerare() => false;
[JsonProperty]
public HashSet<string> statusFlags { get; set; } = [ ];
public bool ShouldSerializestatusFlags()
{
// Don't serialize status flags if they are empty as the schema requires that if present they contain at least 1 element
return statusFlags != null && statusFlags.Count > 0;
}
public bool IsMarketable()
{
// Don't serialize non-marketable commodities such as drones / limpets
if ( string.Equals( category.Replace( "-", "" ), "nonmarketable", StringComparison.OrdinalIgnoreCase ) ||
string.Equals( edName, "drones", StringComparison.OrdinalIgnoreCase ) )
{
return false;
}
return true;
}
public MarketInfoItem()
{ }
public MarketInfoItem(long eliteId, string Name, string Category, int BuyPrice, int SellPrice, int MeanPrice, CommodityBracket? StockBracket, CommodityBracket? DemandBracket, int Stock, int Demand, bool Rare = false, HashSet<string> statusFlags = null)
{
this.EliteID = eliteId;
this.edName = Name;
this.category = Category;
this.buyPrice = BuyPrice;
this.sellPrice = SellPrice;
this.meanPrice = MeanPrice;
this.stockBracket = StockBracket;
this.demandBracket = DemandBracket;
this.stock = Stock;
this.demand = Demand;
this.rare = Rare;
this.statusFlags = statusFlags ?? this.statusFlags;
}
public CommodityMarketQuote ToCommodityMarketQuote()
{
try
{
Logging.Debug($"Converting MarketInfoItem to CommodityMarketQuote: ", this);
var definition = CommodityDefinition.CommodityDefinitionFromEliteID(EliteID, edName) ?? CommodityDefinition.FromEDName(edName);
if (!string.Equals( edName, definition?.edname, StringComparison.OrdinalIgnoreCase ) )
{
// Unknown or obsolete commodity definition; report the full object so that we can update the definitions
Logging.Info("Commodity definition error: " + edName, JsonConvert.SerializeObject(this));
}
definition ??= new CommodityDefinition(EliteID, edName, CommodityCategory.FromEDName(category), meanPrice);
var quote = new CommodityMarketQuote(definition)
{
avgprice = meanPrice,
buyprice = buyPrice,
stock = stock,
stockbracket = stockBracket,
sellprice = sellPrice,
demand = demand,
demandbracket = demandBracket,
StatusFlags = statusFlags
};
return quote;
}
catch (Exception ex)
{
Logging.Error($"Failed to parse OutfittingInfoItem.", ex);
}
return null;
}
}
public class NullableCommodityBracketConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(CommodityBracket?);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanRead => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
serializer.Serialize(writer, "");
}
else if (value is string s)
{
serializer.Serialize(writer, s);
}
else if (value is CommodityBracket bracket)
{
serializer.Serialize(writer, bracket);
}
}
}
// Prices are sometimes written as floats (either to Market.json or to the Frontier API).
// These must be converted to integers before they can be passed to EDDN.
class DecimalToIntPriceConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(decimal) || objectType == typeof(decimal?));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader);
if (token.Type is JTokenType.Float or JTokenType.Integer)
{
return token.ToObject<int>();
}
if (token.Type == JTokenType.Null)
{
return null;
}
throw new JsonSerializationException("Unexpected token type: " +
token.Type.ToString());
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is null)
{
serializer.Serialize(writer, null);
}
else if (value is int i)
{
serializer.Serialize(writer, i);
}
else if (value is decimal d)
{
serializer.Serialize(writer, Convert.ToInt32(d));
}
}
}
}