Code Cleanup: Assemblies

This commit is contained in:
Rick Falkvinge
2014-12-04 23:55:03 +01:00
parent 93abb92c67
commit fa3b05da6f
458 changed files with 13969 additions and 13709 deletions
+1 -8
View File
@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Mail;
using System.Web;
using Swarmops.Logic.Structure;
using Swarmops.Logic.Swarm;
namespace Swarmops.Utility.BotCode
{
@@ -94,7 +88,6 @@ namespace Swarmops.Utility.BotCode
}
}
} */
}
}
}
}
+54 -51
View File
@@ -8,81 +8,81 @@ namespace Swarmops.Utility.BotCode
{
public class BallotComposer
{
private Dictionary<int, bool> defectionsLookup;
private Dictionary<int, MeetingElectionCandidates> geographicLists;
private MeetingElectionCandidates rawElectionResult;
/// <summary>
/// Minimum fraction of either gender. Can be in the range 0.0 -- 0.5.
/// Minimum fraction of either gender. Can be in the range 0.0 -- 0.5.
/// </summary>
public double GenderQuota { get; set; }
/// <summary>
/// Sets the output from the election count, i.e. the Schulze output.
/// Sets the output from the election count, i.e. the Schulze output.
/// </summary>
public MeetingElectionCandidates RawElectionResult
{
set
{
rawElectionResult = value;
geographicLists = new Dictionary<int, MeetingElectionCandidates>();
this.rawElectionResult = value;
this.geographicLists = new Dictionary<int, MeetingElectionCandidates>();
}
}
private MeetingElectionCandidates rawElectionResult;
/// <summary>
/// Sets the geographies for which to construct ballots.
/// Sets the geographies for which to construct ballots.
/// </summary>
public Geographies BallotGeographies { set; get; }
/// <summary>
/// Gets the final result.
/// Gets the final result.
/// </summary>
public Dictionary<int, MeetingElectionCandidates> FinalBallots { get; private set; }
private Dictionary<int, MeetingElectionCandidates> geographicLists;
public MeetingElectionCandidates QuotedMasterList { get; private set; }
private Dictionary<int, bool> defectionsLookup;
public int[] DefectedPersonIds
{
set
{
defectionsLookup = new Dictionary<int, bool>();
this.defectionsLookup = new Dictionary<int, bool>();
foreach (int defectedPersonId in value)
{
defectionsLookup[defectedPersonId] = true;
this.defectionsLookup[defectedPersonId] = true;
}
}
}
public void ComposeBallots(BallotCompositionMethod method)
{
FinalBallots = new Dictionary<int, MeetingElectionCandidates>();
QuotedMasterList = GenerateBallot(rawElectionResult, -1, BallotCompositionMethod.Unmixed);
if (geographicLists.Count == 0)
QuotedMasterList = GenerateBallot(this.rawElectionResult, -1, BallotCompositionMethod.Unmixed);
if (this.geographicLists.Count == 0)
{
GenerateGeographicLists();
}
foreach (Geography ballotGeography in BallotGeographies)
{
FinalBallots[ballotGeography.Identity] = GenerateBallot(geographicLists[ballotGeography.Identity], 22,
method);
FinalBallots[ballotGeography.Identity] = GenerateBallot(this.geographicLists[ballotGeography.Identity],
22,
method);
}
}
public bool CandidatePersonIdDefected (int personId)
public bool CandidatePersonIdDefected(int personId)
{
return defectionsLookup.ContainsKey(personId);
return this.defectionsLookup.ContainsKey(personId);
}
private void GenerateGeographicLists()
{
foreach (MeetingElectionCandidate candidate in rawElectionResult)
foreach (MeetingElectionCandidate candidate in this.rawElectionResult)
{
foreach (Geography ballotGeography in BallotGeographies)
{
@@ -90,20 +90,20 @@ namespace Swarmops.Utility.BotCode
{
// This candidate is under this particular geography, so add to list
if (!geographicLists.ContainsKey(ballotGeography.Identity))
if (!this.geographicLists.ContainsKey(ballotGeography.Identity))
{
geographicLists[ballotGeography.Identity] = new MeetingElectionCandidates();
this.geographicLists[ballotGeography.Identity] = new MeetingElectionCandidates();
}
geographicLists[ballotGeography.Identity].Add(candidate);
this.geographicLists[ballotGeography.Identity].Add(candidate);
}
}
}
}
private MeetingElectionCandidates GenerateBallot (MeetingElectionCandidates rawList, int candidateCount, BallotCompositionMethod method)
private MeetingElectionCandidates GenerateBallot(MeetingElectionCandidates rawList, int candidateCount,
BallotCompositionMethod method)
{
MeetingElectionCandidates result = new MeetingElectionCandidates();
Dictionary<int, bool> takenCandidates = new Dictionary<int, bool>();
@@ -117,7 +117,7 @@ namespace Swarmops.Utility.BotCode
for (int rawIndex = 0; rawIndex < rawList.Count; rawIndex++)
{
if (this.CandidatePersonIdDefected(rawList [rawIndex].PersonId))
if (CandidatePersonIdDefected(rawList[rawIndex].PersonId))
{
takenCandidates[rawIndex] = true;
}
@@ -136,15 +136,15 @@ namespace Swarmops.Utility.BotCode
//
// Should we add a candidate from the raw list or from the quoted master list?
int masterPosition = GetMasterListPosition (result.Count + 1, method);
int masterPosition = GetMasterListPosition(result.Count + 1, method);
if (masterPosition > 0)
{
// We should add a candidate from the master list, no quota calculations, BUT ONLY if this candidate
// hasn't already been added from the district list.
int rawListIndex = FindCandidateIndex (QuotedMasterList[masterPosition - 1].InternalPollCandidateId,
rawList);
int rawListIndex = FindCandidateIndex(QuotedMasterList[masterPosition - 1].InternalPollCandidateId,
rawList);
if (rawListIndex >= 0 && !takenCandidates.ContainsKey(rawListIndex))
{
@@ -188,8 +188,8 @@ namespace Swarmops.Utility.BotCode
// fall outside of bounds (33% or 66%). If so, ignore the quota if it is not obtainable.
PersonGender oppositeGender = (candidateGender == PersonGender.Male
? PersonGender.Female
: PersonGender.Male);
? PersonGender.Female
: PersonGender.Male);
double alternateMaleQuota = CalculateListMaleQuota(result, oppositeGender);
@@ -214,18 +214,17 @@ namespace Swarmops.Utility.BotCode
result.Add(rawList[nextCandidateIndex]);
takenCandidates[nextCandidateIndex] = true;
}
return result;
}
private static int FindCandidateIndex (int candidateId, MeetingElectionCandidates list)
private static int FindCandidateIndex(int candidateId, MeetingElectionCandidates list)
{
for (int index = 0; index < list.Count; index++)
{
if (list [index].Identity == candidateId)
if (list[index].Identity == candidateId)
{
return index;
}
@@ -233,9 +232,10 @@ namespace Swarmops.Utility.BotCode
return -1;
}
private static double CalculateListMaleQuota (MeetingElectionCandidates candidates, PersonGender nextCandidateGender)
private static double CalculateListMaleQuota(MeetingElectionCandidates candidates,
PersonGender nextCandidateGender)
{
if (candidates.Count < 1)
{
@@ -261,26 +261,26 @@ namespace Swarmops.Utility.BotCode
}
private static int GetNextSpecificGenderCandidate (MeetingElectionCandidates candidates,
Dictionary<int,bool> takenCandidates, PersonGender desiredGender)
private static int GetNextSpecificGenderCandidate(MeetingElectionCandidates candidates,
Dictionary<int, bool> takenCandidates, PersonGender desiredGender)
{
int index = 0;
while (takenCandidates.ContainsKey(index) || candidates [index].Person.Gender != desiredGender)
while (takenCandidates.ContainsKey(index) || candidates[index].Person.Gender != desiredGender)
{
index++; // potential out-of-range exception here, if there aren't enough candidates
index++; // potential out-of-range exception here, if there aren't enough candidates
}
return index;
}
/// <summary>
/// Gets the position of the master list to use for this position on the local list.
/// Gets the position of the master list to use for this position on the local list.
/// </summary>
/// <param name="currentPosition">The position of a particular ballot.</param>
/// <param name="method">The composition method to use.</param>
/// <returns>The position to pick from the master list, or zero if not from the master list.</returns>
private int GetMasterListPosition (int currentPosition, BallotCompositionMethod method)
private int GetMasterListPosition(int currentPosition, BallotCompositionMethod method)
{
if (method == BallotCompositionMethod.Unmixed)
{
@@ -309,7 +309,7 @@ namespace Swarmops.Utility.BotCode
if (method == BallotCompositionMethod.InterleavedTenNational)
{
if ((currentPosition % 2 == 1) && currentPosition < 20)
if ((currentPosition%2 == 1) && currentPosition < 20)
{
return (currentPosition/2 + 1);
}
@@ -319,30 +319,33 @@ namespace Swarmops.Utility.BotCode
throw new NotImplementedException("Unimplemented method");
}
}
public enum BallotCompositionMethod
{
/// <summary>
/// FxCop directive - unused
/// FxCop directive - unused
/// </summary>
Unknown = 0,
/// <summary>
/// The national top ten names are the top ten on all geographic ballots.
/// The national top ten names are the top ten on all geographic ballots.
/// </summary>
TopTenNational,
/// <summary>
/// The national top five names are the top ten on all geographic ballots.
/// The national top five names are the top ten on all geographic ballots.
/// </summary>
TopFiveNational,
/// <summary>
/// Odd positions 1..19 are the national top ten names on all geographic ballots.
/// Odd positions 1..19 are the national top ten names on all geographic ballots.
/// </summary>
InterleavedTenNational,
/// <summary>
/// No top national names; only names from this district.
/// No top national names; only names from this district.
/// </summary>
Unmixed
}
}
}
+1 -1
View File
@@ -25,7 +25,7 @@ namespace Swarmops.Utility.BotCode
{
string scrapeData = string.Empty;
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create("http://knuff.se/topp50/knuffpoaeng/");
HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://knuff.se/topp50/knuffpoaeng/");
request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9b5) Gecko/2008050509 Firefox/3.0b5";
using (Stream stream = request.GetResponse().GetResponseStream())
+13 -12
View File
@@ -7,14 +7,7 @@ namespace Swarmops.Utility.BotCode
{
public class BlogWatcher
{
public class ReaderException : Exception
{
public ReaderException (string message, Exception innerException)
: base(message, innerException)
{ }
}
public static void Run ()
public static void Run()
{
// Get keywords. Read Knuff. Parse. Store.
@@ -26,9 +19,9 @@ namespace Swarmops.Utility.BotCode
// Read the RSS URL into memory, then feed RssReader from a MemoryStream
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(rssUrl);
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(rssUrl);
request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9b5) Gecko/2008050509 Firefox/3.0b5";
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
HttpWebResponse resp = (HttpWebResponse) request.GetResponse();
RssReader reader = new RssReader(resp.GetResponseStream());
try
@@ -79,13 +72,21 @@ namespace Swarmops.Utility.BotCode
}
}
private static void PingCreeper (string referringUrl)
private static void PingCreeper(string referringUrl)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://gnuheter.com/creeper/image");
HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://gnuheter.com/creeper/image");
request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9b5) Gecko/2008050509 Firefox/3.0b5";
request.Referer = referringUrl;
request.GetResponse().GetResponseStream().Close();
}
public class ReaderException : Exception
{
public ReaderException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
}
+3 -3
View File
@@ -6,7 +6,7 @@ namespace Swarmops.Utility.BotCode
{
public class BotLog
{
static public void Write (int generation, string code, string message)
public static void Write(int generation, string code, string message)
{
string line = string.Empty;
@@ -27,7 +27,7 @@ namespace Swarmops.Utility.BotCode
LogWrite(line);
}
static private void LogWrite (string message)
private static void LogWrite(string message)
{
DateTime now = DateTime.Now;
@@ -40,4 +40,4 @@ namespace Swarmops.Utility.BotCode
}
}
}
}
}
+5 -24
View File
@@ -1,21 +1,5 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net.Mail;
using System.Text;
using Swarmops.Basic;
using Swarmops.Basic.Enums;
using Swarmops.Basic.Types;
using Swarmops.Logic.Communications;
using Swarmops.Logic.Financial;
using Swarmops.Logic.Governance;
using Swarmops.Logic.Security;
using Swarmops.Logic.Special.Mail;
using Swarmops.Logic.Structure;
using Swarmops.Logic.Support;
using Swarmops.Logic.Swarm;
using Swarmops.Utility.Financial;
using Swarmops.Utility.Mail;
using System.IO;
namespace Swarmops.Utility.BotCode
{
@@ -24,7 +8,7 @@ namespace Swarmops.Utility.BotCode
// This entire class could use a tune-up. More event types will come, too.
[Obsolete("Deprecated for Swarmops. Way too much hardcoded. Rewrite, generalize, or scrap.", true)]
public static void Run ()
public static void Run()
{
/*
BasicPWEvent[] events = PWEvents.GetTopUnprocessedEvents();
@@ -207,16 +191,13 @@ namespace Swarmops.Utility.BotCode
}
internal static bool RunningOnLinux ()
internal static bool RunningOnLinux()
{
if (System.IO.Path.DirectorySeparatorChar == '/')
if (Path.DirectorySeparatorChar == '/')
{
return true;
}
else
{
return false;
}
return false;
}
/*
+39 -40
View File
@@ -1,33 +1,55 @@
using System;
using System.IO;
using System.Text;
using Swarmops.Logic.Support;
namespace Swarmops.Utility.BotCode
{
public class HeartBeater
{
static private HeartBeater instance = null;
static private object lockObject = new object();
private static HeartBeater instance;
private static readonly object lockObject = new object();
private bool FlagRestartRequested = false;
private bool FlagRestartRequested;
private DateTime lastBeat = DateTime.MinValue;
private string lastFilename = "";
public void Beat ()
public bool WasKilled
{
Beat(lastFilename);
get { return this.FlagRestartRequested; }
}
public void Beat (string filename)
public static HeartBeater Instance
{
get
{
if (instance == null)
{
lock (lockObject)
{
if (instance == null)
instance = new HeartBeater();
}
}
return instance;
}
}
public void Beat()
{
Beat(this.lastFilename);
}
public void Beat(string filename)
{
lock (lockObject)
{
lastFilename = filename;
this.lastFilename = filename;
}
if ((DateTime.Now.Subtract(lastBeat).TotalSeconds > 10)
&& (this.FlagRestartRequested == false))
if ((DateTime.Now.Subtract(this.lastBeat).TotalSeconds > 10)
&& (this.FlagRestartRequested == false))
{
try
{
@@ -41,55 +63,32 @@ namespace Swarmops.Utility.BotCode
}
else
{
this.SuggestRestart();
SuggestRestart();
throw new Exception("Failed to update HeartBeat");
}
}
catch (Exception e)
{
this.SuggestRestart();
SuggestRestart();
throw new Exception("Failed to update HeartBeat", e);
}
}
}
public void SuggestRestart ()
public void SuggestRestart()
{
if (!File.Exists("./piratebotexit.flag"))
File.Create("./piratebotexit.flag");
this.FlagRestartRequested = true;
}
public bool WasKilled
public static void writeFile(string sPath, string content)
{
get { return (this.FlagRestartRequested == true); }
}
public static HeartBeater Instance
{
get
{
if (instance == null)
{
lock (lockObject)
{
if (instance == null)
instance = new HeartBeater();
}
}
return instance;
}
}
static public void writeFile (string sPath, string content)
{
StreamWriter writeStream = new StreamWriter(new FileStream(sPath, FileMode.Create, FileAccess.ReadWrite), System.Text.Encoding.Default);
StreamWriter writeStream = new StreamWriter(new FileStream(sPath, FileMode.Create, FileAccess.ReadWrite),
Encoding.Default);
writeStream.Write(content);
writeStream.Close();
}
}
}
}
+73 -75
View File
@@ -8,13 +8,13 @@ namespace Swarmops.Utility.BotCode
{
public class InternalPollMaintenance
{
static public void Run()
public static void Run()
{
MeetingElections polls = MeetingElections.GetAll();
foreach (MeetingElection poll in polls)
{
Console.Write("Looking at poll #" + poll.Identity.ToString() + "...");
Console.Write("Looking at poll #" + poll.Identity + "...");
if (DateTime.Now > poll.VotingCloses)
{
@@ -28,7 +28,8 @@ namespace Swarmops.Utility.BotCode
poll.VotingOpen = false; // Closes poll
poll.Creator.SendNotice("Poll Closed: " + poll.Name, string.Empty, poll.OrganizationId);
Person.FromIdentity(1).SendNotice("Poll Closed: " + poll.Name, string.Empty, poll.OrganizationId);
Person.FromIdentity(1)
.SendNotice("Poll Closed: " + poll.Name, string.Empty, poll.OrganizationId);
ReportPollResults(poll, false);
}
@@ -41,89 +42,86 @@ namespace Swarmops.Utility.BotCode
{
try
{
// Poll should be OPEN.
Console.Write("after opendatetime " + poll.VotingOpens.ToString("yyyy-MM-dd HH:mm") + "...");
// Poll should be OPEN.
Console.Write("after opendatetime " + poll.VotingOpens.ToString("yyyy-MM-dd HH:mm") + "...");
if (!poll.VotingOpen)
{
Console.WriteLine("OPENING for " + poll.Organization.Name + ":");
// Populate voters, then open for voting
Organizations orgTree = poll.Organization.GetTree();
Memberships memberships = Memberships.ForOrganizations(orgTree);
Dictionary<int, bool> dupeCheck = new Dictionary<int, bool>();
int count = 0;
foreach (Membership membership in memberships)
if (!poll.VotingOpen)
{
Console.Write("\r - voters: {0:D6}/{1:D6} (person #{2:D6})...", ++count, memberships.Count, membership.PersonId);
Console.WriteLine("OPENING for " + poll.Organization.Name + ":");
if (!membership.Active)
{
continue; // paranoid programming
}
// Populate voters, then open for voting
if (!membership.Organization.IsOrInherits(poll.Organization))
{
continue; // more paranoid programming
}
Organizations orgTree = poll.Organization.GetTree();
if (!dupeCheck.ContainsKey(membership.PersonId))
Memberships memberships = Memberships.ForOrganizations(orgTree);
Dictionary<int, bool> dupeCheck = new Dictionary<int, bool>();
int count = 0;
foreach (Membership membership in memberships)
{
if (membership.Person.GeographyId == 0)
Console.Write("\r - voters: {0:D6}/{1:D6} (person #{2:D6})...", ++count,
memberships.Count, membership.PersonId);
if (!membership.Active)
{
// It's a trap!
Console.Write(" GEOGRAPHY ZERO, ignoring\r\n");
continue; // paranoid programming
}
else
if (!membership.Organization.IsOrInherits(poll.Organization))
{
continue; // more paranoid programming
}
Geography geo = membership.Person.Geography;
if (geo.Inherits(poll.GeographyId) || geo.Identity == poll.GeographyId)
if (!dupeCheck.ContainsKey(membership.PersonId))
{
if (membership.Person.GeographyId == 0)
{
poll.AddVoter(membership.Person);
dupeCheck[membership.PersonId] = true;
// It's a trap!
Console.Write(" GEOGRAPHY ZERO, ignoring\r\n");
}
else
{
Geography geo = membership.Person.Geography;
if (geo.Inherits(poll.GeographyId) || geo.Identity == poll.GeographyId)
{
poll.AddVoter(membership.Person);
dupeCheck[membership.PersonId] = true;
}
}
}
}
Console.WriteLine(" done.");
Console.Write(" - opening poll...");
poll.VotingOpen = true;
Console.WriteLine(" done.");
Console.Write("Sending notices... ");
string body = "Electoral roll for poll \"" + poll.Name + "\" primed. " +
dupeCheck.Count + " people can vote. The vote is now OPEN.";
string subject = "Poll Open: " + poll.Name;
poll.Creator.SendNotice(subject, body, poll.OrganizationId);
Person.FromIdentity(1).SendNotice(subject, body, poll.OrganizationId);
Console.WriteLine(" done.");
}
else
{
Console.WriteLine(" already open, no action.");
Console.WriteLine(" done.");
Console.Write(" - opening poll...");
poll.VotingOpen = true;
Console.WriteLine(" done.");
Console.Write("Sending notices... ");
string body = "Electoral roll for poll \"" + poll.Name + "\" primed. " +
dupeCheck.Count.ToString() + " people can vote. The vote is now OPEN.";
string subject = "Poll Open: " + poll.Name;
poll.Creator.SendNotice(subject, body, poll.OrganizationId);
Person.FromIdentity(1).SendNotice (subject, body, poll.OrganizationId);
Console.WriteLine(" done.");
}
else
{
Console.WriteLine(" already open, no action.");
// Report intermediate results to owner
ReportPollResults(poll, true);
}
// Report intermediate results to owner
ReportPollResults(poll, true);
}
}
catch (Exception exception)
{
@@ -131,13 +129,12 @@ namespace Swarmops.Utility.BotCode
throw exception;
}
}
}
}
static private void ReportPollResults (MeetingElection poll, bool stillOpen)
private static void ReportPollResults(MeetingElection poll, bool stillOpen)
{
SchulzeProcessor processor = new SchulzeProcessor();
@@ -167,10 +164,13 @@ namespace Swarmops.Utility.BotCode
for (int candidateIndex = 0; candidateIndex < candidates.Count; candidateIndex++)
{
int distance = processor.GetCandidateDistance(candidateIndex);
body += String.Format("{0:D3}. {1} {2}{3}\r\n", candidateIndex + 1, (distance > 0 ? distance.ToString("D4") : "----"), candidates[candidateIndex].Person.Canonical, dropoutLookup.ContainsKey(candidates[candidateIndex].PersonId) ? " [hoppat av]" : string.Empty);
body += String.Format("{0:D3}. {1} {2}{3}\r\n", candidateIndex + 1,
(distance > 0 ? distance.ToString("D4") : "----"), candidates[candidateIndex].Person.Canonical,
dropoutLookup.ContainsKey(candidates[candidateIndex].PersonId) ? " [hoppat av]" : string.Empty);
}
int[] recipients = new int[] { 1 , poll.CreatedByPersonId }; // Send to Rick too while stabilizing functionality -- remove as soon as Rick is running in any poll
int[] recipients = {1, poll.CreatedByPersonId};
// Send to Rick too while stabilizing functionality -- remove as soon as Rick is running in any poll
string subject = (stillOpen ? "Intermediate" : "FINAL") + " results for poll - " + poll.Name;
@@ -179,8 +179,6 @@ namespace Swarmops.Utility.BotCode
Person.FromIdentity(personId).SendNotice(
subject, body, poll.OrganizationId);
}
}
}
}
}
+2 -3
View File
@@ -5,9 +5,8 @@ namespace Swarmops.Utility.BotCode
public class InternalPollRandomizer
{
// Randomizes the order of candidates on the open polls.
static public void Run()
public static void Run()
{
// TODO: Foreach open poll...
MeetingElectionCandidates candidates = MeetingElectionCandidates.ForPoll(MeetingElection.Primaries2010);
@@ -18,4 +17,4 @@ namespace Swarmops.Utility.BotCode
}
}
}
}
}
+210 -182
View File
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
@@ -19,54 +20,66 @@ namespace Swarmops.Utility.BotCode
public class MailProcessor
{
#region Exception declarations
public class RemoveRecipientException : Exception
{
public RemoveRecipientException (string message, Exception innerException)
: base(message, innerException)
{ }
}
public class IgnoreRecipientException : Exception
{
public IgnoreRecipientException (string message, Exception innerException)
public IgnoreRecipientException(string message, Exception innerException)
: base(message, innerException)
{ }
{
}
}
public class InvalidRecipientException : IgnoreRecipientException
{
public InvalidRecipientException (string message, Exception innerException)
public InvalidRecipientException(string message, Exception innerException)
: base(message, innerException)
{ }
}
public class RetryRecipientException : Exception
{
public RetryRecipientException (string message, Exception innerException)
: base(message, innerException)
{ }
}
public class ReportAndRetryRecipientException : RetryRecipientException
{
public ReportAndRetryRecipientException (string message, Exception innerException)
: base(message, innerException)
{ }
{
}
}
public class InvalidSenderException : Exception
{
public InvalidSenderException (string message, Exception innerException)
public InvalidSenderException(string message, Exception innerException)
: base(message, innerException)
{ }
{
}
}
public class RemoveRecipientException : Exception
{
public RemoveRecipientException(string message, Exception innerException)
: base(message, innerException)
{
}
}
public class ReportAndRetryRecipientException : RetryRecipientException
{
public ReportAndRetryRecipientException(string message, Exception innerException)
: base(message, innerException)
{
}
}
public class RetryRecipientException : Exception
{
public RetryRecipientException(string message, Exception innerException)
: base(message, innerException)
{
}
}
#endregion
static QuotedPrintable qpUTF8 = new QuotedPrintable(Encoding.UTF8);
static QuotedPrintable qp8859 = new QuotedPrintable(Encoding.GetEncoding("ISO-8859-1"));
static Dictionary<Encoding, QuotedPrintable> QuotedPrintableEncoder = InitQpDictionary();
private static readonly QuotedPrintable qpUTF8 = new QuotedPrintable(Encoding.UTF8);
private static readonly QuotedPrintable qp8859 = new QuotedPrintable(Encoding.GetEncoding("ISO-8859-1"));
private static readonly Dictionary<Encoding, QuotedPrintable> QuotedPrintableEncoder = InitQpDictionary();
private static int mailQueueSize;
private static readonly Object lockObject = new Object();
#region Static initialisation
static private Dictionary<Encoding, QuotedPrintable> InitQpDictionary ()
private static Dictionary<Encoding, QuotedPrintable> InitQpDictionary()
{
Dictionary<Encoding, QuotedPrintable> qp = new Dictionary<Encoding, QuotedPrintable>();
qp[Encoding.UTF8] = qpUTF8;
@@ -76,7 +89,7 @@ namespace Swarmops.Utility.BotCode
#endregion
public static void Run ()
public static void Run()
{
// If there is mail in the outbound mail queue, do not add more. (This is a primitive
// protection against dupes. Better will come that doesn't force idle time like this.)
@@ -103,7 +116,6 @@ namespace Swarmops.Utility.BotCode
foreach (OutboundMail mail in mails)
{
// If we have already processed past our limit, return for now.
if (maxBatchSize < 1)
{
@@ -118,8 +130,8 @@ namespace Swarmops.Utility.BotCode
// Yes! Mark it as started and mail our author.
mail.StartProcessDateTime = DateTime.Now;
if (mail.MailType == (int)TypedMailTemplate.TemplateType.MemberMail
|| mail.MailType == (int)TypedMailTemplate.TemplateType.OfficerMail) // TODO: Set special flag
if (mail.MailType == (int) TypedMailTemplate.TemplateType.MemberMail
|| mail.MailType == (int) TypedMailTemplate.TemplateType.OfficerMail) // TODO: Set special flag
{
string mailBody = string.Empty;
@@ -133,17 +145,17 @@ namespace Swarmops.Utility.BotCode
// If we are debugging, and stepping through this program, avoid the misery of many simultaneous threads.
if (System.Diagnostics.Debugger.IsAttached)
if (Debugger.IsAttached)
{
batchSize = 1; // Do NOT multithread while debugging
}
while (true)
{
if (!System.Diagnostics.Debugger.IsAttached)
if (!Debugger.IsAttached)
{
HeartBeater.Instance.Beat();
//Tick the heartbeat to stop exernal restart if this takes a lot of time, but only if not debugging.
//Tick the heartbeat to stop exernal restart if this takes a lot of time, but only if not debugging.
}
OutboundMailRecipients recipients = mail.GetNextRecipientBatch(batchSize);
@@ -156,16 +168,19 @@ namespace Swarmops.Utility.BotCode
mail.SetProcessed();
if (mail.MailType == (int)TypedMailTemplate.TemplateType.MemberMail
|| mail.MailType == (int)TypedMailTemplate.TemplateType.OfficerMail) // TODO: Set special flag
if (mail.MailType == (int) TypedMailTemplate.TemplateType.MemberMail
|| mail.MailType == (int) TypedMailTemplate.TemplateType.OfficerMail)
// TODO: Set special flag
{
string body = "Your mail has completed transmitting to " + mail.RecipientCount.ToString("#,##0") +
string body = "Your mail has completed transmitting to " +
mail.RecipientCount.ToString("#,##0") +
" intended recipients. Out of these, " + mail.RecipientsFail.ToString("#,##0") +
" failed because of invalid, empty, or otherwise bad e-mail addresses. These people have not received your message.\r\n";
new Mail.MailTransmitter(
new MailTransmitter(
Strings.MailSenderName, Strings.MailSenderAddress,
"Mail transmission completed: " + mail.Title, body, Person.FromIdentity(mail.AuthorPersonId),
"Mail transmission completed: " + mail.Title, body,
Person.FromIdentity(mail.AuthorPersonId),
true).Send();
}
@@ -176,165 +191,154 @@ namespace Swarmops.Utility.BotCode
break; //the while loop
}
else
List<IAsyncResult> sendInProgress = new List<IAsyncResult>();
List<WaitHandle> waitHandlesList = new List<WaitHandle>();
foreach (OutboundMailRecipient recipient in recipients)
{
List<IAsyncResult> sendInProgress = new List<IAsyncResult>();
List<WaitHandle> waitHandlesList = new List<WaitHandle>();
foreach (OutboundMailRecipient recipient in recipients)
// Skip known invalid mail addresses
if (recipient.Person != null
&& (recipient.Person.EMailIsInvalid || recipient.Person.MailUnreachable))
{
// Skip known invalid mail addresses
if (recipient.Person != null
&& (recipient.Person.EMailIsInvalid || recipient.Person.MailUnreachable))
{
lock (lockObject)
{
recipient.Delete();
recipient.OutboundMail.IncrementFailures();
}
continue;
}
// Start the transmission process, asynchronously
lock (lockObject)
{
MailTransmissionDelegate asyncTransmitter = new MailTransmissionDelegate(TransmitOneMail);
MailTransmissionAsyncState asyncState = new MailTransmissionAsyncState();
asyncState.dlgt = asyncTransmitter;
asyncState.recipient = recipient;
IAsyncResult asyncResult = asyncTransmitter.BeginInvoke(recipient, new AsyncCallback(MailSent), asyncState);
sendInProgress.Add(asyncResult);
waitHandlesList.Add(asyncResult.AsyncWaitHandle);
mailQueueSize++;
recipient.Delete();
recipient.OutboundMail.IncrementFailures();
}
System.Threading.Thread.Sleep(25); // Allow some time
continue;
}
// now wait for them to finish;
int numberStillExecuting = sendInProgress.Count;
int numberExecutingLast = numberStillExecuting + 1;
DateTime lastProgress = DateTime.Now;
// Start the transmission process, asynchronously
while (numberStillExecuting > 0)
lock (lockObject)
{
WaitHandle.WaitAny(waitHandlesList.ToArray(), 100, true);
lock (lockObject)
MailTransmissionDelegate asyncTransmitter = TransmitOneMail;
MailTransmissionAsyncState asyncState = new MailTransmissionAsyncState();
asyncState.dlgt = asyncTransmitter;
asyncState.recipient = recipient;
IAsyncResult asyncResult = asyncTransmitter.BeginInvoke(recipient, MailSent, asyncState);
sendInProgress.Add(asyncResult);
waitHandlesList.Add(asyncResult.AsyncWaitHandle);
mailQueueSize++;
}
Thread.Sleep(25); // Allow some time
}
// now wait for them to finish;
int numberStillExecuting = sendInProgress.Count;
int numberExecutingLast = numberStillExecuting + 1;
DateTime lastProgress = DateTime.Now;
while (numberStillExecuting > 0)
{
WaitHandle.WaitAny(waitHandlesList.ToArray(), 100, true);
lock (lockObject)
{
numberStillExecuting = 0;
waitHandlesList = new List<WaitHandle>();
for (int i = 0; i < sendInProgress.Count; ++i)
{
numberStillExecuting = 0;
waitHandlesList = new List<WaitHandle>();
IAsyncResult iares = sendInProgress[i];
MailTransmissionAsyncState asyncState = (MailTransmissionAsyncState) iares.AsyncState;
for (int i = 0; i < sendInProgress.Count; ++i)
if (asyncState.dlgt != null)
{
IAsyncResult iares = sendInProgress[i];
MailTransmissionAsyncState asyncState = (MailTransmissionAsyncState)iares.AsyncState;
if (asyncState.dlgt != null)
if (!asyncState.callbackCompleted)
{
if (!asyncState.callbackCompleted)
waitHandlesList.Add(iares.AsyncWaitHandle);
numberStillExecuting++;
}
else
{
//Just finalised
if (asyncState.exception != null)
{
waitHandlesList.Add(iares.AsyncWaitHandle);
numberStillExecuting++;
}
else
{
//Just finalised
if (asyncState.exception != null)
if (asyncState.exception is RetryRecipientException)
{
if (asyncState.exception is RetryRecipientException)
//Failed in sending due to some reason that can clear up by itself.
asyncState.dlgt = null;
}
else
{
//Make sure recipient is deleted
try
{
//Failed in sending due to some reason that can clear up by itself.
asyncState.dlgt = null;
asyncState.recipient.Delete();
// if RemoveRecipientException everything went ok except for the removal
if (asyncState.exception is RemoveRecipientException)
asyncState.recipient.OutboundMail.IncrementSuccesses();
asyncState.dlgt = null; // mark as done;
mailQueueSize--;
}
else
catch
{
//Make sure recipient is deleted
try
{
asyncState.recipient.Delete();
// if RemoveRecipientException everything went ok except for the removal
if (asyncState.exception is RemoveRecipientException)
asyncState.recipient.OutboundMail.IncrementSuccesses();
asyncState.dlgt = null; // mark as done;
mailQueueSize--;
}
catch
{ //Keep looping until recipient removed
numberStillExecuting++;
}
//Keep looping until recipient removed
numberStillExecuting++;
}
}
}
}
}
}
}
if (numberExecutingLast != numberStillExecuting)
lastProgress = DateTime.Now;
if (numberExecutingLast != numberStillExecuting)
lastProgress = DateTime.Now;
numberExecutingLast = numberStillExecuting;
numberExecutingLast = numberStillExecuting;
if (lastProgress.AddSeconds(60 * 2) < DateTime.Now)
if (lastProgress.AddSeconds(60*2) < DateTime.Now)
{
// since last change, something must have hanged
lock (lockObject)
{
// since last change, something must have hanged
lock (lockObject)
{
mailQueueSize = -1000;
}
throw new Exception("Timeout in MailProcessor");
mailQueueSize = -1000;
}
throw new Exception("Timeout in MailProcessor");
}
}
}
}
}
internal class MailTransmissionAsyncState
{
internal MailTransmissionDelegate dlgt = null;
internal Exception exception = null;
internal OutboundMailRecipient recipient = null;
internal bool callbackCompleted = false;
}
internal delegate OutboundMailRecipient MailTransmissionDelegate (OutboundMailRecipient recipient);
internal static OutboundMailRecipient TransmitOneMail (OutboundMailRecipient recipient)
internal static OutboundMailRecipient TransmitOneMail(OutboundMailRecipient recipient)
{
try
{
// If the mail address in illegal format, do not try to send anything:
if (!Formatting.ValidateEmailFormat(recipient.EmailPerson.Email.Trim()))
{
string msg = "Invalid email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity.ToString() + "], mail [" +
recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title;
string msg = "Invalid email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity +
"], mail [" +
recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title;
throw new InvalidRecipientException(msg, null);
}
// If the mail address is marked as unreachable, do not try to send anything
if (recipient.Person != null && recipient.Person.MailUnreachable)
{
string msg = "MailUnreachable email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity.ToString() + "], mail [" +
recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title;
string msg = "MailUnreachable email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity +
"], mail [" +
recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title;
throw new InvalidRecipientException(msg, null);
}
// If the mail address is marked as unreachable, do not try to send anything
if (recipient.Person != null && recipient.Person.NeverMail)
{
string msg = "NeverMail email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity.ToString() + "], mail [" +
recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title;
string msg = "NeverMail email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity +
"], mail [" +
recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title;
throw new IgnoreRecipientException(msg, null);
}
// Otherwise, let's start processing
OutboundMail mail = recipient.OutboundMail;
@@ -384,35 +388,39 @@ namespace Swarmops.Utility.BotCode
try
{
message.From = new MailAddress(mail.Author.PartyEmail,
qp.EncodeMailHeaderString(mail.Author.Name + " (" + mail.Organization.MailPrefixInherited + ")"),
currentEncoding);
qp.EncodeMailHeaderString(mail.Author.Name + " (" + mail.Organization.MailPrefixInherited +
")"),
currentEncoding);
if (mail.Author.Identity == 1)
{
//TODO: Create alternative party mail optional data field, or organization chairman (based on roles) differently
// Ugly hack
message.From = new MailAddress("rick.falkvinge@piratpartiet.se",
qp.EncodeMailHeaderString(mail.Author.Name + " (" + mail.Organization.MailPrefixInherited + ")"),
currentEncoding);
qp.EncodeMailHeaderString(mail.Author.Name + " (" +
mail.Organization.MailPrefixInherited + ")"),
currentEncoding);
}
}
catch (Exception ex)
{
throw new InvalidSenderException("Invalid author address in MailProcessor.TransmitOneMail:" + (mail.AuthorPersonId).ToString() + ";" + mail.Author.PartyEmail, ex);
throw new InvalidSenderException(
"Invalid author address in MailProcessor.TransmitOneMail:" + (mail.AuthorPersonId) + ";" +
mail.Author.PartyEmail, ex);
}
}
else
{
try
{
FunctionalMail.AddressItem aItem = mail.Organization.GetFunctionalMailAddressInh(mail.AuthorType);
message.From = new MailAddress(aItem.Email, qp.EncodeMailHeaderString(aItem.Name),
currentEncoding);
message.From = new MailAddress(aItem.Email, qp.EncodeMailHeaderString(aItem.Name),
currentEncoding);
}
catch (Exception ex)
{
throw new InvalidSenderException("Unknown MailAuthorType in MailProcessor.TransmitOneMail:" + ((int)mail.AuthorType).ToString(), ex);
throw new InvalidSenderException(
"Unknown MailAuthorType in MailProcessor.TransmitOneMail:" + ((int) mail.AuthorType), ex);
}
}
@@ -422,13 +430,16 @@ namespace Swarmops.Utility.BotCode
try
{
message.To.Add(new MailAddress(recipient.Person.PartyEmail,
qp.EncodeMailHeaderString(recipient.Person.Name + " (" + mail.Organization.MailPrefixInherited + ")"),
currentEncoding));
qp.EncodeMailHeaderString(recipient.Person.Name + " (" +
mail.Organization.MailPrefixInherited + ")"),
currentEncoding));
}
catch (FormatException e)
{
string msg = "Invalid officer email address:\r\nperson [" + recipient.Person.Identity.ToString() + "], mail [" +
recipient.Person.PartyEmail + "]\r\nwill not send mail:" + recipient.OutboundMail.Title;
string msg = "Invalid officer email address:\r\nperson [" + recipient.Person.Identity +
"], mail [" +
recipient.Person.PartyEmail + "]\r\nwill not send mail:" +
recipient.OutboundMail.Title;
throw new InvalidRecipientException(msg, e);
}
}
@@ -437,13 +448,15 @@ namespace Swarmops.Utility.BotCode
try
{
message.To.Add(new MailAddress(recipient.EmailPerson.Email,
qp.EncodeMailHeaderString(recipient.EmailPerson.Name),
currentEncoding));
qp.EncodeMailHeaderString(recipient.EmailPerson.Name),
currentEncoding));
}
catch (FormatException e)
{
string msg = "Invalid email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity.ToString() + "], mail [" +
recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title;
string msg = "Invalid email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity +
"], mail [" +
recipient.EmailPerson.Email + "]\r\nwill not send mail:" +
recipient.OutboundMail.Title;
throw new InvalidRecipientException(msg, e);
}
}
@@ -485,7 +498,9 @@ namespace Swarmops.Utility.BotCode
}
catch (Exception ex)
{
throw new RemoveRecipientException("TextRendering failed for " + mail.Title + " to " + recipient.EmailPerson.Email + " will not retry.\n", ex);
throw new RemoveRecipientException(
"TextRendering failed for " + mail.Title + " to " + recipient.EmailPerson.Email +
" will not retry.\n", ex);
}
}
message.BodyEncoding = currentEncoding;
@@ -512,9 +527,13 @@ namespace Swarmops.Utility.BotCode
}
}
if (text == "")
throw new RemoveRecipientException("Rendering (text) failed for " + mail.Title + " to " + recipient.EmailPerson.Email + " will not retry.\n", ex);
else if (html == "" || ex != null)
throw new RemoveRecipientException("Rendering (html) failed for " + mail.Title + " to " + recipient.EmailPerson.Email + " will not retry.\n", ex);
throw new RemoveRecipientException(
"Rendering (text) failed for " + mail.Title + " to " + recipient.EmailPerson.Email +
" will not retry.\n", ex);
if (html == "" || ex != null)
throw new RemoveRecipientException(
"Rendering (html) failed for " + mail.Title + " to " + recipient.EmailPerson.Email +
" will not retry.\n", ex);
ContentType textContentType = new ContentType(MediaTypeNames.Text.Plain);
textContentType.CharSet = currentEncoding.BodyName;
@@ -567,10 +586,10 @@ namespace Swarmops.Utility.BotCode
string smtpServer = ConfigurationManager.AppSettings["SmtpServer"];
if (System.Diagnostics.Debugger.IsAttached)
if (Debugger.IsAttached)
{
System.Diagnostics.Debug.WriteLine("sending " + message.Subject + " to " + recipient.EmailPerson.Email);
System.Threading.Thread.Sleep(200); //simulate delay
Debug.WriteLine("sending " + message.Subject + " to " + recipient.EmailPerson.Email);
Thread.Sleep(200); //simulate delay
}
@@ -592,7 +611,7 @@ namespace Swarmops.Utility.BotCode
{
// Temporary error (SMTP 4xx). Try again.
System.Threading.Thread.Sleep(2000); // Allow 2 seconds pause to wait for smtp-server to become available
Thread.Sleep(2000); // Allow 2 seconds pause to wait for smtp-server to become available
throw new ReportAndRetryRecipientException("Temporary smtp error, will retry.", e);
}
@@ -604,18 +623,22 @@ namespace Swarmops.Utility.BotCode
recipients.Add(address.Address);
}
ExceptionMail.Send(new ArgumentException("Bad Recipients when sending to " + recipient.EmailPerson.Email + ": " + String.Join(", ", recipients.ToArray()), e));
ExceptionMail.Send(
new ArgumentException(
"Bad Recipients when sending to " + recipient.EmailPerson.Email + ": " +
String.Join(", ", recipients.ToArray()), e));
if (mail.AuthorType == MailAuthorType.Person)
{
try
{
mail.Author.SendOfficerNotice("Failed recipient(s): " + String.Join(", ", recipients.ToArray()),
"Some recipients failed inexplicably in a mail from you.", 1);
mail.Author.SendOfficerNotice(
"Failed recipient(s): " + String.Join(", ", recipients.ToArray()),
"Some recipients failed inexplicably in a mail from you.", 1);
}
catch (Exception ex)
{
throw new Exception("Failed to SendOfficerNotice to :" + mail.AuthorPersonId.ToString(), ex);
throw new Exception("Failed to SendOfficerNotice to :" + mail.AuthorPersonId, ex);
}
}
}
@@ -624,28 +647,26 @@ namespace Swarmops.Utility.BotCode
}
catch (InvalidRecipientException ex)
{
throw ex;
}
catch (RetryRecipientException ex)
{
System.Threading.Thread.Sleep(2000); // Allow 2 seconds pause to avoid flooding the errorlog too fast in case of a permanent failure
Thread.Sleep(2000);
// Allow 2 seconds pause to avoid flooding the errorlog too fast in case of a permanent failure
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
internal static void MailSent (IAsyncResult result)
internal static void MailSent(IAsyncResult result)
{
lock (lockObject)
{
MailTransmissionAsyncState asyncState = (MailTransmissionAsyncState)result.AsyncState;
MailTransmissionAsyncState asyncState = (MailTransmissionAsyncState) result.AsyncState;
MailTransmissionDelegate asyncTransmitter = asyncState.dlgt;
OutboundMailRecipient recipient = asyncState.recipient;
try
@@ -667,7 +688,7 @@ namespace Swarmops.Utility.BotCode
catch (ReportAndRetryRecipientException e)
{
asyncState.exception = e;
System.Diagnostics.Debug.WriteLine(e.ToString());
Debug.WriteLine(e.ToString());
ExceptionMail.Send(e, true);
}
catch (RetryRecipientException e)
@@ -696,13 +717,13 @@ namespace Swarmops.Utility.BotCode
catch (Exception ex)
{
// Return this exception in asyncState since it is important to stop flooding.
asyncState.exception = new RemoveRecipientException("Couldn't remove mail recipient after exception.", ex);
asyncState.exception =
new RemoveRecipientException("Couldn't remove mail recipient after exception.", ex);
ExceptionMail.Send(asyncState.exception, true); //Report the secondary exception
}
System.Diagnostics.Debug.WriteLine(e.ToString());
Debug.WriteLine(e.ToString());
ExceptionMail.Send(e, true);
}
@@ -710,7 +731,14 @@ namespace Swarmops.Utility.BotCode
}
}
private static int mailQueueSize;
private static Object lockObject = new Object();
internal class MailTransmissionAsyncState
{
internal bool callbackCompleted = false;
internal MailTransmissionDelegate dlgt = null;
internal Exception exception = null;
internal OutboundMailRecipient recipient = null;
}
internal delegate OutboundMailRecipient MailTransmissionDelegate(OutboundMailRecipient recipient);
}
}
+19 -20
View File
@@ -3,7 +3,6 @@ using System.Collections.Generic;
using Swarmops.Basic.Enums;
using Swarmops.Logic.Communications;
using Swarmops.Logic.Structure;
using Swarmops.Logic.Support;
using Swarmops.Logic.Swarm;
using Swarmops.Utility.Mail;
@@ -11,7 +10,7 @@ namespace Swarmops.Utility.BotCode
{
public class MailResolver
{
public static void Run ()
public static void Run()
{
OutboundMail mail = OutboundMail.GetFirstUnresolved();
@@ -32,7 +31,7 @@ namespace Swarmops.Utility.BotCode
switch (mail.MailType)
{
case (int)TypedMailTemplate.TemplateType.MemberMail:
case (int) TypedMailTemplate.TemplateType.MemberMail:
// All members at this org and geography
People people = People.FromOrganizationAndGeography(mail.Organization, mail.Geography);
@@ -43,7 +42,7 @@ namespace Swarmops.Utility.BotCode
}
break;
case (int)TypedMailTemplate.TemplateType.OfficerMail:
case (int) TypedMailTemplate.TemplateType.OfficerMail:
// All officers at this org and geography
int[] officers = Roles.GetAllDownwardRoles(mail.OrganizationId, mail.GeographyId);
downwardCount = officers.Length;
@@ -55,7 +54,7 @@ namespace Swarmops.Utility.BotCode
default:
throw new InvalidOperationException("Unhandled mail mode; can't resolve mail id " +
mail.Identity.ToString());
mail.Identity);
}
int[] upwardIds = Roles.GetAllUpwardRoles(mail.OrganizationId, mail.GeographyId);
@@ -155,19 +154,18 @@ namespace Swarmops.Utility.BotCode
mailBody +=
"Transmissions will begin " + (mail.ReleaseDateTime < DateTime.Now
? "immediately"
:
"in " + (mail.ReleaseDateTime - DateTime.Now).Minutes.ToString() +
" minutes") + ".\r\n";
? "immediately"
: "in " + (mail.ReleaseDateTime - DateTime.Now).Minutes +
" minutes") + ".\r\n";
new MailTransmitter(
"PirateWeb", "noreply@pirateweb.net",
"Mail resolved: " + mail.Title + " (" + countTotal.ToString() + " recipients)", mailBody,
"Mail resolved: " + mail.Title + " (" + countTotal + " recipients)", mailBody,
Person.FromIdentity(mail.AuthorPersonId), true).Send();
}
static private People ApplySubscription (People input, int feedId)
private static People ApplySubscription(People input, int feedId)
{
People output = new People();
@@ -183,7 +181,7 @@ namespace Swarmops.Utility.BotCode
}
public static string CreateWelcomeMail (Person person, Organization organization)
public static string CreateWelcomeMail(Person person, Organization organization)
{
// for this person, iterate over all applicable geographies and organizations
@@ -192,7 +190,7 @@ namespace Swarmops.Utility.BotCode
orgLine.Reverse(); // Start at the most local org
Dictionary<int,bool> orgMailedLookup = new Dictionary<int, bool>();
Dictionary<int, bool> orgMailedLookup = new Dictionary<int, bool>();
int delay = 0;
string result = string.Empty;
@@ -215,7 +213,8 @@ namespace Swarmops.Utility.BotCode
try
{
lead = Roles.GetLocalLead(org, geo);
orgMailedLookup[org.Identity] = true; // Make sure that the chairman doesn't mail at a lower level
orgMailedLookup[org.Identity] = true;
// Make sure that the chairman doesn't mail at a lower level
}
catch (ArgumentException)
{
@@ -226,7 +225,7 @@ namespace Swarmops.Utility.BotCode
// If we get here, there is a mail template at the highest possible geo for this org, but no local lead.
// That's usually the case with board-centric organizations rather than executive-centric.
// Try to mail from chairman rather than the local lead.
try
{
orgMailedLookup[org.Identity] = true;
@@ -257,16 +256,16 @@ namespace Swarmops.Utility.BotCode
welcomemail.pBodyContent = autoMail.Body;
welcomemail.pSubject = autoMail.Title;
OutboundMail newMail = welcomemail.CreateOutboundMail (lead, OutboundMail.PriorityNormal,
org, geo, DateTime.Now.AddMinutes(delay));
OutboundMail newMail = welcomemail.CreateOutboundMail(lead, OutboundMail.PriorityNormal,
org, geo, DateTime.Now.AddMinutes(delay));
newMail.AddRecipient(person.Identity, false);
newMail.SetRecipientCount(1);
newMail.SetResolved();
newMail.SetReadyForPickup();
result += String.Format(" - {0}/{1} by {2} (",
org.NameShort, geoName, lead.Canonical);
org.NameShort, geoName, lead.Canonical);
if (delay == 0)
{
result += "sent now";
+4 -11
View File
@@ -1,18 +1,13 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Swarmops.Basic.Enums;
using Swarmops.Logic.Structure;
using Swarmops.Logic.Support;
using Swarmops.Logic.Swarm;
namespace Swarmops.Utility.BotCode
{
public class Mappery
{
public Dictionary<int, string> OrgColorLookup; // ugly way to transfer data to delegate
[Obsolete("Too specialized for Swarmops. Plugin or generalize.", true)]
public static void CreateUngPiratUptakeMap()
{
@@ -106,8 +101,6 @@ namespace Swarmops.Utility.BotCode
Persistence.Key["OrgUptakeMap-2"] = regex.Replace(svg, matchEvaluator);*/
}
public Dictionary<int, string> OrgColorLookup; // ugly way to transfer data to delegate
/*
public string UPUptakeLookupReplacer (Match match)
{
@@ -127,12 +120,12 @@ namespace Swarmops.Utility.BotCode
}*/
public static Color ColorFromAhsb (int a, float h, float s, float b)
public static Color ColorFromAhsb(int a, float h, float s, float b)
{
if (0 == s)
{
return Color.FromArgb(a, Convert.ToInt32(b*255),
Convert.ToInt32(b*255), Convert.ToInt32(b*255));
Convert.ToInt32(b*255), Convert.ToInt32(b*255));
}
float fMax, fMid, fMin;
+11 -9
View File
@@ -7,13 +7,7 @@ namespace Swarmops.Utility.BotCode
{
public class MediaWatcher
{
public class ReaderException : Exception
{
public ReaderException (string message, Exception innerException)
: base(message, innerException)
{ }
}
public static void Run ()
public static void Run()
{
// Get keywords. Read Frisim. Parse. Store.
@@ -27,10 +21,10 @@ namespace Swarmops.Utility.BotCode
// Read the RSS URL into memory, then feed RssReader from a MemoryStream
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(rssUrl);
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(rssUrl);
request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9b5) Gecko/2008050509 Firefox/3.0b5";
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
HttpWebResponse resp = (HttpWebResponse) request.GetResponse();
RssReader reader = new RssReader(resp.GetResponseStream());
try
@@ -60,5 +54,13 @@ namespace Swarmops.Utility.BotCode
}
}
}
public class ReaderException : Exception
{
public ReaderException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
}
+14 -16
View File
@@ -1,31 +1,20 @@
using System;
using System.Collections.Generic;
using NRss;
using Swarmops.Logic.Communications;
using Swarmops.Logic.Special.Sweden;
using Swarmops.Logic.Structure;
using Swarmops.Logic.Support;
using Swarmops.Logic.Swarm;
namespace Swarmops.Utility.BotCode
{
public class NewsletterChecker
{
const int ForumIdTestPost = 262;//vBulletin, old forum was 326;
const int ForumIdNewsletter = 342; //vBulletin, old forum was 69;
private const int ForumIdTestPost = 262; //vBulletin, old forum was 326;
private const int ForumIdNewsletter = 342; //vBulletin, old forum was 69;
public class ReaderException : Exception
{
public ReaderException (string message, Exception innerException)
: base(message, innerException)
{ }
}
static Dictionary<string, DateTime> feedErrorSignaled = new Dictionary<string, DateTime>();
private static Dictionary<string, DateTime> feedErrorSignaled = new Dictionary<string, DateTime>();
[Obsolete("Too specialized for Swarmops. Plugin or generalize.", true)]
public static void Run()
{/*
{
/*
//TODO: This list should reside in database/by organisation and possibly geography.
CheckOneBlog("http://rickfalkvinge.se/feed", 1);
@@ -33,6 +22,15 @@ namespace Swarmops.Utility.BotCode
CheckOneBlog("http://opassande.se/index.php/feed/", 367);
CheckOneBlog("http://www.annatroberg.com/feed/", 11443);*/
}
public class ReaderException : Exception
{
public ReaderException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/*
private static void CheckOneBlog (string readerFeedUrl, int personId)
{
+18 -16
View File
@@ -13,20 +13,19 @@ namespace Swarmops.Utility.BotCode
public class PressReleaseChecker
{
[Obsolete("Do not call this function until it's been generalized. Don't delete, though - generalize it.", true)]
public static void Run ()
public static void Run()
{
throw new NotImplementedException();
//TODO: This list should reside in database/by organisation and possibly geography.
/*
CheckOneFeed("http://press.piratpartiet.se/feed", "PPSE", Organization.PPSEid);
CheckOneFeed("http://presscenter.ungpirat.se/feed", "UPSE", Organization.UPSEid);
*/
}
private static void CheckOneFeed (string readerUrl, string persistAsKey, int orgIdForTemplate)
private static void CheckOneFeed(string readerUrl, string persistAsKey, int orgIdForTemplate)
{
string persistenceKey = String.Format("Pressrelease-Highwater-{0}", persistAsKey);
@@ -46,7 +45,6 @@ namespace Swarmops.Utility.BotCode
}
else
{
try
{
highWaterMark = DateTime.Parse(highWaterMarkString);
@@ -55,7 +53,9 @@ namespace Swarmops.Utility.BotCode
{
HeartBeater.Instance.SuggestRestart();
throw new Exception(
"Triggered restart. Unable to read/parse old highwater mark from database in PressReleaseChecker.Run(), from key:" + persistenceKey + ", loaded string was '" + highWaterMarkString + "' expected format is " + DateTime.Now.ToString(), ex);
"Triggered restart. Unable to read/parse old highwater mark from database in PressReleaseChecker.Run(), from key:" +
persistenceKey + ", loaded string was '" + highWaterMarkString + "' expected format is " +
DateTime.Now, ex);
}
}
DateTime storedHighWaterMark = highWaterMark;
@@ -95,7 +95,8 @@ namespace Swarmops.Utility.BotCode
catch (Exception ex)
{
throw new Exception(
"Unable to commit/parse new highwater mark to database in PressReleaseChecker.Run(), loaded string was '" + newStoredHighWaterString + "'", ex);
"Unable to commit/parse new highwater mark to database in PressReleaseChecker.Run(), loaded string was '" +
newStoredHighWaterString + "'", ex);
}
if (DateTime.Parse(Persistence.Key[persistenceKey]) < item.PubDate)
@@ -117,9 +118,8 @@ namespace Swarmops.Utility.BotCode
}
else if (category.Name == "Uncategorized")
{
continue;
}
else
else
{
try
{
@@ -133,7 +133,8 @@ namespace Swarmops.Utility.BotCode
}
catch (Exception)
{
ExceptionMail.Send(new Exception("Unrecognized media category in press release: " + category.Name));
ExceptionMail.Send(
new Exception("Unrecognized media category in press release: " + category.Name));
}
}
}
@@ -172,7 +173,6 @@ namespace Swarmops.Utility.BotCode
}
// Send press release
//TODO: hardcoded geo ... using World
@@ -186,7 +186,7 @@ namespace Swarmops.Utility.BotCode
pressreleasemail.pOrgName = org.MailPrefixInherited;
if (allReporters)
{
pressreleasemail.pPostedToCategories = "Alla"; // TODO: TRANSLATE
pressreleasemail.pPostedToCategories = "Alla"; // TODO: TRANSLATE
}
else if (international)
{
@@ -197,7 +197,8 @@ namespace Swarmops.Utility.BotCode
pressreleasemail.pPostedToCategories = PressReleaseMail.GetConcatenatedCategoryString(categories);
}
OutboundMail newMail = pressreleasemail.CreateFunctionalOutboundMail(MailAuthorType.PressService, OutboundMail.PriorityHighest, org, geo);
OutboundMail newMail = pressreleasemail.CreateFunctionalOutboundMail(MailAuthorType.PressService,
OutboundMail.PriorityHighest, org, geo);
int recipientCount = 0;
foreach (Reporter recipient in reporters)
@@ -227,14 +228,16 @@ namespace Swarmops.Utility.BotCode
}
catch (Exception ex)
{
ExceptionMail.Send(new Exception("PressReleaseChecker failed:" + ex.Message + "\r\nwhen checking " + readerUrl, ex));
ExceptionMail.Send(
new Exception("PressReleaseChecker failed:" + ex.Message + "\r\nwhen checking " + readerUrl, ex));
}
finally
{
reader.Close();
}
}
private static string Blog2Mail (string text)
private static string Blog2Mail(string text)
{
return text.
Replace("<h3>", "<h2>").
@@ -246,6 +249,5 @@ namespace Swarmops.Utility.BotCode
Replace("&#8212;", "--").
Replace("&#8230;", "...");
}
}
}
+30 -35
View File
@@ -1,18 +1,13 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Swarmops.Basic;
using Swarmops.Basic.Enums;
using Swarmops.Basic.Types;
using Swarmops.Database;
using Swarmops.Logic.Communications;
using Swarmops.Logic.DataObjects;
using Swarmops.Logic.Security;
using Swarmops.Logic.Structure;
using Swarmops.Logic.Support;
using Swarmops.Logic.Swarm;
using Swarmops.Utility.Mail;
namespace Swarmops.Utility.BotCode
{
@@ -21,7 +16,7 @@ namespace Swarmops.Utility.BotCode
// This function should basically not be called. Any time it is called means a security
// risk.
public static string ExportMemberList (int organizationIdRoot, DateTime membersAfter, DateTime membersBefore)
public static string ExportMemberList(int organizationIdRoot, DateTime membersAfter, DateTime membersBefore)
{
Organizations orgs = Organization.FromIdentity(organizationIdRoot).GetTree();
StringBuilder result = new StringBuilder();
@@ -61,8 +56,8 @@ namespace Swarmops.Utility.BotCode
{
csvResultList.Add(
String.Format("{0},{1},{2},{3:yyyy-MMM-dd},{4}",
person.Name, person.Street, person.PostalCodeAndCity, person.Birthdate,
person.IsMale ? "Male" : "Female"));
person.Name, person.Street, person.PostalCodeAndCity, person.Birthdate,
person.IsMale ? "Male" : "Female"));
}
string[] csvResults = csvResultList.ToArray();
@@ -80,7 +75,7 @@ namespace Swarmops.Utility.BotCode
// This should run daily.
public static void RemindAllExpiries ()
public static void RemindAllExpiries()
{
throw new NotImplementedException();
@@ -97,7 +92,7 @@ namespace Swarmops.Utility.BotCode
[Obsolete("Generalize and localize this function.", true)]
public static void RemindExpiriesMail ()
public static void RemindExpiriesMail()
{
// Get expiring
@@ -120,7 +115,7 @@ namespace Swarmops.Utility.BotCode
foreach (Membership membership in memberships)
{
if (membership.OrganizationId % 7 != weekDayInteger)
if (membership.OrganizationId%7 != weekDayInteger)
{
continue;
}
@@ -132,9 +127,9 @@ namespace Swarmops.Utility.BotCode
SendReminderMail(membership);
Console.Write(".");
PWLog.Write(PWLogItem.Person, membership.PersonId,
PWLogAction.MembershipRenewReminder,
"Mail was sent to " + membership.Person.Mail +
" reminding to renew membership in " + membership.Organization.Name + ".", string.Empty);
PWLogAction.MembershipRenewReminder,
"Mail was sent to " + membership.Person.Mail +
" reminding to renew membership in " + membership.Organization.Name + ".", string.Empty);
Console.Write(".");
@@ -150,11 +145,11 @@ namespace Swarmops.Utility.BotCode
catch (Exception x)
{
string logText = "FAILED sending mail to " + membership.Person.Mail +
" for reminder of pending renewal in " + membership.Organization.Name + ".";
" for reminder of pending renewal in " + membership.Organization.Name + ".";
failedReminders.Add(membership.Person.Canonical);
PWLog.Write(PWLogItem.Person, membership.PersonId,
PWLogAction.MembershipRenewReminder,
logText, string.Empty);
PWLogAction.MembershipRenewReminder,
logText, string.Empty);
ExceptionMail.Send(new Exception(logText, x));
}
}
@@ -204,7 +199,7 @@ namespace Swarmops.Utility.BotCode
// This should run daily, suggested right after midnight.
public static void ChurnExpiredMembers ()
public static void ChurnExpiredMembers()
{
Organizations organizations = Organizations.GetAll();
@@ -231,8 +226,9 @@ namespace Swarmops.Utility.BotCode
if (personRole.OrganizationId == membership.OrganizationId)
{
PWEvents.CreateEvent(EventSource.PirateBot, EventType.DeletedRole, person.Identity,
personRole.OrganizationId, personRole.GeographyId, person.Identity, (int)personRole.Type,
string.Empty);
personRole.OrganizationId, personRole.GeographyId, person.Identity,
(int) personRole.Type,
string.Empty);
personRole.Delete();
}
}
@@ -257,7 +253,7 @@ namespace Swarmops.Utility.BotCode
{
foreach (Membership personMembership in membershipsToDelete)
{
membershipsIds += "," + personMembership.MembershipId.ToString();
membershipsIds += "," + personMembership.MembershipId;
}
membershipsIds = membershipsIds.Substring(1);
string expiredMemberships = "";
@@ -267,7 +263,6 @@ namespace Swarmops.Utility.BotCode
{
expiredMemberships += ", " + personMembership.Organization.Name;
}
}
expiredMemberships += ". ";
expiredmail.pMemberships = expiredMemberships.Substring(2).Trim();
@@ -275,9 +270,9 @@ namespace Swarmops.Utility.BotCode
//TODO: URL for renewal, recieving end of this is NOT yet implemented...
// intended to recreate the memberships in MID
string tokenBase = person.PasswordHash + "-" + membership.Expires.Year.ToString();
string tokenBase = person.PasswordHash + "-" + membership.Expires.Year;
string stdLink = "https://pirateweb.net/Pages/Public/SE/People/MemberRenew.aspx?MemberId=" +
person.Identity.ToString() +
person.Identity +
"&SecHash=" + SHA1.Hash(tokenBase).Replace(" ", "").Substring(0, 8) +
"&MID=" + membershipsIds;
@@ -304,7 +299,7 @@ namespace Swarmops.Utility.BotCode
}
[Obsolete("Generalize and localize this functionality.", true)]
internal static void RemindExpiries (DateTime dateExpiry)
internal static void RemindExpiries(DateTime dateExpiry)
{
Organizations orgs = Organizations.GetAll();
@@ -320,20 +315,21 @@ namespace Swarmops.Utility.BotCode
{
SendReminderMail(membership);
PWLog.Write(PWLogItem.Person, membership.PersonId,
PWLogAction.MembershipRenewReminder,
"Mail was sent to " + membership.Person.Mail +
" reminding to renew membership in " + membership.Organization.Name + ".", string.Empty);
PWLogAction.MembershipRenewReminder,
"Mail was sent to " + membership.Person.Mail +
" reminding to renew membership in " + membership.Organization.Name + ".", string.Empty);
}
catch (Exception ex)
{
ExceptionMail.Send(new Exception("Failed to create reminder mail for person " + membership.PersonId, ex));
ExceptionMail.Send(
new Exception("Failed to create reminder mail for person " + membership.PersonId, ex));
}
}
}
}
[Obsolete("Requires move to plugin or similar, or at least rearch into a hook", true)]
internal static void RemindExpiriesSms (DateTime dateExpiry, string message)
internal static void RemindExpiriesSms(DateTime dateExpiry, string message)
{
throw new NotImplementedException();
@@ -375,7 +371,7 @@ namespace Swarmops.Utility.BotCode
}
internal static bool SendReminderSms (Person person, string message)
internal static bool SendReminderSms(Person person, string message)
{
bool result = false;
@@ -384,7 +380,7 @@ namespace Swarmops.Utility.BotCode
person.SendPhoneMessage(message);
result = true;
}
// ignore exceptions
// ignore exceptions
catch (Exception)
{
}
@@ -393,7 +389,7 @@ namespace Swarmops.Utility.BotCode
}
[Obsolete("Generalize and localize this function.", true)]
public static void SendReminderMail (Membership membership)
public static void SendReminderMail(Membership membership)
{
/*
// First, determine the organization template to use. Prioritize a long ancestry.
@@ -494,7 +490,7 @@ namespace Swarmops.Utility.BotCode
}*/
}
public static void TimeoutVolunteers ()
public static void TimeoutVolunteers()
{
Volunteers volunteers = Volunteers.GetOpen();
DateTime threshold = DateTime.Today.AddDays(-30);
@@ -521,6 +517,5 @@ namespace Swarmops.Utility.BotCode
// Deleted a ton of special cases here, see file history if you need to copy code for reminding people to change org
}
}
+5 -6
View File
@@ -9,7 +9,7 @@ namespace Swarmops.Utility.BotCode
{
public class SalaryProcessor
{
static public void Run()
public static void Run()
{
DateTime today = DateTime.Today;
@@ -17,7 +17,7 @@ namespace Swarmops.Utility.BotCode
string expectedLastRun = today.ToString("yyyyMM", CultureInfo.InvariantCulture);
if (lastRun != null && String.Compare(lastRun,expectedLastRun) >= 0)
if (lastRun != null && String.Compare(lastRun, expectedLastRun) >= 0)
{
// nothing to do, return
@@ -31,14 +31,13 @@ namespace Swarmops.Utility.BotCode
Payroll payroll = Payroll.GetAll();
DateTime payday = new DateTime(today.Year, today.Month, 25);
Dictionary<int,double> salariesTotalPerBudget = new Dictionary<int, double>();
Dictionary<int, double> salariesTotalPerBudget = new Dictionary<int, double>();
foreach (PayrollItem payrollItem in payroll)
{
Salary salary = Salary.Create(payrollItem, payday);
PWEvents.CreateEvent(EventSource.PirateBot, EventType.SalaryCreated, 0, payrollItem.OrganizationId,
0, payrollItem.Person.Identity, salary.Identity, string.Empty);
0, payrollItem.Person.Identity, salary.Identity, string.Empty);
}
}
@@ -65,4 +64,4 @@ namespace Swarmops.Utility.BotCode
transaction.Dependency = salary;
}*/
}
}
}
+46 -44
View File
@@ -5,13 +5,18 @@ using Swarmops.Logic.Governance;
namespace Swarmops.Utility.BotCode
{
/// <summary>
/// This class computes a Condorcet/Single-Transferable-Vote result according to the Schulze Method.
/// This class computes a Condorcet/Single-Transferable-Vote result according to the Schulze Method.
/// </summary>
public class SchulzeProcessor
{
private List<int> candidateIds;
private Dictionary<int, int> indexOfCandidateId;
private int[,] linkStrengthXtoY;
private int[,] preferenceXtoY;
public MeetingElectionVotes Votes { set; private get; }
public MeetingElectionCandidates Candidates { set; private get; }
public MeetingElectionCandidates FinalOrder { get; private set; }
public void Process()
{
@@ -35,13 +40,13 @@ namespace Swarmops.Utility.BotCode
Console.Write("Creating list of candidates and index lookup...");
candidateIds = new List<int>();
indexOfCandidateId = new Dictionary<int, int>();
this.candidateIds = new List<int>();
this.indexOfCandidateId = new Dictionary<int, int>();
int index = 0;
foreach (MeetingElectionCandidate candidate in Candidates)
{
candidateIds.Add(candidate.Identity);
indexOfCandidateId[candidate.Identity] = index;
this.candidateIds.Add(candidate.Identity);
this.indexOfCandidateId[candidate.Identity] = index;
index++;
}
@@ -61,7 +66,8 @@ namespace Swarmops.Utility.BotCode
// At the end of the iteration, we set all the NOT-checked-off candidates as inferior to those
// checked off (as they were not voted for).
preferenceXtoY = new int[candidateIds.Count,candidateIds.Count]; // huuuuuge matrix for 1000+ candidates, zero inited
this.preferenceXtoY = new int[this.candidateIds.Count, this.candidateIds.Count];
// huuuuuge matrix for 1000+ candidates, zero inited
int count = 1;
@@ -73,14 +79,15 @@ namespace Swarmops.Utility.BotCode
Dictionary<int, bool> candidateIdSeen = new Dictionary<int, bool>();
int[] voteCandidateIds = vote.SelectedCandidateIdsInOrder;
foreach (int candidateId in voteCandidateIds)
{
// for each candidate, record all previously iterated as superior for this vote:
foreach (int previousCandidateId in candidateIdSeen.Keys)
{
preferenceXtoY[indexOfCandidateId[previousCandidateId], indexOfCandidateId[candidateId]]++;
this.preferenceXtoY[
this.indexOfCandidateId[previousCandidateId], this.indexOfCandidateId[candidateId]]++;
}
// check this candidate off as iterated
@@ -92,7 +99,7 @@ namespace Swarmops.Utility.BotCode
// superior to the candidates NOT on the votes cast. Iterate through all the candidates to find which ones
// were not mentioned.
foreach (int candidateId in candidateIds)
foreach (int candidateId in this.candidateIds)
{
if (!candidateIdSeen.ContainsKey(candidateId))
{
@@ -100,7 +107,8 @@ namespace Swarmops.Utility.BotCode
foreach (int voteCandidateId in voteCandidateIds)
{
preferenceXtoY[indexOfCandidateId[voteCandidateId], indexOfCandidateId[candidateId]]++;
this.preferenceXtoY[
this.indexOfCandidateId[voteCandidateId], this.indexOfCandidateId[candidateId]]++;
}
}
}
@@ -118,29 +126,28 @@ namespace Swarmops.Utility.BotCode
//
// http://en.wikipedia.org/wiki/Schulze_method
linkStrengthXtoY = new int[candidateIds.Count,candidateIds.Count];
this.linkStrengthXtoY = new int[this.candidateIds.Count, this.candidateIds.Count];
// First part of magic. Establish the direction of pairwise defeats. I think.
Console.WriteLine("Calculating link strengths.");
for (int outerIndex = 0; outerIndex < candidateIds.Count; outerIndex++)
for (int outerIndex = 0; outerIndex < this.candidateIds.Count; outerIndex++)
{
Console.Write("\r - Step 1: {0:D4} of {1:D4}...", outerIndex+1, candidateIds.Count);
Console.Write("\r - Step 1: {0:D4} of {1:D4}...", outerIndex + 1, this.candidateIds.Count);
for (int innerIndex = 0; innerIndex < candidateIds.Count; innerIndex++)
for (int innerIndex = 0; innerIndex < this.candidateIds.Count; innerIndex++)
{
if (innerIndex == outerIndex)
{
continue;
}
if (preferenceXtoY[outerIndex, innerIndex] > preferenceXtoY[innerIndex, outerIndex])
if (this.preferenceXtoY[outerIndex, innerIndex] > this.preferenceXtoY[innerIndex, outerIndex])
{
linkStrengthXtoY[outerIndex, innerIndex] = preferenceXtoY[outerIndex, innerIndex];
this.linkStrengthXtoY[outerIndex, innerIndex] = this.preferenceXtoY[outerIndex, innerIndex];
}
// else set to zero, but this is handled by the framework on initialization
}
}
@@ -148,29 +155,28 @@ namespace Swarmops.Utility.BotCode
// Second part of magic, an O(n^3) algorithm. In the famous words of Alfred E. Neuman: Yecch!
for (int outerIndex = 0; outerIndex < candidateIds.Count; outerIndex++)
for (int outerIndex = 0; outerIndex < this.candidateIds.Count; outerIndex++)
{
Console.Write("\r - Step 2: {0:D4} of {1:D4}...", outerIndex + 1, candidateIds.Count);
Console.Write("\r - Step 2: {0:D4} of {1:D4}...", outerIndex + 1, this.candidateIds.Count);
for (int middleIndex = 0; middleIndex < candidateIds.Count; middleIndex++)
for (int middleIndex = 0; middleIndex < this.candidateIds.Count; middleIndex++)
{
if (outerIndex == middleIndex)
{
continue;
}
for (int innerIndex = 0; innerIndex < candidateIds.Count; innerIndex++)
for (int innerIndex = 0; innerIndex < this.candidateIds.Count; innerIndex++)
{
if (outerIndex == innerIndex || middleIndex == innerIndex)
{
continue;
}
linkStrengthXtoY[middleIndex, innerIndex] =
Math.Max(linkStrengthXtoY[middleIndex, innerIndex],
Math.Min(linkStrengthXtoY[middleIndex, outerIndex],
linkStrengthXtoY[outerIndex, innerIndex]));
this.linkStrengthXtoY[middleIndex, innerIndex] =
Math.Max(this.linkStrengthXtoY[middleIndex, innerIndex],
Math.Min(this.linkStrengthXtoY[middleIndex, outerIndex],
this.linkStrengthXtoY[outerIndex, innerIndex]));
}
}
}
@@ -186,7 +192,7 @@ namespace Swarmops.Utility.BotCode
MeetingElectionCandidates result = new MeetingElectionCandidates();
Dictionary<int, bool> candidateAdded = new Dictionary<int, bool>();
int candidatesRemaining = candidateIds.Count;
int candidatesRemaining = this.candidateIds.Count;
int count = 1;
@@ -213,15 +219,17 @@ namespace Swarmops.Utility.BotCode
{
allSuperior = true;
for (int compareCandidateIndex = 0; compareCandidateIndex < candidateIds.Count; compareCandidateIndex++)
for (int compareCandidateIndex = 0;
compareCandidateIndex < this.candidateIds.Count;
compareCandidateIndex++)
{
if (candidateAdded.ContainsKey(compareCandidateIndex))
{
continue;
}
if (linkStrengthXtoY[winningCandidateIndex, compareCandidateIndex] <
linkStrengthXtoY[compareCandidateIndex,winningCandidateIndex])
if (this.linkStrengthXtoY[winningCandidateIndex, compareCandidateIndex] <
this.linkStrengthXtoY[compareCandidateIndex, winningCandidateIndex])
{
// the compareCandidateIndex had a greater link strength, so jump there and take it as
// a new potential winner, restarting the comparison
@@ -235,7 +243,8 @@ namespace Swarmops.Utility.BotCode
// We have the winning candidate among the not-yet-ranked candidates:
MeetingElectionCandidate candidate = MeetingElectionCandidate.FromIdentity(candidateIds[winningCandidateIndex]);
MeetingElectionCandidate candidate =
MeetingElectionCandidate.FromIdentity(this.candidateIds[winningCandidateIndex]);
candidateAdded[winningCandidateIndex] = true;
result.Add(candidate);
@@ -249,19 +258,12 @@ namespace Swarmops.Utility.BotCode
}
private int[,] preferenceXtoY;
private int[,] linkStrengthXtoY;
private List<int> candidateIds;
private Dictionary<int, int> indexOfCandidateId;
public MeetingElectionCandidates FinalOrder { get; private set; }
public int GetCandidateDistance (int finalOrderIndex)
public int GetCandidateDistance(int finalOrderIndex)
{
// Gets the distance, in preference counts, between candidate [finalOrderIndex] and candidate [finalOrderIndex+1].
// This is purely a diagnostic function and does not contribute to the results calculations.
if (finalOrderIndex >= FinalOrder.Count -1)
if (finalOrderIndex >= FinalOrder.Count - 1)
{
return 0;
}
@@ -269,12 +271,12 @@ namespace Swarmops.Utility.BotCode
int candidateIdX = FinalOrder[finalOrderIndex].Identity;
int candidateIdY = FinalOrder[finalOrderIndex + 1].Identity;
int indexX = indexOfCandidateId[candidateIdX];
int indexY = indexOfCandidateId[candidateIdY];
int indexX = this.indexOfCandidateId[candidateIdX];
int indexY = this.indexOfCandidateId[candidateIdY];
int distance = preferenceXtoY[indexX, indexY] - preferenceXtoY[indexY, indexX];
int distance = this.preferenceXtoY[indexX, indexY] - this.preferenceXtoY[indexY, indexX];
return distance;
}
}
}
}
+2 -6
View File
@@ -1,9 +1,4 @@
using System;
using Swarmops.Database;
using Swarmops.Logic.Communications;
using Swarmops.Logic.Special.Sweden;
using Swarmops.Logic.Structure;
using Swarmops.Logic.Support;
namespace Swarmops.Utility.BotCode
{
@@ -86,6 +81,7 @@ namespace Swarmops.Utility.BotCode
Persistence.Key[persistenceKey] = lastDeltaId.ToString();*/
}
/*
public static void Housekeeping()
{
@@ -106,4 +102,4 @@ namespace Swarmops.Utility.BotCode
}
}*/
}
}
}
+6 -7
View File
@@ -2,7 +2,7 @@ namespace Swarmops.Utility.BotCode
{
public class UpdateStatsCache
{
static public void Run()
public static void Run()
{
BotLog.Write(1, "UpdateStatsCache", "Entering (obsoleted does nothing");
@@ -11,14 +11,15 @@ namespace Swarmops.Utility.BotCode
BotLog.Write(1, "UpdateStatsCache", "Exiting");
}
private static void UpdateBallotDistroData ()
private static void UpdateBallotDistroData()
{
//Empty method now this is done from the web app.
}
private static void ObsoletedUpdateBallotDistroData ()
private static void ObsoletedUpdateBallotDistroData()
{
#region Obsoleted commented code
//BotLog.Write(2, "BallotDistroData", "Entering");
//BotLog.Write(2, "BallotDistroData", "Getting geographic voter counts...");
@@ -175,12 +176,9 @@ namespace Swarmops.Utility.BotCode
//BotLog.Write(2, "BallotDistroData", "Done collecting election day data.");
//BotLog.Write(2, "BallotDistroData", "Aggregating per electoral circuit.");
//// This is not very optimized, but it runs only once per hour and
//// has easy-to-follow logic.
@@ -234,7 +232,8 @@ namespace Swarmops.Utility.BotCode
//Persistence.Key["BallotCoverage-SE"] = coverageData.ToXml();
//BotLog.Write(2, "BallotDistroData", "Exiting");
#endregion
}
}
}
}