Add project files.

This commit is contained in:
2022-11-01 18:01:28 +01:00
parent f7069a830d
commit dadae23393
73 changed files with 7076 additions and 0 deletions

View File

@@ -0,0 +1,70 @@
using System.Text;
using EDPlayerJournal.Entries;
namespace EDPlayerJournal.BGS;
public class BuyCargo : Transaction {
public BuyCargo() { }
public BuyCargo(MarketBuyEntry e) {
Entries.Add(e);
}
public string? Cargo {
get {
string? cargo;
var sell = Entries.OfType<MarketBuyEntry>().First();
if (!string.IsNullOrEmpty(sell.TypeLocalised)) {
cargo = sell.TypeLocalised;
} else {
cargo = sell.Type;
if (cargo != null && cargo.Length >= 2) {
cargo = cargo[0].ToString().ToUpper() + cargo.Substring(1);
}
}
return cargo;
}
}
public long Amount {
get { return Entries.OfType<MarketBuyEntry>().Sum(x => x.Count); }
}
public override int CompareTo(Transaction? other) {
if (other == null || other.GetType() != typeof(BuyCargo)) {
return -1;
}
BuyCargo? buycargo = other as BuyCargo;
if (buycargo != null &&
buycargo.Cargo == Cargo &&
buycargo.System == System &&
buycargo.Faction == Faction) {
return 0;
}
return -1;
}
public override string ToString() {
StringBuilder builder = new StringBuilder();
if (Entries.Count <= 0) {
return builder.ToString();
}
builder.AppendFormat("Bought {0} {1} at the Commodity Market",
Amount,
Cargo
);
return builder.ToString().Trim();
}
/// <summary>
/// Selling resources to a market only helps the controlling faction
/// </summary>
public override bool OnlyControllingFaction => true;
}

View File

@@ -0,0 +1,56 @@
using System.Linq;
using System.Text;
using EDPlayerJournal.Entries;
namespace EDPlayerJournal.BGS;
public class Cartographics : Transaction {
public Cartographics(MultiSellExplorationDataEntry e) {
Entries.Add(e);
}
public Cartographics(SellExplorationDataEntry e) {
Entries.Add(e);
}
public override int CompareTo(Transaction? other) {
if (other == null || other.GetType() != typeof(Cartographics)) {
return -1;
}
Cartographics? b = other as Cartographics;
if (b != null &&
b.System == System &&
b.Faction == Faction &&
b.Station == Station) {
return 0;
}
return -1;
}
public long TotalSum {
get {
/* add multi sell and normal ones together */
long total =
Entries.OfType<MultiSellExplorationDataEntry>()
.Sum(x => x.TotalEarnings)
+
Entries.OfType<SellExplorationDataEntry>()
.Sum(x => x.TotalEarnings)
;
return total;
}
}
public override string ToString() {
StringBuilder builder = new StringBuilder();
builder.AppendFormat("Sold {0} worth of Cartographics Data", Credits.FormatCredits(TotalSum));
return builder.ToString();
}
/// <summary>
/// Cartographics only help the controlling faction.
/// </summary>
public override bool OnlyControllingFaction => true;
}

View File

@@ -0,0 +1,42 @@
using System;
using System.Linq;
namespace EDPlayerJournal.BGS;
public class CombatZone : Transaction {
public string Type { get; set; } = "";
public string Grade { get; set; } = "";
public int Amount { get; set; } = 0;
public DateTime Completed { get; set; } = DateTime.UtcNow;
public override string CompletedAt {
get {
return Completed.ToString("dd.MM.yyyy HH:mm UTC");
}
}
public override int CompareTo(Transaction? obj) {
if (obj == null || obj.GetType() != typeof(CombatZone)) {
return -1;
}
CombatZone? b = obj as CombatZone;
if (b == null) {
return -1;
}
if (b.Faction != Faction || b.System != System) {
return -1; // System and faction don't match
}
if (b.Type != b.Type || b.Grade != b.Grade) {
return -1; // grade and type don't match
}
return 0;
}
public override string ToString() {
return string.Format("Won {0} x {1} {2} Combat Zone(s) for {3}",
Amount, Grade, Type, Faction);
}
}

View File

@@ -0,0 +1,42 @@
using EDPlayerJournal.Entries;
namespace EDPlayerJournal.BGS;
public class FactionKillBonds : Transaction {
public int TotalSum {
get {
return Entries
.OfType<FactionKillBondEntry>()
.Sum(x => x.Reward)
;
}
}
public string? VictimFaction {
get {
return Entries
.OfType<FactionKillBondEntry>()
.First()
.VictimFaction
;
}
}
public override int CompareTo(Transaction? other) {
if (other == null || other.GetType() != typeof(FactionKillBonds)) {
return -1;
}
FactionKillBonds? b = other as FactionKillBonds;
if (b == null || b.VictimFaction == VictimFaction) {
return 0;
}
return -1;
}
public override string ToString() {
return string.Format("Faction Kill Bonds: {0} against {1}",
Credits.FormatCredits(TotalSum),
VictimFaction);
}
}

View File

@@ -0,0 +1,66 @@
using System.Text;
using EDPlayerJournal.Entries;
namespace EDPlayerJournal.BGS;
/// <summary>
/// 36 Lessons of Vivec, Sermon Thirty Six
/// </summary>
public class FoulMurder : Transaction {
public FoulMurder() { }
public FoulMurder (CommitCrimeEntry e) {
Entries.Add(e);
}
public string? CrimeType {
get { return Entries.OfType<CommitCrimeEntry>().First().CrimeType; }
}
public long Bounties => Entries.OfType<CommitCrimeEntry>().Sum(x => x.Bounty);
public long Fines => Entries.OfType<CommitCrimeEntry>().Sum(x => x.Fine);
public override int CompareTo(Transaction? other) {
if (other == null || other.GetType() != typeof(FoulMurder)) {
return -1;
}
FoulMurder? hortator = other as FoulMurder;
if (hortator != null &&
Faction == hortator.Faction &&
CrimeType == hortator.CrimeType) {
return 0;
}
return -1;
}
public override string ToString() {
StringBuilder builder = new StringBuilder();
string type;
if (CrimeType == CrimeTypes.Murder) {
if (Entries.Count > 1) {
type = "ships";
} else {
type = "ship";
}
} else {
if (Entries.Count > 1) {
type = "people";
} else {
type = "person";
}
}
builder.AppendFormat("Murdered {0} {1} of {2} (Bounties: {3}, Fines: {4})",
Entries.Count,
type,
Faction,
Credits.FormatCredits(Bounties),
Credits.FormatCredits(Fines)
);
return builder.ToString();
}
}

View File

@@ -0,0 +1,12 @@
namespace EDPlayerJournal.BGS;
internal class IncompleteTransaction : Transaction {
public Transaction? UnderlyingTransaction { get; set; } = null;
public string Reason { get; set; } = "";
public IncompleteTransaction() { }
public IncompleteTransaction(Transaction? underlying, string reason) {
UnderlyingTransaction = underlying;
Reason = reason;
}
}

View File

@@ -0,0 +1,45 @@
using System.Text;
using EDPlayerJournal.Entries;
namespace EDPlayerJournal.BGS;
/// <summary>
/// This class is used when a completed mission gives influence to another
/// faction as well. This happens, for example, when you deliver cargo from one
/// faction to another. Both sometimes gain influence.
/// </summary>
public class InfluenceSupport : Transaction {
public string Influence { get; set; } = "";
public MissionCompletedEntry? RelevantMission { get; set; }
public override string CompletedAt {
get {
if (RelevantMission == null) {
return "";
}
return RelevantMission.Timestamp.ToString("dd.MM.yyyy hh:mm UTC");
}
}
public override string ToString() {
StringBuilder builder = new StringBuilder();
string? missionname;
if (RelevantMission != null) {
missionname = RelevantMission.HumanReadableName;
} else {
missionname = "UNKNOWN MISSION";
}
if (missionname == null) {
return "";
}
builder.AppendFormat("Influence gained from \"{0}\": \"{1}\"",
missionname,
string.IsNullOrEmpty(Influence) ? "NONE" : Influence
);
return builder.ToString();
}
}

View File

@@ -0,0 +1,64 @@
using System.Text;
using EDPlayerJournal.Entries;
namespace EDPlayerJournal.BGS;
public class MissionCompleted : Transaction {
public MissionCompleted() { }
public MissionCompleted(MissionCompletedEntry e) {
Entries.Add(e);
}
public string MissionName {
get {
MissionCompletedEntry? c = Entries[0] as MissionCompletedEntry;
if (c == null) {
return "";
}
if (string.IsNullOrEmpty(c.HumanReadableName)) {
return (c.Name ?? "");
} else {
return c.HumanReadableName;
}
}
}
public string Influence {
get {
MissionCompletedEntry? e = (Entries[0] as MissionCompletedEntry);
if (e == null || Faction == null) {
return "";
}
if (SystemAddress == 0) {
return (e.GetInfluenceForFaction(Faction) ?? "");
} else {
return (e.GetInfluenceForFaction(Faction, SystemAddress) ?? "");
}
}
}
public override string ToString() {
if (Faction == null || Entries.Count <= 0) {
return "";
}
StringBuilder builder = new StringBuilder();
var entry = Entries[0] as MissionCompletedEntry;
if (entry == null) {
return "";
}
var influence = entry.GetInfluenceForFaction(Faction, SystemAddress);
builder.AppendFormat("{0}", MissionName);
if (influence != "") {
builder.AppendFormat(", Influence: {0}", influence);
}
return builder.ToString();
}
}

View File

@@ -0,0 +1,55 @@
using System.Text;
using EDPlayerJournal.Entries;
namespace EDPlayerJournal.BGS;
public class MissionFailed : Transaction {
public MissionFailedEntry? Failed { get; set; }
public MissionAcceptedEntry? Accepted { get; set; }
public MissionFailed() { }
public MissionFailed(MissionAcceptedEntry accepted) {
Accepted = accepted;
Faction = accepted.Faction;
}
public override int CompareTo(Transaction? other) {
if (other == null || other.GetType() != typeof(MissionFailed)) {
return -1;
}
MissionFailed? failed = other as MissionFailed;
if (failed == null) {
return -1;
}
/* if it is the same mission name, the same faction and the same system,
* collate mission failures together */
if (failed.Failed?.HumanReadableName == Failed?.HumanReadableName &&
failed.Faction == Faction &&
failed.System == System) {
return 0;
}
return -1;
}
// +1 since the other entries are just copies of the one we have in our properties
public int Amount => Entries.Count + 1;
public override string ToString() {
StringBuilder builder = new StringBuilder();
if (Failed == null || Accepted == null) {
return "";
}
builder.AppendFormat("{0}x Mission failed: \"{1}\"",
Amount,
Failed.HumanReadableName != null ? Failed.HumanReadableName : Failed.Name
);
return builder.ToString();
}
}

View File

@@ -0,0 +1,126 @@
using System.Collections.Generic;
using System;
using System.Text;
using Newtonsoft.Json;
namespace EDPlayerJournal.BGS;
public class Objective : IComparable<Objective> {
private List<Transaction> entries = new List<Transaction>();
[JsonIgnore]
public bool IsEnabled { get; set; }
[JsonIgnore]
public List<Transaction> Children {
get => entries;
}
[JsonIgnore]
public string Name => this.ToString();
[JsonIgnore]
public bool IsExpanded { get; set; }
[JsonIgnore]
public List<Transaction> LogEntries {
get => entries;
set => entries = value;
}
public void Clear() {
if (entries == null) {
return;
}
entries.Clear();
}
public int Matches(Transaction e) {
int match_count = 0;
if (e.OnlyControllingFaction) {
if (Faction == null || (e.Faction != Faction)) {
return 0;
}
}
if (e.Faction != null && Faction != null) {
if (string.Compare(e.Faction, Faction, true) != 0) {
/* if we have a faction, and it doesn't match we don't care.
* faction is the most important comparision, so if it doesn't match
* it is not the right objective
*/
return 0;
} else {
++match_count;
}
}
/* system and station only add to the match strength though */
if (e.System != null && System != null) {
if (string.Compare(e.System, System, true) == 0) {
++match_count;
}
}
/* if system and faction already match, station is not so important */
if (e.Station != null && Station != null) {
if (string.Compare(e.Station, Station, true) == 0) {
++match_count;
}
}
return match_count;
}
public int CompareTo(Objective? other) {
if (other == null) {
return 0;
}
return (other.System == System &&
other.Station == Station &&
other.Faction == Faction) ? 0 : -1;
}
public bool IsValid => (!string.IsNullOrEmpty(System) && !string.IsNullOrEmpty(Faction));
public string System { get; set; } = "";
public string Station { get; set; } = "";
public string Faction { get; set; } = "";
public override string ToString() {
StringBuilder str = new StringBuilder();
if (System != null && System.Length > 0) {
str.AppendFormat("System: {0}", System);
}
if (Station != null && Station.Length > 0) {
if (str.Length > 0) {
str.Append(", ");
}
str.AppendFormat("Station: {0}", Station);
}
if (Faction != null && Faction.Length > 0) {
if (str.Length > 0) {
str.Append(", ");
}
str.AppendFormat("Faction: {0}", Faction);
}
return str.ToString();
}
public string ToShortString() {
StringBuilder str = new StringBuilder();
if (System != null && System.Length > 0) {
str.AppendFormat("{0}", System);
}
if (Station != null && Station.Length > 0) {
if (str.Length > 0) {
str.Append(", ");
}
str.AppendFormat("{0}", Station);
}
return str.ToString();
}
}

View File

@@ -0,0 +1,41 @@
using EDPlayerJournal.Entries;
namespace EDPlayerJournal.BGS;
public class OrganicData : Transaction {
public OrganicData(SellOrganicDataEntry e) {
Entries.Add(e);
}
public long TotalValue {
get {
return Entries.OfType<SellOrganicDataEntry>().Sum(x => x.TotalValue);
}
}
public override int CompareTo(Transaction? other) {
if (other == null || other.GetType() != typeof(OrganicData)) {
return -1;
}
if (other?.Faction == Faction &&
other?.System == System &&
other?.Station == Station) {
return 0;
}
return -1;
}
public override string ToString() {
return string.Format("Sold {0} worth of organic data to Vista Genomics",
Credits.FormatCredits(TotalValue)
);
}
/* Selling organic data only helps the controlling faction, just like
* selling cartographic data.
*/
public override bool OnlyControllingFaction => true;
}

View File

@@ -0,0 +1,672 @@
using System;
using System.Collections.Generic;
using System.Linq;
using EDPlayerJournal.Entries;
namespace EDPlayerJournal.BGS;
public class Report {
private List<Objective> objectives = new List<Objective>();
public delegate void OnLogDelegate(string log);
public event OnLogDelegate? OnLog;
public List<Objective> Objectives {
get { return objectives; }
set { objectives = value; }
}
public bool AddObjective(Objective objective) {
var found = objectives.Find(x => x.CompareTo(objective) == 0);
bool added = false;
if (found == null) {
objectives.Add(objective);
added = true;
}
return added;
}
public static bool IsRelevant(Entry e) {
return e.Is(Events.CommitCrime) ||
e.Is(Events.Docked) ||
e.Is(Events.FactionKillBond) ||
e.Is(Events.FSDJump) ||
e.Is(Events.Location) ||
e.Is(Events.MarketBuy) ||
e.Is(Events.MarketSell) ||
e.Is(Events.MissionAccepted) ||
e.Is(Events.MissionFailed) ||
e.Is(Events.MultiSellExplorationData) ||
e.Is(Events.RedeemVoucher) ||
e.Is(Events.SearchAndRescue) ||
e.Is(Events.SellExplorationData) ||
e.Is(Events.SellMicroResources) ||
e.Is(Events.SellOrganicData) ||
e.Is(Events.ShipTargeted) ||
e.Is(Events.MissionCompleted)
;
}
public void Scan(PlayerJournal journal, DateTime start, DateTime end) {
/* Log files only get rotated if you restart the game client. This means that there might
* be - say - entries from the 4th of May in the file with a timestamp of 3rd of May. This
* happens if you happen to play a session late into the night.
* At first I tried extracting the first and last line of a file to see the date range, but
* if you have a lot of files this becomes quite slow, and quite the memory hog (as journal
* files have to be read in their entirety to check this). So we assume that you can't play
* three days straight, and keep the code fast.
*/
DateTime actualstart = start.AddDays(-3);
List<Entry> entries = journal.Files
.Where(f => f.NormalisedDateTime >= actualstart && f.NormalisedDateTime <= end)
.SelectMany(e => e.Entries)
.ToList()
;
// Now further sort the list down to entries that are actually within the given datetime
// Note that entry datetimes are not normalised, so we have to sort until end + 1 day
DateTime actualend = end.AddDays(1);
entries = entries
.Where(e => e.Timestamp >= start && e.Timestamp < actualend)
.ToList()
;
Scan(entries);
}
public void Scan(List<Entry> entries) {
if (entries.Count <= 0) {
return;
}
List<Entry> relevant = entries
.Where(x => IsRelevant(x))
.ToList()
;
Dictionary<ulong, MissionAcceptedEntry> acceptedMissions = new Dictionary<ulong, MissionAcceptedEntry>();
Dictionary<string, long> buyCost = new Dictionary<string, long>();
Dictionary<ulong, string> systems = new Dictionary<ulong, string>();
Dictionary<string, string> npcfactions = new Dictionary<string, string>();
Dictionary<string, List<Faction>> system_factions = new Dictionary<string, List<Faction>>();
// A dictionary resolving to a station at which each mission was accepted
Dictionary<ulong, string> acceptedStations = new Dictionary<ulong, string>();
// A dictionary resolving to a system at which each mission was accepted
Dictionary<ulong, ulong> acceptedSystems = new Dictionary<ulong, ulong>();
string? current_system = null;
ulong? current_system_address = null;
string? current_station = null;
string? controlling_faction = null;
objectives.ForEach(x => x.Clear());
foreach (Entry e in relevant) {
List<Transaction> results = new List<Transaction>();
bool collate = false;
if (e.Is(Events.Docked)) {
DockedEntry? docked = e as DockedEntry;
if (docked == null) {
continue;
}
/* gleem the current station from this message
*/
current_station = docked.StationName;
current_system = docked.StarSystem;
controlling_faction = docked.StationFaction;
current_system_address = docked.SystemAddress;
if (current_system_address != null && current_system != null) {
if (!systems.ContainsKey(current_system_address.Value)) {
systems.Add(current_system_address.Value, current_system);
}
}
} else if (e.Is(Events.FSDJump)) {
/* Gleem current system and controlling faction from this message.
*/
FSDJumpEntry? fsd = e as FSDJumpEntry;
if (fsd == null || fsd.StarSystem == null) {
continue;
}
current_system_address = fsd.SystemAddress;
current_system = fsd.StarSystem;
controlling_faction = fsd.SystemFaction;
if (!systems.ContainsKey(fsd.SystemAddress)) {
systems.Add(fsd.SystemAddress, fsd.StarSystem);
}
if (!system_factions.ContainsKey(fsd.StarSystem) &&
fsd.SystemFactions.Count > 0) {
system_factions[fsd.StarSystem] = fsd.SystemFactions;
}
} else if (e.Is(Events.Location)) {
/* Get current system, faction name and station from Location message
*/
LocationEntry? location = e as LocationEntry;
if (location == null || location.StarSystem == null) {
continue;
}
current_system = location.StarSystem;
current_system_address = location.SystemAddress;
if (!systems.ContainsKey(location.SystemAddress)) {
systems.Add(location.SystemAddress, location.StarSystem);
}
if (!string.IsNullOrEmpty(location.SystemFaction)) {
controlling_faction = location.SystemFaction;
}
if (!string.IsNullOrEmpty(location.StationName)) {
current_station = location.StationName;
}
if (!system_factions.ContainsKey(location.StarSystem) &&
location.SystemFactions.Count > 0) {
system_factions[location.StarSystem] = location.SystemFactions;
}
} else if (e.Is(Events.ShipTargeted)) {
ShipTargetedEntry? targeted = e as ShipTargetedEntry;
if (targeted == null) {
continue;
}
if (string.IsNullOrEmpty(targeted.PilotNameLocalised) ||
string.IsNullOrEmpty(targeted.Faction)) {
continue;
}
npcfactions[targeted.PilotNameLocalised] = targeted.Faction;
} else if (e.Is(Events.CommitCrime)) {
CommitCrimeEntry? crime = e as CommitCrimeEntry;
if (crime == null) {
continue;
}
string? faction = crime.Faction;
if (faction == null || !crime.IsMurder) {
/* we don't care about anything but murder for now */
continue;
}
/* use localised victim name if we have it, otherwise use normal name */
string? victim = crime.VictimLocalised;
if (string.IsNullOrEmpty(victim)) {
victim = crime.Victim;
}
if (string.IsNullOrEmpty(victim)) {
continue;
}
if (!npcfactions.ContainsKey(victim)) {
/* The faction in the crime report is the faction that issues the bounty,
* and not the faction of the victim.
*/
OnLog?.Invoke(string.Format(
"No faction found for victim \"{0}\", using faction that issued the bounty instead.",
victim, crime.Faction
));
} else {
faction = npcfactions[victim];
}
results.Add(new FoulMurder(crime) {
System = current_system,
Faction = faction,
});
collate = true;
} else if (e.Is(Events.MissionCompleted)) {
MissionCompletedEntry? completed = e as MissionCompletedEntry;
if (completed == null ||
completed.MissionID == null) {
continue;
}
MissionAcceptedEntry? accepted = null;
MissionCompleted? main_mission = null;
ulong accepted_address;
string? accepted_system;
string? target_faction_name = completed.TargetFaction;
string? source_faction_name = completed.Faction;
if (!acceptedMissions.TryGetValue(completed.MissionID.Value, out accepted)) {
OnLog?.Invoke(string.Format(
"Unable to find mission acceptance for mission \"{0}\". " +
"Please extend range to include the mission acceptance.", completed.HumanReadableName
));
continue;
}
if (!acceptedSystems.TryGetValue(completed.MissionID.Value, out accepted_address)) {
OnLog?.Invoke(string.Format(
"Unable to figure out in which system mission \"{0}\" was accepted.", completed.HumanReadableName
));
continue;
}
if (!systems.TryGetValue(accepted_address, out accepted_system)) {
OnLog?.Invoke(string.Format(
"Unable to figure out in which system mission \"{0}\" was accepted.", completed.HumanReadableName
));
continue;
}
if (completed.HumanReadableNameWasGenerated) {
/* If the human readable name was generated, we send a log message. Because the
* generated names all sort of suck, we should have more human readable names in
* in the lookup dictionary.
*/
OnLog?.Invoke("Human readable name for mission \"" +
completed.Name +
"\" was generated, please report this.");
}
foreach (var other in completed.Influences) {
string faction = other.Key;
if (string.IsNullOrEmpty(faction)) {
OnLog?.Invoke(string.Format(
"Mission \"{0}\" has empty faction name in influence block, "+
"so this influence support was ignored. " +
"Please check the README on why this happens.", completed.HumanReadableName)
);
continue;
}
/* Now comes the fun part. Sometimes the influence list is empty for a faction.
* This happens if the faction in question
*/
if (other.Value.Count() == 0) {
OnLog?.Invoke(string.Format(
"Mission \"{0}\" gave no influence to \"{1}\", so we assume this is because the " +
"faction is in a conflict and cannot gain influence right now. " +
"If this assessment is wrong, just remove the entry from the objective list.",
completed.HumanReadableName, faction
));
if (string.Compare(target_faction_name, faction, true) == 0) {
/* here we assume that if the faction in question is the target faction,
* that we gave said target faction no influence in the target system, aka
* current system
*/
if (current_system_address == null) {
continue;
}
other.Value.Add(current_system_address.Value, "");
OnLog?.Invoke(string.Format(
"Mission \"{0}\" gave no influence to \"{1}\". Since \"{1}\" is the target faction " +
"of the mission, we assume the influence was gained in \"{2}\". " +
"Please remove the entry if this assumption is wrong.",
completed.HumanReadableName, faction, current_system
));
} else if (string.Compare(source_faction_name, faction, true) == 0) {
/* source faction of the mission is not getting any influence. This could be because
* the source faction is in an election state in its home system and cannot gain any
* influence. It may also very well be that the source and target faction are the same
* since the faction is present in both target and source system. In which case we add
* both and hope for the best.
*/
other.Value.Add(accepted_address, "");
OnLog?.Invoke(string.Format(
"Mission \"{0}\" gave no influence to \"{1}\". Since \"{1}\" is the source faction " +
"of the mission, we assume the influence was gained in \"{2}\". " +
"Please remove the entry if this assumption is wrong.",
completed.HumanReadableName, faction, accepted_system
));
/* check if source/target faction are equal, in which case we also need an entry
* for the target system. As said factions can be present in two systems, and can
* give missions that target each other.
*/
if (string.Compare(source_faction_name, target_faction_name, true) == 0 &&
current_system_address != null) {
other.Value.Add(current_system_address.Value, "");
OnLog?.Invoke(string.Format(
"Mission \"{0}\" gave no influence to \"{1}\". Since \"{1}\" is the source and target faction " +
"of the mission, we assume the influence was also gained in target system \"{2}\". " +
"Please remove the entry if this assumption is wrong.",
completed.HumanReadableName, faction, current_system
));
}
}
}
foreach (var influences in other.Value) {
ulong system_address = influences.Key;
string? system;
string? accepted_station;
if (completed.MissionID == null) {
continue;
}
if (!systems.TryGetValue(system_address, out system)) {
OnLog?.Invoke(string.Format(
"Unknown system \"{0}\" unable to assign that mission a target.", system_address
));
continue;
}
if (!acceptedStations.TryGetValue(completed.MissionID.Value, out accepted_station)) {
OnLog?.Invoke(string.Format(
"Unable to figure out in which station mission \"{0}\" was accepted.", completed.HumanReadableName
));
continue;
}
if (faction.Equals(source_faction_name) && system_address == accepted_address) {
/* This is the influence block for the origin of the mission.
*/
main_mission = new MissionCompleted(completed) {
System = accepted_system,
Faction = source_faction_name,
SystemAddress = accepted_address,
Station = accepted_station,
};
results.Add(main_mission);
} else if (!faction.Equals(source_faction_name) ||
(faction.Equals(source_faction_name) && system_address != accepted_address)) {
/* This block is for secondary factions (first if), or if the secondary faction
* is the same as the mission giver, but in another system (second if).
*/
results.Add(new InfluenceSupport() {
Faction = faction,
Influence = influences.Value,
System = system,
SystemAddress = system_address,
RelevantMission = completed
});
}
}
}
} else if (e.Is(Events.MissionAccepted)) {
MissionAcceptedEntry? accepted = e as MissionAcceptedEntry;
if (accepted == null ||
current_station == null ||
current_system_address == null) {
continue;
}
ulong id = accepted.MissionID;
if (!acceptedMissions.ContainsKey(id)) {
acceptedMissions[id] = accepted;
}
if (!acceptedStations.ContainsKey(id)) {
acceptedStations[id] = current_station;
}
if (!acceptedSystems.ContainsKey(id)) {
acceptedSystems[id] = current_system_address.Value;
}
} else if (e.Is(Events.MissionFailed)) {
MissionFailedEntry? failed = e as MissionFailedEntry;
MissionAcceptedEntry? accepted = null;
ulong accepted_address = 0;
string? accepted_system;
string? accepted_station;
if (failed == null) {
continue;
}
if (!acceptedMissions.TryGetValue(failed.MissionID, out accepted)) {
OnLog?.Invoke("A mission failed which wasn't accepted in the given time frame. " +
"Please adjust start date to when the mission was accepted to include it in the list.");
continue;
}
if (!acceptedSystems.TryGetValue(failed.MissionID, out accepted_address)) {
OnLog?.Invoke(string.Format(
"Unable to figure out in which system mission \"{0}\" was accepted.", accepted.Name
));
continue;
}
if (!systems.TryGetValue(accepted_address, out accepted_system)) {
OnLog?.Invoke(string.Format(
"Unable to figure out in which system mission \"{0}\" was accepted.", accepted.Name
));
continue;
}
if (!acceptedStations.TryGetValue(failed.MissionID, out accepted_station)) {
OnLog?.Invoke(string.Format(
"Unable to figure out in which station mission \"{0}\" was accepted.", accepted.Name
));
continue;
}
results.Add(new MissionFailed(accepted) {
Failed = failed,
System = accepted_system,
Station = accepted_station,
Faction = accepted.Faction,
SystemAddress = accepted_address,
});
if (failed.HumanReadableName == null) {
OnLog?.Invoke("Human readable name for mission \"" +
failed.Name +
"\" was not recognised");
}
/* Mission failed should be collated if they are in the same system/station
*/
collate = true;
} else if (e.Is(Events.SellExplorationData)) {
SellExplorationDataEntry? explo = e as SellExplorationDataEntry;
if (explo == null) {
continue;
}
results.Add(new Cartographics(explo) {
System = current_system,
Station = current_station,
Faction = controlling_faction,
});
/* colate single cartographic selling into one */
collate = true;
} else if (e.Is(Events.SellOrganicData)) {
SellOrganicDataEntry? organic = e as SellOrganicDataEntry;
if (organic == null) {
return;
}
/* organic data sold to Vista Genomics */
results.Add(new OrganicData(organic) {
System = current_system,
Station = current_station,
Faction = controlling_faction,
});
collate = true;
} else if (e.Is(Events.MultiSellExplorationData)) {
MultiSellExplorationDataEntry? explo = e as MultiSellExplorationDataEntry;
if (explo == null) {
continue;
}
/* For multi-sell-exploraton-data only the controlling faction of the station sold to matters.
*/
results.Add(new Cartographics(explo) {
System = current_system,
Station = current_station,
Faction = controlling_faction
});
collate = true;
} else if (e.Is(Events.RedeemVoucher)) {
RedeemVoucherEntry? voucher = e as RedeemVoucherEntry;
List<Faction> current_factions = new List<Faction>();
if (voucher == null || current_system == null) {
continue;
}
if (system_factions.ContainsKey(current_system)) {
current_factions = system_factions[current_system];
} else {
OnLog?.Invoke("There are no current system factions, so turned in vouchers were ignored.");
continue;
}
foreach (string faction in voucher.Factions) {
if (current_factions.Find(x => x.Name == faction) == null) {
OnLog?.Invoke(
string.Format("Vouchers for \"{0}\" were ignored in \"{1}\" since said " +
"faction is not present there.", faction, current_system)
);
continue; /* faction is not present, so it is ignored */
}
/* Same for selling combat vouchers. Only the current controlling faction matters here.
*/
results.Add(new Vouchers(voucher) {
System = current_system,
Station = current_station,
Faction = faction,
ControllingFaction = controlling_faction,
});
}
collate = true;
} else if (e.Is(Events.SellMicroResources)) {
SellMicroResourcesEntry? smr = e as SellMicroResourcesEntry;
if (smr == null) {
continue;
}
results.Add(new SellMicroResources(smr) {
Faction = controlling_faction,
Station = current_station,
System = current_system
});
} else if (e.Is(Events.MarketBuy)) {
MarketBuyEntry? buy = e as MarketBuyEntry;
if (buy == null) {
continue;
}
if (string.IsNullOrEmpty(buy.Type) || buy.BuyPrice == 0) {
continue;
}
buyCost[buy.Type] = buy.BuyPrice;
results.Add(new BuyCargo(buy) {
Faction = controlling_faction,
Station = current_station,
System = current_system,
});
collate = true;
} else if (e.Is(Events.SearchAndRescue)) {
SearchAndRescueEntry? sar = e as SearchAndRescueEntry;
if (sar == null) {
continue;
}
results.Add(new SearchAndRescue(sar) {
Faction = controlling_faction,
Station = current_station,
System = current_system,
});
collate = true;
} else if (e.Is(Events.MarketSell)) {
MarketSellEntry? sell = e as MarketSellEntry;
long profit = 0;
if (sell == null || sell.Type == null) {
continue;
}
if (!buyCost.ContainsKey(sell.Type)) {
OnLog?.Invoke("Could not find buy order for the given commodity. Please adjust profit manually.");
} else {
long avg = buyCost[sell.Type];
profit = (long)sell.TotalSale - (avg * sell.Count);
}
results.Add(new SellCargo(sell) {
Faction = controlling_faction,
Station = current_station,
System = current_system,
Profit = profit
});
}
if (results == null || results.Count <= 0) {
continue;
}
foreach (Transaction entry in results) {
/* Find all objectives that generally match.
*/
var matches = objectives
.Where(x => x.Matches(entry) >= 2)
.OrderBy(x => x.Matches(entry))
;
Objective? objective = null;
if (matches != null && matches.Count() > 0) {
/* Then select the one that matches the most.
*/
objective = matches
.OrderBy(x => x.Matches(entry))
.Reverse()
.First()
;
} else {
/* create a new objective if we don't have one */
objective = new Objective() {
Station = (entry.Station ?? ""),
Faction = (entry.Faction ?? ""),
System = (entry.System ?? ""),
};
objectives.Add(objective);
}
Transaction? existing = null;
existing = objective.LogEntries.Find(x => {
try {
return x.CompareTo(entry) == 0;
} catch (NotImplementedException) {
return false;
}
});
if (collate && existing != null) {
existing.Entries.Add(e);
} else if (!collate || existing == null) {
objective.LogEntries.Add(entry);
}
}
}
}
public void Scan(PlayerJournal journal) {
Scan(journal, DateTime.Now, DateTime.Now);
}
}

View File

@@ -0,0 +1,53 @@
using EDPlayerJournal.Entries;
namespace EDPlayerJournal.BGS;
public class SearchAndRescue : Transaction {
public SearchAndRescue (SearchAndRescueEntry e) {
Entries.Add(e);
}
public long Count {
get {
return Entries.OfType<SearchAndRescueEntry>().Sum(x => x.Count);
}
}
public long Reward {
get {
return Entries.OfType<SearchAndRescueEntry>().Sum(x => x.Reward);
}
}
public string? NameLocalised {
get {
return Entries.OfType<SearchAndRescueEntry>().First().NameLocalised;
}
}
public override int CompareTo(Transaction? o) {
if (o == null || o.GetType() != typeof(SearchAndRescue)) {
return -1;
}
SearchAndRescue? other = o as SearchAndRescue;
if (other?.System == System &&
other?.Station == Station &&
other?.Faction == Faction &&
other?.NameLocalised == NameLocalised) {
return 0;
}
return -1;
}
public override string ToString() {
return string.Format("Contributed {0} {1} to Search and Rescue ({2})",
Count,
NameLocalised,
Credits.FormatCredits(Reward)
);
}
public override bool OnlyControllingFaction => true;
}

View File

@@ -0,0 +1,73 @@
using System.Text;
using EDPlayerJournal.Entries;
namespace EDPlayerJournal.BGS;
public class SellCargo : Transaction {
public long Profit { get; set; }
public SellCargo() { }
public SellCargo(MarketSellEntry e) {
Entries.Add(e);
}
public string? Cargo {
get {
string? cargo;
var sell = Entries.OfType<MarketSellEntry>().First();
if (!string.IsNullOrEmpty(sell.TypeLocalised)) {
cargo = sell.TypeLocalised;
} else {
cargo = sell.Type;
if (cargo != null && cargo.Length >= 2) {
cargo = cargo[0].ToString().ToUpper() + cargo.Substring(1);
}
}
return cargo;
}
}
public string Market {
get {
var sell = Entries.OfType<MarketSellEntry>().First();
return sell.BlackMarket ? "Black Market" : "Commodity Market";
}
}
public long Amount {
get { return Entries.OfType<MarketSellEntry>().Sum(x => x.Count); }
}
public override string ToString() {
StringBuilder builder = new StringBuilder();
var sold = Entries.OfType<MarketSellEntry>().ToArray();
if (sold == null || sold.Length == 0) {
return builder.ToString();
}
foreach (MarketSellEntry sell in sold) {
builder.AppendFormat("Sold {0} {1} to the {2}",
sell.Count,
Cargo,
Market
);
if (Profit != 0) {
builder.AppendFormat(" ({0} {1})",
Credits.FormatCredits(Profit),
Profit < 0 ? "loss" : "profit"
);
}
}
return builder.ToString().Trim();
}
/// <summary>
/// Selling resources to a market only helps the controlling faction
/// </summary>
public override bool OnlyControllingFaction => true;
}

View File

@@ -0,0 +1,26 @@
using System.Linq;
using EDPlayerJournal.Entries;
namespace EDPlayerJournal.BGS;
public class SellMicroResources : Transaction {
public int TotalSum {
get {
return Entries
.OfType<SellMicroResourcesEntry>()
.Sum(x => x.Price)
;
}
}
public SellMicroResources() { }
public SellMicroResources(SellMicroResourcesEntry e) {
Entries.Add(e);
}
public override string ToString() {
return string.Format("Sell Micro Resources: {0}", Credits.FormatCredits(TotalSum));
}
public override bool OnlyControllingFaction => true;
}

View File

@@ -0,0 +1,44 @@
using EDPlayerJournal.Entries;
namespace EDPlayerJournal.BGS;
public class Transaction : IComparable<Transaction> {
public List<Entry> Entries { get; } = new List<Entry>();
public virtual string CompletedAt {
get {
var items = Entries
.OrderBy(x => x.Timestamp)
.ToArray()
;
if (items == null || items.Length == 0) {
return "Unknown";
}
Entry last = items.Last();
return last.Timestamp.ToString("dd.MM.yyyy HH:mm UTC");
}
}
/// <summary>
/// Controlling faction of the station this entry was made/turned into.
/// </summary>
public string? ControllingFaction { get; set; }
public string? Station { get; set; }
public string? System { get; set; }
public ulong SystemAddress { get; set; }
public string? Faction { get; set; }
/// <summary>
/// Whether this transaction type only benefits the controlling faction or not, default: no
/// </summary>
public virtual bool OnlyControllingFaction {
get { return false; }
}
public virtual int CompareTo(Transaction? other) {
throw new NotImplementedException("not implemented");
}
public string? Name => ToString();
}

View File

@@ -0,0 +1,619 @@
using EDPlayerJournal.Entries;
using System.Collections.Generic;
using System.Reflection.Metadata.Ecma335;
namespace EDPlayerJournal.BGS;
internal class TransactionParserContext {
public string? CurrentSystem { get; set; }
public ulong? CurrentSystemAddress { get; set; }
public string? CurrentStation { get; set; }
public string? ControllingFaction { get; set; }
/// <summary>
/// A list of accepted missions index by their mission ID
/// </summary>
public Dictionary<ulong, MissionAcceptedEntry> AcceptedMissions { get; } = new();
public Dictionary<ulong, Location> AcceptedMissionLocation { get; } = new();
/// <summary>
/// A way to lookup a system by its system id
/// </summary>
public Dictionary<ulong, string> SystemsByID { get; } = new();
/// <summary>
/// A list of factions present in the given star system
/// </summary>
public Dictionary<string, List<Faction>> SystemFactions { get; } = new();
/// <summary>
/// To which faction a given named NPC belonged to.
/// </summary>
public Dictionary<string, string> NPCFaction { get; } = new();
/// <summary>
/// Buy costs for a given commodity
/// </summary>
public Dictionary<string, long> BuyCost = new();
public void BoughtCargo(string? cargo, long? cost) {
if (cargo == null || cost == null) {
return;
}
BuyCost[cargo] = cost.Value;
}
public List<Faction>? GetFactions(string? system) {
if (system == null || !SystemFactions.ContainsKey(system)) {
return null;
}
return SystemFactions[system];
}
public void MissionAccepted(MissionAcceptedEntry accepted) {
if (CurrentSystem == null || CurrentSystemAddress == null) {
throw new Exception("Mission accepted without knowing where.");
}
AcceptedMissions.TryAdd(accepted.MissionID, accepted);
Location location = new() {
StarSystem = CurrentSystem,
SystemAddress = CurrentSystemAddress.Value,
Station = (CurrentStation ?? ""),
};
AcceptedMissionLocation.TryAdd(accepted.MissionID, location);
}
}
public class TransactionList : List<Transaction> {
public void AddIncomplete(Transaction underlying, string reason) {
Add(new IncompleteTransaction(underlying, reason));
}
}
internal interface TransactionParserPart{
/// <summary>
/// Parse a given entry of the entry type specified when declaring to implement this
/// interface. You must add your transaction to the passed list in case you did have
/// enough information to parse one or more. You may update the parser context
/// with new information in case the entry yielded new information.
/// Throw an exception if there was an error or a malformed entry. If you have an
/// incomplete entry, i.e. not enough information to complete one, add an
/// IncompleteTransaction to the list
/// </summary>
/// <param name="entry">The entry to parse</param>
/// <param name="context">Parsing context that may contain useful information</param>
/// <param name="transactions">List of parsed transactions</param>
public void Parse(Entry entry, TransactionParserContext context, TransactionList transactions);
}
/// <summary>
/// The location parser only updates the context with useful information, and does not
/// by itself generate any transactions. Location is the best information gatherer here
/// as we are getting controlling faction, system factions, address and station name.
/// </summary>
internal class LocationParser : TransactionParserPart {
public void Parse(Entry e, TransactionParserContext context, TransactionList transactions) {
LocationEntry? entry = e as LocationEntry;
if (entry == null) {
throw new NotImplementedException();
}
if (entry.StarSystem == null) {
throw new InvalidJournalEntryException();
}
context.CurrentSystem = entry.StarSystem;
context.CurrentSystemAddress = entry.SystemAddress;
context.SystemsByID.TryAdd(entry.SystemAddress, entry.StarSystem);
if (!string.IsNullOrEmpty(entry.SystemFaction)) {
context.ControllingFaction = entry.SystemFaction;
}
if (!string.IsNullOrEmpty(entry.StationName)) {
context.CurrentStation = entry.StationName;
}
if (!context.SystemFactions.ContainsKey(entry.StarSystem) &&
entry.SystemFactions != null && entry.SystemFactions.Count > 0) {
context.SystemFactions[entry.StarSystem] = entry.SystemFactions;
}
}
}
internal class FSDJumpParser : TransactionParserPart {
public void Parse(Entry e, TransactionParserContext context, TransactionList transactions) {
FSDJumpEntry? entry = e as FSDJumpEntry;
if (entry == null) {
throw new NotImplementedException();
}
if (entry.StarSystem == null) {
throw new InvalidJournalEntryException();
}
context.CurrentSystem = entry.StarSystem;
context.CurrentSystemAddress = entry.SystemAddress;
context.SystemsByID.TryAdd(entry.SystemAddress, entry.StarSystem);
if (!string.IsNullOrEmpty(entry.SystemFaction)) {
context.ControllingFaction = entry.SystemFaction;
}
if (!context.SystemFactions.ContainsKey(entry.StarSystem) &&
entry.SystemFactions != null && entry.SystemFactions.Count > 0) {
context.SystemFactions[entry.StarSystem] = entry.SystemFactions;
}
}
}
internal class DockedParser : TransactionParserPart {
public void Parse(Entry e, TransactionParserContext context, TransactionList transactions) {
DockedEntry? entry = e as DockedEntry;
if (entry == null) {
throw new NotImplementedException();
}
if (entry.StarSystem == null || entry.SystemAddress == null) {
throw new InvalidJournalEntryException();
}
context.CurrentSystem = entry.StarSystem;
context.CurrentSystemAddress = entry.SystemAddress;
context.SystemsByID.TryAdd(entry.SystemAddress.Value, entry.StarSystem);
if (!string.IsNullOrEmpty(entry.StationFaction)) {
context.ControllingFaction = entry.StationFaction;
}
if (!string.IsNullOrEmpty(entry.StationName)) {
context.CurrentStation = entry.StationName;
}
}
}
/// <summary>
/// With ship targeted we might find out to which faction a given NPC belonged. This is
/// useful later when said NPC gets killed or murdered.
/// </summary>
internal class ShipTargetedParser : TransactionParserPart {
public void Parse(Entry e, TransactionParserContext context, TransactionList transactions) {
ShipTargetedEntry? entry = e as ShipTargetedEntry;
if (entry == null) {
throw new NotImplementedException();
}
// Scan happens in stages, and sometimes this information is not known
// yet. Do now throw an error, this is expected behaviour.
if (!string.IsNullOrEmpty(entry.PilotNameLocalised) &&
!string.IsNullOrEmpty(entry.Faction)) {
context.NPCFaction.TryAdd(entry.PilotNameLocalised, entry.Faction);
}
}
}
/// <summary>
/// Commit crime can result in a transaction, especially if the crime committed is
/// murder.
/// </summary>
internal class CommitCrimeParser : TransactionParserPart {
public void Parse(Entry e, TransactionParserContext context, TransactionList transactions) {
CommitCrimeEntry? entry = e as CommitCrimeEntry;
if (entry == null) {
throw new NotImplementedException();
}
// Right now we only care for murder
if (!entry.IsMurder) {
return;
}
string? victim = entry.Victim;
if (victim == null) {
victim = entry.VictimLocalised;
}
// If they were not properly scanned prior to the murder we do not have
// This information. But in the end the name of the NPC does not matter.
if (victim == null) {
victim = "Unknown";
}
if (!context.NPCFaction.ContainsKey(victim)) {
transactions.AddIncomplete(
new FoulMurder(),
"Crime victim was not properly scanned."
);
return;
}
string faction = context.NPCFaction[victim];
transactions.Add(new FoulMurder(entry) {
System = context.CurrentSystem,
Faction = faction,
});
}
}
internal class MissionAcceptedParser : TransactionParserPart {
public void Parse(Entry e, TransactionParserContext context, TransactionList transactions) {
MissionAcceptedEntry? entry = e as MissionAcceptedEntry;
if (entry == null) {
throw new NotImplementedException();
}
if (context.CurrentSystem == null || context.CurrentSystemAddress == null) {
transactions.AddIncomplete(new MissionCompleted(),
"Could not determine current location on mission acceptance."
);
return;
}
try {
context.MissionAccepted(entry);
} catch (Exception exception) {
transactions.AddIncomplete(new MissionCompleted(),
exception.Message
);
}
}
}
internal class MissionCompletedParser : TransactionParserPart {
public void Parse(Entry e, TransactionParserContext context, TransactionList transactions) {
MissionCompletedEntry? entry = e as MissionCompletedEntry;
if (entry == null) {
throw new NotImplementedException();
}
if (entry.MissionID == null) {
throw new InvalidJournalEntryException("mission completed has no mission ID");
}
MissionAcceptedEntry? accepted = null;
Location? accepted_location = null;
string? target_faction_name = entry.TargetFaction;
string? source_faction_name = entry.Faction;
// We did not find when the mission was accepted.
if (!context.AcceptedMissions.TryGetValue(entry.MissionID.Value, out accepted)) {
transactions.AddIncomplete(new MissionCompleted(),
String.Format("Mission acceptance for mission id {0} was not found",
entry.MissionID.Value));
return;
}
if (!context.AcceptedMissionLocation.TryGetValue(entry.MissionID.Value, out accepted_location)) {
transactions.AddIncomplete(new MissionCompleted(),
String.Format("Location for acceptance for mission id {0} was not found",
entry.MissionID.Value));
return;
}
// This block does some preliminary "repairs" on the influences block of a completed
// mission. Sometimes these entries are broken, or are missing information for later
// parsing.
foreach (var other in entry.Influences) {
string faction = other.Key;
if (string.IsNullOrEmpty(faction)) {
// Target faction might be empty string, in special cases. For example if you
// scan a surface installation, and the target faction of the surface installation
// gets negative REP, but the surface installation is not owned by anyone.
continue;
}
// Fun ahead: sometimes the influence list is empty for a faction entry. Here
// we try to repair it.
if (other.Value.Count == 0) {
if (string.Compare(target_faction_name, faction, true) == 0) {
if (context.CurrentSystemAddress == null) {
continue;
}
other.Value.Add(context.CurrentSystemAddress.Value, "");
// Mission gave no influence to the target faction, so we assume
// the target faction was in the same system.
} else if (string.Compare(source_faction_name, faction, true) == 0) {
// This happens if the source faction is not getting any influence
// This could be if the source faction is in a conflict, and thus does
// not gain any influence at all.
other.Value.Add(accepted_location.SystemAddress, "");
// Just check if the target/source faction are the same, in which case
// we also have to make an additional entry
if (string.Compare(source_faction_name, target_faction_name, true) == 0 &&
context.CurrentSystemAddress != null) {
other.Value.Add(context.CurrentSystemAddress.Value, "");
}
}
}
// Now actually parse completed mission
foreach (var influences in other.Value) {
ulong system_address = influences.Key;
string? system;
if (!context.SystemsByID.TryGetValue(system_address, out system)) {
transactions.AddIncomplete(new MissionCompleted(),
string.Format("Unknown system {0}, unable to assign that mission a target", system_address)
);
continue;
}
if (string.Compare(faction, source_faction_name, true) == 0 &&
system_address == accepted_location.SystemAddress) {
// Source and target faction are the same, and this is the block
// for the source system. So we make a full mission completed entry.
transactions.Add(new MissionCompleted(entry) {
System = accepted_location.StarSystem,
Faction = source_faction_name,
SystemAddress = accepted_location.SystemAddress,
Station = accepted_location.Station,
});
} else if (string.Compare(faction, source_faction_name, true) != 0 ||
(string.Compare(faction, source_faction_name) == 0 &&
system_address != accepted_location.SystemAddress)) {
// Source or target faction are different, and/or the system
// differs. Sometimes missions go to different systems but to
// the same faction.
transactions.Add(new InfluenceSupport() {
Faction = faction,
Influence = influences.Value,
System = system,
SystemAddress = system_address,
RelevantMission = entry,
});
}
}
}
}
}
internal class MissionFailedParser : TransactionParserPart {
public void Parse(Entry e, TransactionParserContext context, TransactionList transactions) {
MissionAcceptedEntry? accepted = null;
Location? accepted_location = null;
string? accepted_system = null;
MissionFailedEntry? entry = e as MissionFailedEntry;
if (entry == null) {
throw new NotImplementedException();
}
if (!context.AcceptedMissions.TryGetValue(entry.MissionID, out accepted)) {
transactions.AddIncomplete(new MissionFailed(),
"Mission acceptance was not found"
);
return;
}
if (!context.AcceptedMissionLocation.TryGetValue(entry.MissionID, out accepted_location)) {
transactions.AddIncomplete(new MissionFailed(),
"Unable to figure out where failed mission was accepted"
);
return;
}
if (!context.SystemsByID.TryGetValue(accepted_location.SystemAddress, out accepted_system)) {
transactions.AddIncomplete(new MissionFailed(),
"Unable to figure out in which system failed mission was accepted"
);
return;
}
transactions.Add(new MissionFailed() {
Accepted = accepted,
Faction = accepted.Faction,
Failed = entry,
Station = accepted_location.Station,
System = accepted_location.StarSystem,
SystemAddress = accepted_location.SystemAddress,
});
}
}
internal class SellExplorationDataParser : TransactionParserPart {
public void Parse(Entry e, TransactionParserContext context, TransactionList transactions) {
SellExplorationDataEntry? entry = e as SellExplorationDataEntry;
if (entry == null) {
throw new NotImplementedException();
}
transactions.Add(new Cartographics(entry) {
System = context.CurrentSystem,
Station = context.CurrentStation,
Faction = context.ControllingFaction,
});
}
}
internal class SellOrganicDataParser : TransactionParserPart {
public void Parse(Entry e, TransactionParserContext context, TransactionList transactions) {
SellOrganicDataEntry? entry = e as SellOrganicDataEntry;
if (entry == null) {
throw new NotImplementedException();
}
transactions.Add(new OrganicData(entry) {
System = context.CurrentSystem,
Station = context.CurrentStation,
Faction = context.ControllingFaction,
});
}
}
internal class MultiSellExplorationDataParser : TransactionParserPart {
public void Parse(Entry e, TransactionParserContext context, TransactionList transactions) {
MultiSellExplorationDataEntry? entry = e as MultiSellExplorationDataEntry;
if (entry == null) {
throw new NotImplementedException();
}
transactions.Add(new Cartographics(entry) {
System = context.CurrentSystem,
Station = context.CurrentStation,
Faction = context.ControllingFaction,
});
}
}
internal class RedeemVoucherParser : TransactionParserPart {
public void Parse(Entry e, TransactionParserContext context, TransactionList transactions) {
RedeemVoucherEntry? entry = e as RedeemVoucherEntry;
if (entry == null) {
throw new NotImplementedException();
}
if (context.CurrentSystem == null) {
transactions.AddIncomplete(new Vouchers(),
"Could not find out where the vouchers were redeemed"
);
return;
}
List<Faction>? current_factions = context.GetFactions(context.CurrentSystem);
if (current_factions == null) {
transactions.AddIncomplete(new Vouchers(),
"Current system factions are unknown, so vouchers were ineffective");
return;
}
foreach (string faction in entry.Factions) {
if (current_factions.Find(x => string.Compare(x.Name, faction, true) == 0) == null) {
transactions.AddIncomplete(new Vouchers(),
string.Format("Vouchers for {0} were ignored in {1} since said " +
"faction is not present here", faction, context.CurrentSystem)
);
continue;
}
transactions.Add(new Vouchers(entry) {
System = context.CurrentSystem,
Station = context.CurrentStation,
Faction = faction,
ControllingFaction = context.ControllingFaction,
});
}
}
}
internal class SellMicroResourcesParser : TransactionParserPart {
public void Parse(Entry e, TransactionParserContext context, TransactionList transactions) {
SellMicroResourcesEntry? entry = e as SellMicroResourcesEntry;
if (entry == null) {
throw new NotImplementedException();
}
transactions.Add(new SellMicroResources(entry) {
System = context.CurrentSystem,
Station = context.CurrentStation,
Faction = context.ControllingFaction,
});
}
}
internal class SearchAndRescueParser : TransactionParserPart {
public void Parse(Entry e, TransactionParserContext context, TransactionList transactions) {
SearchAndRescueEntry? entry = e as SearchAndRescueEntry;
if (entry == null) {
throw new NotImplementedException();
}
transactions.Add(new SearchAndRescue(entry) {
Faction = context.ControllingFaction,
Station = context.CurrentStation,
System = context.CurrentSystem,
});
}
}
internal class MarketBuyParser : TransactionParserPart {
public void Parse(Entry e, TransactionParserContext context, TransactionList transactions) {
MarketBuyEntry? entry = e as MarketBuyEntry;
if (entry == null) {
throw new NotImplementedException();
}
context.BoughtCargo(entry.Type, entry.BuyPrice);
transactions.Add(new BuyCargo(entry) {
Faction = context.ControllingFaction,
Station = context.CurrentStation,
System = context.CurrentSystem,
});
}
}
internal class MarketSellParser : TransactionParserPart {
public void Parse(Entry e, TransactionParserContext context, TransactionList transactions) {
long profit = 0;
MarketSellEntry? entry = e as MarketSellEntry;
if (entry == null) {
throw new NotImplementedException();
}
if (entry.Type == null) {
throw new InvalidJournalEntryException("market sell contains no cargo type");
}
if (context.BuyCost.ContainsKey(entry.Type)) {
long avg = context.BuyCost[entry.Type];
profit = (long)entry.TotalSale - (avg * entry.Count);
}
transactions.Add(new SellCargo(entry) {
Faction = context.ControllingFaction,
Station = context.CurrentStation,
System = context.CurrentSystem,
Profit = profit,
});
}
}
public class TransactionParser {
private static Dictionary<string, TransactionParserPart> ParserParts { get; } = new()
{
{ Events.CommitCrime, new CommitCrimeParser() },
{ Events.Docked, new DockedParser() },
{ Events.FSDJump, new FSDJumpParser() },
{ Events.Location, new LocationParser() },
{ Events.MarketBuy, new MarketBuyParser() },
{ Events.MarketSell, new MarketSellParser() },
{ Events.MissionAccepted, new MissionAcceptedParser() },
{ Events.MissionCompleted, new MissionCompletedParser() },
{ Events.MissionFailed, new MissionFailedParser() },
{ Events.MultiSellExplorationData, new MultiSellExplorationDataParser() },
{ Events.RedeemVoucher, new RedeemVoucherParser() },
{ Events.SearchAndRescue, new SearchAndRescueParser() },
{ Events.SellExplorationData, new SellExplorationDataParser() },
{ Events.SellMicroResources, new SellMicroResourcesParser() },
{ Events.SellOrganicData, new SellOrganicDataParser() },
{ Events.ShipTargeted, new ShipTargetedParser() },
};
public List<Transaction>? Parse(IEnumerable<Entry> entries) {
TransactionList transactions = new();
TransactionParserContext context = new();
foreach (Entry entry in entries) {
if (entry.Event == null) {
throw new InvalidJournalEntryException();
}
if (!ParserParts.ContainsKey(entry.Event)) {
continue;
}
TransactionParserPart transactionParserPart = ParserParts[entry.Event];
transactionParserPart.Parse(entry, context, transactions);
}
return transactions.ToList();
}
}

View File

@@ -0,0 +1,74 @@
using System.Globalization;
using EDPlayerJournal.Entries;
namespace EDPlayerJournal.BGS;
public class Vouchers : Transaction {
private string? type = null;
public Vouchers() {
}
public Vouchers(RedeemVoucherEntry e) {
Entries.Add(e);
}
public long TotalSum {
get {
if (Faction == null) {
return 0;
}
return Entries
.OfType<RedeemVoucherEntry>()
.Where(x => x.FactionBounties.ContainsKey(Faction))
.Sum(x => x.FactionBounties[Faction])
;
}
}
public string? Type {
get {
if (Entries == null) {
return null;
}
if (type == null) {
string? v = Entries
.OfType<RedeemVoucherEntry>()
.GroupBy(x => x.Type)
.Select(x => x.Key)
.First();
if (v == null) {
return null;
} else if (v == "CombatBond") {
type = "Combat Bond";
} else if (v == "bounty") {
type = "Bounty";
} else {
type = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(v);
}
}
return type;
}
}
public override int CompareTo(Transaction? other) {
if (other == null || other.GetType() != typeof(Vouchers)) {
return -1;
}
Vouchers? b = other as Vouchers;
if (b?.Type == Type &&
b?.Faction == Faction &&
b?.System == System &&
b?.Station == Station) {
return 0;
}
return -1;
}
public override string ToString() {
return string.Format("{0} Vouchers: {1}", Type, Credits.FormatCredits(TotalSum));
}
}