First import into fresh repo

This commit is contained in:
Rick Falkvinge
2011-05-13 15:04:42 +00:00
commit 10701edbb7
7418 changed files with 1994168 additions and 0 deletions
+99
View File
@@ -0,0 +1,99 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Mail;
using System.Text;
using System.Web;
using Activizr.Basic.Enums;
using Activizr.Logic.Pirates;
using Activizr.Logic.Structure;
namespace Activizr.Utility.BotCode
{
public class ActivityMailer
{
public static void Run()
{
// PPSE only, for now
ExternalActivities activities = ExternalActivities.ForOrganization(Organization.PPSE);
// TODO: HTML mailer for this (or TemplateMail)
string body = string.Empty;
body +=
"<html><body>" +
"<p>Veckans aktivism i Piratpartiet (ladda bilderna):</p>";
DateTime cutoffDate = DateTime.Today.AddDays(-6);
foreach (ExternalActivity activity in activities)
{
if (activity.DateTime > cutoffDate)
{
body += "<img src=\"http://data.piratpartiet.se/Handlers/DisplayActivism.aspx?Id=" +
activity.Identity +
"\" width=\"600\" height=\"450\" Alt=\"Aktivism i " +
HttpUtility.HtmlEncode(activity.Geography.Name) + "\" /><br/><br/>";
}
}
body +=
"<p>F&ouml;r att logga aktivism d&auml;r du &auml;r funktion&auml;r, g&aring; till PirateWeb, Aktivism, <a href=\"https://pirateweb.net/Pages/v4/Activism/LogActivism.aspx\">Logga aktivism</a>. B&auml;sta valkretsen fram till valet vinner Fina Priser!</p>" +
"<p>Denna sammanfattning skickas varje tisdag kl 10, s&aring; att alla hinner logga helgens aktivism.</p>" +
"</body></html>";
// foreach officer
Roles roles = Roles.GetAll();
Dictionary<int, bool> dupeCheck = new Dictionary<int, bool>();
foreach (PersonRole role in roles)
{
if (role.OrganizationId == 1)
{
Person person = role.Person;
if (person.MemberOf(Organization.PPSE) && person.PartyEmail.Length > 0 && !dupeCheck.ContainsKey(person.Identity))
{
dupeCheck[person.Identity] = true;
MailMessage message = new MailMessage();
message.To.Add(person.PartyEmail);
message.From = new MailAddress("noreply@pirateweb.net", "PirateWeb Activism");
message.IsBodyHtml = true;
message.Body = body;
message.Subject = "Veckans aktivism i Piratpartiet";
string smtpServer = ConfigurationManager.AppSettings["SmtpServer"];
if (smtpServer.ToLower() != "none")
{
if (smtpServer == null || smtpServer.Length < 2)
{
smtpServer = "localhost";
}
try
{
SmtpClient client = new SmtpClient(smtpServer, 25);
client.Send(message);
}
catch (SmtpException e)
{
// Basically ignore any exception
Console.WriteLine(e.Message);
}
}
}
}
}
}
}
}
@@ -0,0 +1,142 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.3620
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Activizr.Utility.BotCode.App_LocalResources {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class EventProcessor {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal EventProcessor() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Activizr.Utility.BotCode.App_LocalResources.EventProcessor", typeof(EventProcessor).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to (Du får detta mail eftersom du skrivit upp dig som aktivist i någon av piratorganisationerna. Ingen av våra funktionärer kan se vem du är. Om du inte längre vill ha aktivistmail och -SMS, så gå till https://pirateweb.net/Pages/Public/SE/People/ActivistSignoff.aspx för att avregistrera din mailadress.).
/// </summary>
internal static string ActivistMail_Ending {
get {
return ResourceManager.GetString("ActivistMail_Ending", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Du är nu inte längre aktivist i piratrörelsen. Det innebär att du inte längre kommer att få de speciella meddelanden som skickas till aktivister när något händer lokalt på din ort
///
///Du är när som helst välkommen tillbaka att registrera dig som aktivist på
///https://pirateweb.net/Pages/Public/SE/People/ActivistSignup.aspx
///.
/// </summary>
internal static string LostActivistAck_Mail_Body {
get {
return ResourceManager.GetString("LostActivistAck_Mail_Body", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Piratpartiet: Avregistrerad som Aktivist.
/// </summary>
internal static string LostActivistAck_Mail_Subject {
get {
return ResourceManager.GetString("LostActivistAck_Mail_Subject", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Du är nu aktivist i piratrörelsen. Det innebär att du kommer att få meddelanden när något händer lokalt på din ort, så att du själv kan välja om du vill vara med på dem eller inte. De kan skickas till din mobil och/eller mail, beroende på händelsernas art.
///
///Välkommen att hjälpa till att återställa medborgarrätterna i valet 2010!
///
///.
/// </summary>
internal static string NewActivistWelcome_Mail_Body {
get {
return ResourceManager.GetString("NewActivistWelcome_Mail_Body", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Piratpartiet: Välkommen som aktivist.
/// </summary>
internal static string NewActivistWelcome_Mail_Subject {
get {
return ResourceManager.GetString("NewActivistWelcome_Mail_Subject", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Tack för att du har valt att förnya ditt medlemskap och fortsätta vara en del av piratrörelsen i Sverige! Ditt medlemskap går nu ut {0}, och gäller följande organisationer och föreningar:
///
///{1}
///
///Om du har några frågor, så kontakta gärna Medlemsservice på {2}.
///
///Återigen, välkommen att vara med i vårt fortsatta arbete!
///
///.
/// </summary>
internal static string RenewalAck_Mail {
get {
return ResourceManager.GetString("RenewalAck_Mail", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0}: Ditt medlemskap är förnyat.
/// </summary>
internal static string RenewalAck_Mail_Subject {
get {
return ResourceManager.GetString("RenewalAck_Mail_Subject", resourceCulture);
}
}
}
}
@@ -0,0 +1,148 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="LostActivistAck_Mail_Body" xml:space="preserve">
<value>Olet poistunut aktiivijäsenten listalta. Jatkossa saat enää harvakseltaan lähetettävät tärkeimmät puolueen tiedotteet ja viestit, kuten kokouskutsut.
Mikäli joskus haluat liittyä takaisin aktiivijäseneksi, se onnistuu helposti PirateWeb jäsenrekisterin kautta.
</value>
</data>
<data name="LostActivistAck_Mail_Subject" xml:space="preserve">
<value>Piraattipuolue: Aktiivilistalta poistuminen</value>
</data>
<data name="NewActivistWelcome_Mail_Body" xml:space="preserve">
<value>Olet liittynyt jäsenhakemuksen tai PirateWeb jäsenrekisterin hallinnan kautta aktiivijäseneksi.
Tämä tarkoittaa sitä, että saat paremmin tietoa puolueen toiminnasta, ajankohtaisista asioista ja huomiota vaativista seikoista.
Tervetuloa seuraamaan ja osallistumaan puolueen toimintaan lähemmin, sekä toivomme sinun suosittelevan samaa myös ystävillesi.
</value>
</data>
<data name="NewActivistWelcome_Mail_Subject" xml:space="preserve">
<value>Piraattipuolue: Tervetuloa aktiivijäseneksi!</value>
</data>
<data name="RenewalAck_Mail" xml:space="preserve">
<value>
</value>
<comment>{0} for new expiry date, {1} for org name, {2} for member service email</comment>
</data>
<data name="RenewalAck_Mail_Subject" xml:space="preserve">
<value />
<comment>{0} for org name</comment>
</data>
</root>
@@ -0,0 +1,159 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="ActivistMail_Ending" xml:space="preserve">
<value>(Du får detta mail eftersom du skrivit upp dig som aktivist i någon av piratorganisationerna. Ingen av våra funktionärer kan se vem du är. Om du inte längre vill ha aktivistmail och -SMS, så gå till https://pirateweb.net/Pages/Public/SE/People/ActivistSignoff.aspx för att avregistrera din mailadress.)</value>
</data>
<data name="LostActivistAck_Mail_Body" xml:space="preserve">
<value>Du är nu inte längre aktivist i piratrörelsen. Det innebär att du inte längre kommer att få de speciella meddelanden som skickas till aktivister när något händer lokalt på din ort
Du är när som helst välkommen tillbaka att registrera dig som aktivist på
https://pirateweb.net/Pages/Public/SE/People/ActivistSignup.aspx
</value>
</data>
<data name="LostActivistAck_Mail_Subject" xml:space="preserve">
<value>Piratpartiet: Avregistrerad som Aktivist</value>
</data>
<data name="NewActivistWelcome_Mail_Body" xml:space="preserve">
<value>Du är nu aktivist i piratrörelsen. Det innebär att du kommer att få meddelanden när något händer lokalt på din ort, så att du själv kan välja om du vill vara med på dem eller inte. De kan skickas till din mobil och/eller mail, beroende på händelsernas art.
Välkommen att hjälpa till att återställa medborgarrätterna i valet 2010!
</value>
</data>
<data name="NewActivistWelcome_Mail_Subject" xml:space="preserve">
<value>Piratpartiet: Välkommen som aktivist</value>
</data>
<data name="RenewalAck_Mail" xml:space="preserve">
<value>Tack för att du har valt att förnya ditt medlemskap och fortsätta vara en del av piratrörelsen i Sverige! Ditt medlemskap går nu ut {0}, och gäller följande organisationer och föreningar:
{1}
Om du har några frågor, så kontakta gärna Medlemsservice på {2}.
Återigen, välkommen att vara med i vårt fortsatta arbete!
</value>
<comment>{0} for new expiry date, {1} for org name, {2} for member service email</comment>
</data>
<data name="RenewalAck_Mail_Subject" xml:space="preserve">
<value>{0}: Ditt medlemskap är förnyat</value>
<comment>{0} for org name</comment>
</data>
</root>
@@ -0,0 +1,159 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="ActivistMail_Ending" xml:space="preserve">
<value>(Du får detta mail eftersom du skrivit upp dig som aktivist i någon av piratorganisationerna. Ingen av våra funktionärer kan se vem du är. Om du inte längre vill ha aktivistmail och -SMS, så gå till https://pirateweb.net/Pages/Public/SE/People/ActivistSignoff.aspx för att avregistrera din mailadress.)</value>
</data>
<data name="LostActivistAck_Mail_Body" xml:space="preserve">
<value>Du är nu inte längre aktivist i piratrörelsen. Det innebär att du inte längre kommer att få de speciella meddelanden som skickas till aktivister när något händer lokalt på din ort
Du är när som helst välkommen tillbaka att registrera dig som aktivist på
https://pirateweb.net/Pages/Public/SE/People/ActivistSignup.aspx
</value>
</data>
<data name="LostActivistAck_Mail_Subject" xml:space="preserve">
<value>Piratpartiet: Avregistrerad som Aktivist</value>
</data>
<data name="NewActivistWelcome_Mail_Body" xml:space="preserve">
<value>Du är nu aktivist i piratrörelsen. Det innebär att du kommer att få meddelanden när något händer lokalt på din ort, så att du själv kan välja om du vill vara med på dem eller inte. De kan skickas till din mobil och/eller mail, beroende på händelsernas art.
Välkommen att hjälpa till att återställa medborgarrätterna i valet 2010!
</value>
</data>
<data name="NewActivistWelcome_Mail_Subject" xml:space="preserve">
<value>Piratpartiet: Välkommen som aktivist</value>
</data>
<data name="RenewalAck_Mail" xml:space="preserve">
<value>Tack för att du har valt att förnya ditt medlemskap och fortsätta vara en del av piratrörelsen i Sverige! Ditt medlemskap går nu ut {0}, och gäller följande organisationer och föreningar:
{1}
Om du har några frågor, så kontakta gärna Medlemsservice på {2}.
Återigen, välkommen att vara med i vårt fortsatta arbete!
</value>
<comment>{0} for new expiry date, {1} for org name, {2} for member service email</comment>
</data>
<data name="RenewalAck_Mail_Subject" xml:space="preserve">
<value>{0}: Ditt medlemskap är förnyat</value>
<comment>{0} for org name</comment>
</data>
</root>
+349
View File
@@ -0,0 +1,349 @@
using System;
using System.Collections.Generic;
using System.Text;
using Activizr.Basic.Enums;
using Activizr.Logic.Governance;
using Activizr.Logic.Structure;
namespace Activizr.Utility.BotCode
{
public class BallotComposer
{
/// <summary>
/// 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.
/// </summary>
public MeetingElectionCandidates RawElectionResult
{
set
{
rawElectionResult = value;
geographicLists = new Dictionary<int, MeetingElectionCandidates>();
}
}
private MeetingElectionCandidates rawElectionResult;
/// <summary>
/// Sets the geographies for which to construct ballots.
/// </summary>
public Geographies BallotGeographies { set; get; }
/// <summary>
/// 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>();
foreach (int defectedPersonId in value)
{
defectionsLookup[defectedPersonId] = true;
}
}
}
public void ComposeBallots(BallotCompositionMethod method)
{
FinalBallots = new Dictionary<int, MeetingElectionCandidates>();
QuotedMasterList = GenerateBallot(rawElectionResult, -1, BallotCompositionMethod.Unmixed);
if (geographicLists.Count == 0)
{
GenerateGeographicLists();
}
foreach (Geography ballotGeography in BallotGeographies)
{
FinalBallots[ballotGeography.Identity] = GenerateBallot(geographicLists[ballotGeography.Identity], 22,
method);
}
}
public bool CandidatePersonIdDefected (int personId)
{
return defectionsLookup.ContainsKey(personId);
}
private void GenerateGeographicLists()
{
foreach (MeetingElectionCandidate candidate in rawElectionResult)
{
foreach (Geography ballotGeography in BallotGeographies)
{
if (candidate.Person.Geography.Inherits(ballotGeography))
{
// This candidate is under this particular geography, so add to list
if (!geographicLists.ContainsKey(ballotGeography.Identity))
{
geographicLists[ballotGeography.Identity] = new MeetingElectionCandidates();
}
geographicLists[ballotGeography.Identity].Add(candidate);
}
}
}
}
private MeetingElectionCandidates GenerateBallot (MeetingElectionCandidates rawList, int candidateCount, BallotCompositionMethod method)
{
MeetingElectionCandidates result = new MeetingElectionCandidates();
Dictionary<int, bool> takenCandidates = new Dictionary<int, bool>();
if (candidateCount == -1)
{
candidateCount = rawList.Count;
}
// First, cancel out the defected candidates. Expensive op, but don't care.
for (int rawIndex = 0; rawIndex < rawList.Count; rawIndex++)
{
if (this.CandidatePersonIdDefected(rawList [rawIndex].PersonId))
{
takenCandidates[rawIndex] = true;
}
}
if (candidateCount == rawList.Count)
{
candidateCount -= takenCandidates.Count;
}
// Assemble list.
while (result.Count < candidateCount)
{
// Add a candidate.
//
// Should we add a candidate from the raw list or from the quoted master list?
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);
if (rawListIndex >= 0 && !takenCandidates.ContainsKey(rawListIndex))
{
// The master list candidate is also on the district list, but has not been added. Add
// the candidate in the master list position.
result.Add(QuotedMasterList[masterPosition - 1]);
takenCandidates[rawListIndex] = true;
continue;
}
if (rawListIndex == -1)
{
// The master list candidate is not on the district list. Add the candidate.
result.Add(QuotedMasterList[masterPosition - 1]);
continue;
}
// Getting here, the candidate on the master position had already been placed on the list through his
// or her district, so fallthrough to local candidates for this master position
}
// Add a candidate from the local list. First, try adding the next available candidate.
// If this puts us outside of the allowed gender quota, pick the next candidate of the
// underrepresented gender instead.
int nextCandidateIndex = 0;
while (takenCandidates.ContainsKey(nextCandidateIndex))
{
nextCandidateIndex++;
}
PersonGender candidateGender = rawList[nextCandidateIndex].Person.Gender;
double currentMaleQuota = CalculateListMaleQuota(result, candidateGender);
// Here, we account an extremely rare situation where the correct quota is not even obtainable, e.g.
// for position #3 where #1 is male and #2 is female and with a quota of 40%. Either way, it will
// 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);
double alternateMaleQuota = CalculateListMaleQuota(result, oppositeGender);
// If currentMaleQuota is outside of bounds AND the alternate quota IS inside of bounds...
if (currentMaleQuota < GenderQuota || currentMaleQuota > (1.0 - GenderQuota))
{
if (alternateMaleQuota >= GenderQuota && alternateMaleQuota <= (1.0 - GenderQuota))
{
// ...pick the alternate (underrepresented) candidate
try
{
nextCandidateIndex = GetNextSpecificGenderCandidate(rawList, takenCandidates, oppositeGender);
}
catch (ArgumentOutOfRangeException)
{
// there isn't any more candidate of the requested gender, so go with what we have
}
}
}
result.Add(rawList[nextCandidateIndex]);
takenCandidates[nextCandidateIndex] = true;
}
return result;
}
private static int FindCandidateIndex (int candidateId, MeetingElectionCandidates list)
{
for (int index = 0; index < list.Count; index++)
{
if (list [index].Identity == candidateId)
{
return index;
}
}
return -1;
}
private static double CalculateListMaleQuota (MeetingElectionCandidates candidates, PersonGender nextCandidateGender)
{
if (candidates.Count < 1)
{
return 0.5; // Division by zero protection, here and in caller
}
double malesTotal = 0.0;
foreach (MeetingElectionCandidate candidate in candidates)
{
if (candidate.Person.Gender == PersonGender.Male)
{
malesTotal += 1.0;
}
}
if (nextCandidateGender == PersonGender.Male)
{
malesTotal += 1.0;
}
return malesTotal/(candidates.Count + 1.0);
}
private static int GetNextSpecificGenderCandidate (MeetingElectionCandidates candidates,
Dictionary<int,bool> takenCandidates, PersonGender desiredGender)
{
int index = 0;
while (takenCandidates.ContainsKey(index) || candidates [index].Person.Gender != desiredGender)
{
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.
/// </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)
{
if (method == BallotCompositionMethod.Unmixed)
{
return 0; // always use local
}
if (method == BallotCompositionMethod.TopTenNational)
{
if (currentPosition <= 10)
{
return currentPosition;
}
return 0;
}
if (method == BallotCompositionMethod.TopFiveNational)
{
if (currentPosition <= 5)
{
return currentPosition;
}
return 0;
}
if (method == BallotCompositionMethod.InterleavedTenNational)
{
if ((currentPosition % 2 == 1) && currentPosition < 20)
{
return (currentPosition/2 + 1);
}
return 0;
}
throw new NotImplementedException("Unimplemented method");
}
}
public enum BallotCompositionMethod
{
/// <summary>
/// FxCop directive - unused
/// </summary>
Unknown = 0,
/// <summary>
/// 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.
/// </summary>
TopFiveNational,
/// <summary>
/// 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.
/// </summary>
Unmixed
}
}
+55
View File
@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using Activizr.Database;
using Activizr.Logic;
namespace Activizr.Utility.BotCode
{
public class BlogTop50Scraper
{
public static void Run()
{
// Every hour of the day, we check that this has been recorded for the day. This is just in case
// the bot isn't running at midnight, to make sure that we get one entry per day.
if (PirateDb.GetDatabase().GetBlogTopList(DateTime.Today) == null)
{
ScrapeAndStore();
}
}
private static void ScrapeAndStore()
{
string scrapeData = string.Empty;
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.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())
{
using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(1252)))
{
scrapeData = reader.ReadToEnd();
}
}
Regex regex = new Regex("<h4 .*?><a href.*?>(?<blogname>.*?)</a>", RegexOptions.None);
Match match = regex.Match(scrapeData);
List<string> rankingList = new List<string>();
while (match.Success)
{
string blogName = match.Groups["blogname"].Value;
rankingList.Add(blogName);
match = match.NextMatch();
}
PirateDb.GetDatabase().StoreBlogTopList(DateTime.Today, rankingList.ToArray());
}
}
}
+97
View File
@@ -0,0 +1,97 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using Activizr.Logic.Media;
using NRss;
using Activizr.Logic.Support;
namespace Activizr.Utility.BotCode
{
public class BlogWatcher
{
public class ReaderException : Exception
{
public ReaderException (string message, Exception innerException)
: base(message, innerException)
{ }
}
public static void Run ()
{
// Get keywords. Read Knuff. Parse. Store.
string[] keywords = MediaEntries.GetBlogKeywords();
foreach (string keyword in keywords)
{
string rssUrl = "http://knuff.se/rss/q/" + keyword;
// Read the RSS URL into memory, then feed RssReader from a MemoryStream
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.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();
RssReader reader = new RssReader(resp.GetResponseStream());
try
{
Rss rss = reader.Read();
foreach (RssChannelItem item in rss.Channel.Items)
{
// We want the title, link and pubdate.
string url = item.Link;
DateTime dateTime = item.PubDate;
int dividerIndex = item.Title.LastIndexOf('(');
if (item.Title.EndsWith("))"))
{
dividerIndex = item.Title.Substring(0, item.Title.Length - 7).LastIndexOf('(');
}
string title = item.Title.Substring(0, dividerIndex).Trim();
string blogName = item.Title.Substring(dividerIndex + 1, item.Title.Length - dividerIndex - 2);
bool newEntry = MediaEntry.CreateFromKeyword(keyword, blogName, true, url, title, dateTime);
if (newEntry)
{
try
{
PingCreeper(url);
}
catch (Exception)
{
// Ignore exceptions here, move on to the next entry
}
}
}
}
catch (Exception e)
{
throw new ReaderException("feed:" + rssUrl + ", Status=" + resp.StatusCode, e);
}
finally
{
request.GetResponse().GetResponseStream().Close();
}
}
}
private static void PingCreeper (string referringUrl)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.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();
}
}
}
+44
View File
@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Activizr.Utility.BotCode
{
public class BotLog
{
static public void Write (int generation, string code, string message)
{
string line = string.Empty;
for (int loop = 0; loop < generation; loop++)
{
line += "-";
}
if (generation > 0)
{
line += " ";
}
line += string.Format("{0,-16} ", code);
line += message;
LogWrite(line);
}
static private void LogWrite (string message)
{
DateTime now = DateTime.Now;
string logFileName = "logs" + System.IO.Path.DirectorySeparatorChar + "botlog-" +
now.ToString("yyyy-MM-dd-HH") + ".log";
using (StreamWriter writer = new StreamWriter(logFileName, true, Encoding.GetEncoding(1252)))
{
writer.WriteLine("[" + now.ToString("HH:mm:ss.fff") + "] " + message);
}
}
}
}
File diff suppressed because it is too large Load Diff
+80
View File
@@ -0,0 +1,80 @@
using System;
using System.Collections;
using System.Web.Mail;
using PirateWeb.Logic.Objects;
using PirateWeb.Database;
namespace PirateWeb
{
/// <summary>
/// Summary description for ForumHousekeeping.
/// </summary>
public class ForumHousekeeping
{
public ForumHousekeeping()
{
//
// TODO: Add constructor logic here
//
}
public static void Run()
{
Database database = new Database (Globals.DatabaseConnectString);
ForumDatabase forumDatabase = new ForumDatabase (Globals.ForumDatabaseConnectString);
Hashtable memberAccounts = new Hashtable();
Member[] members = database.GetAllMembers();
foreach (Member member in members)
{
try
{
if (member.ForumAccountId != 0)
{
if (!forumDatabase.IsPartyMember (member.ForumAccountId))
{
// This guy is not listed as a party member, but should be.
forumDatabase.SetPartyMember (member.ForumAccountId);
}
memberAccounts [member.ForumAccountId] = true;
}
}
catch (Exception)
{
// The forum account probably doesn't exist. Just remove it from the profile.
try
{
database.SetMemberForumAccountId (member.MemberId, 0);
}
catch (Exception e2)
{
ExceptionMail.Send (e2);
}
}
}
// Now that we have flagged all member accounts as member accounts, flag the rest as
// non-party members.
int[] accountIds = forumDatabase.GetAccountList();
foreach (int accountId in accountIds)
{
if (!memberAccounts.ContainsKey (accountId))
{
if (forumDatabase.IsPartyMember (accountId))
{
forumDatabase.SetPartyNonmember (accountId);
}
}
}
}
}
}
+97
View File
@@ -0,0 +1,97 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Activizr.Logic.Support;
namespace Activizr.Utility.BotCode
{
public class HeartBeater
{
static private HeartBeater instance = null;
static private object lockObject = new object();
private bool FlagRestartRequested = false;
private DateTime lastBeat = DateTime.MinValue;
private string lastFilename = "";
public void Beat ()
{
Beat(lastFilename);
}
public void Beat (string filename)
{
lock (lockObject)
{
lastFilename = filename;
}
if ((DateTime.Now.Subtract(lastBeat).TotalSeconds > 10)
&& (this.FlagRestartRequested == false))
{
try
{
this.lastBeat = DateTime.Now;
string nowString = this.lastBeat.ToString();
Persistence.Key["PirateBot-L-Heartbeat"] = nowString;
if (nowString == Persistence.Key["PirateBot-L-Heartbeat"])
{
writeFile(filename, DateTime.Now.ToString());
}
else
{
this.SuggestRestart();
throw new Exception("Failed to update HeartBeat");
}
}
catch (Exception e)
{
this.SuggestRestart();
throw new Exception("Failed to update HeartBeat", e);
}
}
}
public void SuggestRestart ()
{
if (!File.Exists("./piratebotexit.flag"))
File.Create("./piratebotexit.flag");
this.FlagRestartRequested = true;
}
public bool WasKilled
{
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);
writeStream.Write(content);
writeStream.Close();
}
}
}
+187
View File
@@ -0,0 +1,187 @@
using System;
using System.Collections.Generic;
using System.Text;
using Activizr.Logic.Governance;
using Activizr.Logic.Pirates;
using Activizr.Logic.Structure;
namespace Activizr.Utility.BotCode
{
public class InternalPollMaintenance
{
static public void Run()
{
MeetingElections polls = MeetingElections.GetAll();
foreach (MeetingElection poll in polls)
{
Console.Write("Looking at poll #" + poll.Identity.ToString() + "...");
if (DateTime.Now > poll.VotingCloses)
{
Console.Write(" after closedatetime " + poll.VotingCloses.ToString("yyyy-MM-dd HH:mm") + "...");
// Poll should be CLOSED, definitely CLOSED.
if (poll.VotingOpen)
{
Console.WriteLine(" CLOSING.");
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);
ReportPollResults(poll, false);
}
else
{
Console.WriteLine(" no action.");
}
}
else if (DateTime.Now > poll.VotingOpens)
{
try
{
// 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)
{
Console.Write("\r - voters: {0:D6}/{1:D6} (person #{2:D6})...", ++count, memberships.Count, membership.PersonId);
if (!membership.Active)
{
continue; // paranoid programming
}
if (!membership.Organization.IsOrInherits(poll.Organization))
{
continue; // more paranoid programming
}
if (!dupeCheck.ContainsKey(membership.PersonId))
{
if (membership.Person.GeographyId == 0)
{
// 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.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);
}
}
catch (Exception exception)
{
Console.WriteLine(exception.ToString());
throw exception;
}
}
}
}
static private void ReportPollResults (MeetingElection poll, bool stillOpen)
{
SchulzeProcessor processor = new SchulzeProcessor();
processor.Candidates = poll.Candidates;
processor.Votes = MeetingElectionVotes.ForInternalPoll(poll);
processor.Process();
MailRawElectionResults(poll, processor, stillOpen);
}
private static void MailRawElectionResults(MeetingElection poll, SchulzeProcessor processor, bool stillOpen)
{
MeetingElectionCandidates candidates = processor.FinalOrder;
Dictionary<int, bool> dropoutLookup = new Dictionary<int, bool>();
// TODO SOMETIME: implement and populate dropouts here
string body = "These are " + (stillOpen ? "intermediate" : "THE FINAL") + " results for the poll \"" +
poll.Name +
"\". Note that the Dist field is purely informative and not part of the Schulze ranking.\r\n\r\n";
body += "Rank Dist Candidate\r\n";
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);
}
int[] recipients = new int[] { 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;
foreach (int personId in recipients)
{
Person.FromIdentity(personId).SendNotice(
subject, body, Organization.PPSEid);
}
}
}
}
+24
View File
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Text;
using Activizr.Logic.Governance;
namespace Activizr.Utility.BotCode
{
public class InternalPollRandomizer
{
// Randomizes the order of candidates on the open polls.
static public void Run()
{
// TODO: Foreach open poll...
MeetingElectionCandidates candidates = MeetingElectionCandidates.ForPoll(MeetingElection.Primaries2010);
foreach (MeetingElectionCandidate candidate in candidates)
{
candidate.RandomizeSortOrder();
}
}
}
}
+717
View File
@@ -0,0 +1,717 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text;
using System.Net.Mail;
using System.Net.Mime;
using Activizr.Basic;
using Activizr.Basic.Enums;
using Activizr.Utility.Mail;
using Activizr.Basic.Diagnostics;
using Activizr.Logic.Communications;
using Activizr.Logic.Media;
using Activizr.Logic.Pirates;
using Activizr.Logic.Support;
using System.Threading;
namespace Activizr.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)
: base(message, innerException)
{ }
}
public class InvalidRecipientException : IgnoreRecipientException
{
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)
: base(message, innerException)
{ }
}
#endregion
static Activizr.Logic.Support.QuotedPrintable qpUTF8 = new Activizr.Logic.Support.QuotedPrintable(Encoding.UTF8);
static Activizr.Logic.Support.QuotedPrintable qp8859 = new Activizr.Logic.Support.QuotedPrintable(Encoding.GetEncoding("ISO-8859-1"));
static Dictionary<Encoding, Activizr.Logic.Support.QuotedPrintable> QuotedPrintableEncoder = InitQpDictionary();
#region Static initialisation
static private Dictionary<Encoding, Activizr.Logic.Support.QuotedPrintable> InitQpDictionary ()
{
Dictionary<Encoding, Activizr.Logic.Support.QuotedPrintable> qp = new Dictionary<Encoding, Activizr.Logic.Support.QuotedPrintable>();
qp[Encoding.UTF8] = qpUTF8;
qp[Encoding.GetEncoding("ISO-8859-1")] = qp8859;
return qp;
}
#endregion
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.)
lock (lockObject)
{
if (mailQueueSize > 0)
{
// return;
}
}
// Look for a mail to process, or keep processing.
OutboundMails mails = OutboundMails.GetTopUnprocessed(100);
mailQueueSize = 0;
if (mails.Count == 0)
{
// no unprocessed mail, everybody's happy
return;
}
int maxBatchSize = 20; // Total number of recipients to process across all mails
foreach (OutboundMail mail in mails)
{
// If we have already processed past our limit, return for now.
if (maxBatchSize < 1)
{
return;
}
// We are continuing to process, and starting with a fresh outbound mail.
// Is this the first time we touch this mail?
if (mail.StartProcessDateTime.Year < 2000)
{
// 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
{
string mailBody = string.Empty;
new MailTransmitter(
Strings.MailSenderName, Strings.MailSenderAddress, "Mail transmission begins: " + mail.Title,
mailBody, Person.FromIdentity(mail.AuthorPersonId), true).Send();
}
}
int batchSize = maxBatchSize;
// If we are debugging, and stepping through this program, avoid the misery of many simultaneous threads.
if (System.Diagnostics.Debugger.IsAttached)
{
batchSize = 1; // Do NOT multithread while debugging
}
while (true)
{
if (!System.Diagnostics.Debugger.IsAttached)
{
HeartBeater.Instance.Beat();
//Tick the heartbeat to stop exernal restart if this takes a lot of time, but only if not debugging.
}
OutboundMailRecipients recipients = mail.GetNextRecipientBatch(batchSize);
maxBatchSize -= recipients.Count; // Decrement number of recipients to process on next mail, if any
if (recipients.Count == 0)
{
// This mail is complete!
mail.SetProcessed();
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") +
" 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(
Strings.MailSenderName, Strings.MailSenderAddress,
"Mail transmission completed: " + mail.Title, body, Person.FromIdentity(mail.AuthorPersonId),
true).Send();
}
if (maxBatchSize < 1)
{
return;
}
break; //the while loop
}
else
{
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))
{
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++;
}
System.Threading.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)
{
IAsyncResult iares = sendInProgress[i];
MailTransmissionAsyncState asyncState = (MailTransmissionAsyncState)iares.AsyncState;
if (asyncState.dlgt != null)
{
if (!asyncState.callbackCompleted)
{
waitHandlesList.Add(iares.AsyncWaitHandle);
numberStillExecuting++;
}
else
{
//Just finalised
if (asyncState.exception != null)
{
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
{
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++;
}
}
}
}
}
}
}
if (numberExecutingLast != numberStillExecuting)
lastProgress = DateTime.Now;
numberExecutingLast = numberStillExecuting;
if (lastProgress.AddSeconds(60 * 2) < DateTime.Now)
{
// since last change, something must have hanged
lock (lockObject)
{
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)
{
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;
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;
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;
throw new IgnoreRecipientException(msg, null);
}
// Otherwise, let's start processing
OutboundMail mail = recipient.OutboundMail;
bool limitToLatin1 = false;
bool limitToText = false;
Encoding currentEncoding = Encoding.UTF8;
string email = recipient.EmailPerson.Email.ToLower();
if (mail.MailType == 0 || mail.TemplateName.EndsWith("Plain"))
limitToText = true;
// TEST: Does this user require the use of a text-only message (as opposed to multipart/alternative)?
if (recipient.Person != null && recipient.Person.LimitMailToText)
{
limitToText = true;
}
// This is supposedly not a problem anymore
//if (email.EndsWith("@hotmail.com") || email.EndsWith("@msn.com"))
//{
// limitToLatin1 = true;
//}
// TEST: Does this user require the limited use of the Latin-1 charset (as opposed to Unicode?)
if (recipient.Person != null && recipient.Person.LimitMailToLatin1)
{
limitToLatin1 = true;
}
// Capability tests end here
if (limitToLatin1)
currentEncoding = Encoding.GetEncoding("ISO-8859-1");
else
currentEncoding = Encoding.UTF8;
Activizr.Logic.Support.QuotedPrintable qp = QuotedPrintableEncoder[currentEncoding];
MailMessage message = new MailMessage();
if (mail.AuthorType == MailAuthorType.Person)
{
try
{
message.From = new MailAddress(mail.Author.PartyEmail,
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);
}
}
catch (Exception ex)
{
throw new InvalidSenderException("Invalid author address in MailProcessor.TransmitOneMail:" + (mail.AuthorPersonId).ToString() + ";" + 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);
}
catch (Exception ex)
{
throw new InvalidSenderException("Unknown MailAuthorType in MailProcessor.TransmitOneMail:" + ((int)mail.AuthorType).ToString(), ex);
}
}
if (recipient.AsOfficer && recipient.Person != null)
{
try
{
message.To.Add(new MailAddress(recipient.Person.PartyEmail,
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;
throw new InvalidRecipientException(msg, e);
}
}
else
{
try
{
message.To.Add(new MailAddress(recipient.EmailPerson.Email,
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;
throw new InvalidRecipientException(msg, e);
}
}
string culture = mail.Organization.DefaultCountry.Culture;
// UGLY UGLY UGLY HACK, NEEDS TO CHANGE ASAP:
// We need to determine the culture of the recipient in order to use the right template. However, this is also dependent on the text body, which needs to be
// in the same culture. At this point, we don't have the mail/recipient cultures in the schema. This would be the correct solution.
// The INCORRECT but working solution is to do as we do here and check if a) it's a reporter and b) the reporter has International/English as a category. If so,
// we change the culture to en-US. It's an ugly as all hell hack but it should work as a temporary stopgap.
if (recipient.Reporter != null)
{
MediaCategories categories = recipient.Reporter.MediaCategories;
foreach (MediaCategory category in categories)
{
if (category.Name == "International/English")
{
culture = Strings.InternationalCultureCode;
break;
}
}
}
if (limitToText)
{
// if just text, then just add a plaintext body;
string text = "";
//Cant really see any reson the HtmlAgilityPack shouldn't be thread safe, but what the heck, just in case..
lock (lockObject)
{
try
{
text = mail.RenderText(recipient.EmailPerson, culture);
}
catch (Exception ex)
{
throw new RemoveRecipientException("TextRendering failed for " + mail.Title + " to " + recipient.EmailPerson.Email + " will not retry.\n", ex);
}
}
message.BodyEncoding = currentEncoding;
message.Body = text;
}
else
{
// otherwise, add a multipart/alternative with text and HTML
string text = "";
string html = "";
//Cant really see any reson the HtmlAgilityPack shouldn't be thread safe, but what the heck, just in case..
Exception ex = null;
lock (lockObject)
{
try
{
text = mail.RenderText(recipient.EmailPerson, culture);
html = mail.RenderHtml(recipient.EmailPerson, culture);
}
catch (Exception e)
{
ex = e;
}
}
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);
ContentType textContentType = new ContentType(MediaTypeNames.Text.Plain);
textContentType.CharSet = currentEncoding.BodyName;
ContentType htmlContentType = new ContentType(MediaTypeNames.Text.Html);
htmlContentType.CharSet = currentEncoding.BodyName;
AlternateView textView = null;
AlternateView htmlView = null;
if (limitToLatin1)
{
textView = new AlternateView(new MemoryStream(currentEncoding.GetBytes(text)), textContentType);
htmlView = new AlternateView(new MemoryStream(currentEncoding.GetBytes(text)), htmlContentType);
}
else
{
textView = AlternateView.CreateAlternateViewFromString(text, textContentType);
htmlView = AlternateView.CreateAlternateViewFromString(html, htmlContentType);
}
// A fucking stupid Mono bug forces us to transfer-encode in base64: it can't encode qp properly
// (the "=" is not encoded to "=3D")
htmlView.TransferEncoding = TransferEncoding.Base64;
textView.TransferEncoding = TransferEncoding.Base64;
// Add the views in increasing order of preference
message.AlternateViews.Add(textView);
message.AlternateViews.Add(htmlView);
}
if (mail.AuthorType == MailAuthorType.PirateWeb)
{
message.Subject = mail.Title;
}
else if (mail.MailType == 0)
{
message.Subject = mail.Organization.MailPrefixInherited + ": " + mail.Title;
}
else
{
//Title is set up in template processing in OutboundMail rendering.
message.Subject = mail.Title;
}
message.SubjectEncoding = currentEncoding;
string smtpServer = ConfigurationManager.AppSettings["SmtpServer"];
if (System.Diagnostics.Debugger.IsAttached)
{
System.Diagnostics.Debug.WriteLine("sending " + message.Subject + " to " + recipient.EmailPerson.Email);
System.Threading.Thread.Sleep(200); //simulate delay
}
if (smtpServer.ToLower() != "none")
{
if (smtpServer == null || smtpServer.Length < 2)
{
smtpServer = "localhost";
}
try
{
SmtpClient client = new SmtpClient(smtpServer, 25);
client.Send(message);
}
catch (SmtpException e)
{
if (e.ToString().StartsWith("System.Net.Mail.SmtpException: 4"))
{
// Temporary error (SMTP 4xx). Try again.
System.Threading.Thread.Sleep(2000); // Allow 2 seconds pause to wait for smtp-server to become available
throw new ReportAndRetryRecipientException("Temporary smtp error, will retry.", e);
}
// Otherwise, bad recipient (assume so). Have the mail removed from the queue.
List<string> recipients = new List<string>();
foreach (MailAddress address in message.To)
{
recipients.Add(address.Address);
}
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);
}
catch (Exception ex)
{
throw new Exception("Failed to SendOfficerNotice to :" + mail.AuthorPersonId.ToString(), ex);
}
}
}
}
return recipient; // To pass this object onto the we're-done callback
}
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
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
internal static void MailSent (IAsyncResult result)
{
lock (lockObject)
{
MailTransmissionAsyncState asyncState = (MailTransmissionAsyncState)result.AsyncState;
MailTransmissionDelegate asyncTransmitter = asyncState.dlgt;
OutboundMailRecipient recipient = asyncState.recipient;
try
{
asyncTransmitter.EndInvoke(result);
try
{
recipient.Delete();
recipient.OutboundMail.IncrementSuccesses();
}
catch (Exception ex)
{
// whatever.. The mail is sent, but we couldn't mark it as such, probably a database failure.
asyncState.exception = new RemoveRecipientException("Couldn't remove mail recipient.", ex);
ExceptionMail.Send(asyncState.exception, true);
}
}
catch (ReportAndRetryRecipientException e)
{
asyncState.exception = e;
System.Diagnostics.Debug.WriteLine(e.ToString());
ExceptionMail.Send(e, true);
}
catch (RetryRecipientException e)
{
// No action - handled in async delegate - retry this mail
asyncState.exception = e;
}
catch (Exception e)
{
asyncState.exception = e;
try
{
recipient.Delete();
recipient.OutboundMail.IncrementFailures();
if (e is InvalidRecipientException)
{
if (recipient.Person != null && recipient.Person.EMailIsInvalid == false)
{
//Mark address as invalid.
recipient.Person.EMailIsInvalid = true;
}
}
}
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);
ExceptionMail.Send(asyncState.exception, true); //Report the secondary exception
}
System.Diagnostics.Debug.WriteLine(e.ToString());
ExceptionMail.Send(e, true);
}
asyncState.callbackCompleted = true;
}
}
private static int mailQueueSize;
private static Object lockObject = new Object();
}
}
+301
View File
@@ -0,0 +1,301 @@
using System;
using System.Collections.Generic;
using System.Text;
using Activizr.Basic.Enums;
using Activizr.Logic.Communications;
using Activizr.Utility.Mail;
using Activizr.Logic.Pirates;
using Activizr.Logic.Structure;
using Activizr.Logic.Support;
namespace Activizr.Utility.BotCode
{
public class MailResolver
{
public static void Run ()
{
OutboundMail mail = OutboundMail.GetFirstUnresolved();
if (mail == null)
{
return; // No unresolved -- nothing to do
}
// Use a dictionary to add people
int downwardCount = 0;
int upwardCount = 0;
Dictionary<int, bool> officerIds = new Dictionary<int, bool>();
Dictionary<int, bool> personIds = new Dictionary<int, bool>();
// Add the affected people
switch (mail.MailType)
{
case (int)TypedMailTemplate.TemplateType.MemberMail:
// All members at this org and geography
People people = People.FromOrganizationAndGeography(mail.OrganizationId, mail.GeographyId);
downwardCount = people.Count;
foreach (Person person in people)
{
personIds[person.Identity] = true;
}
break;
case (int)TypedMailTemplate.TemplateType.OfficerMail:
// All officers at this org and geography
int[] officers = Roles.GetAllDownwardRoles(mail.OrganizationId, mail.GeographyId);
downwardCount = officers.Length;
foreach (int personId in officers)
{
officerIds[personId] = true;
}
break;
default:
throw new InvalidOperationException("Unhandled mail mode; can't resolve mail id " +
mail.Identity.ToString());
}
int[] upwardIds = Roles.GetAllUpwardRoles(mail.OrganizationId, mail.GeographyId);
upwardCount = upwardIds.Length;
foreach (int personId in upwardIds)
{
// Filter for subscription of copies to local mail. Inefficient filter, room for optimization.
if (Person.FromIdentity(personId).IsSubscribing(NewsletterFeed.TypeID.OfficerUpwardCopies))
{
officerIds[personId] = true;
}
}
// Assemble arrays
List<int> officerIdList = new List<int>();
foreach (int officerId in officerIds.Keys)
{
officerIdList.Add(officerId);
if (personIds.ContainsKey(officerId))
{
// If somebody is going to recieve this mail both due to area coverage and
// chain of command, send as chain of command only
personIds.Remove(officerId);
}
}
List<int> personIdList = new List<int>();
foreach (int personId in personIds.Keys)
{
personIdList.Add(personId);
}
// Check for people who have declined local mail
Dictionary<int, bool> decliners = new Dictionary<int, bool>();
//HACK: invitation to member meeting should be sent out to ALL members for PPSE
if (mail.Author.PartyEmail.ToLower() != "motespresidiet@piratpartiet.se"
|| mail.GeographyId != Geography.RootIdentity
|| mail.OrganizationId != Organization.PPSEid)
{
decliners = Optimizations.GetPeopleWhoDeclineLocalMail(personIdList.ToArray());
}
int declineCount = decliners.Count;
if (declineCount > 0)
{
foreach (int personId in decliners.Keys)
{
personIds.Remove(personId);
}
// Rebuild list after decliners gone
personIdList = new List<int>();
foreach (int personId in personIds.Keys)
{
personIdList.Add(personId);
}
}
// TODO: Get queue count to give a time estimate until transmission
// Create recipients
mail.AddRecipients(personIdList.ToArray(), false);
mail.AddRecipients(officerIdList.ToArray(), true);
int countTotal = personIdList.Count + officerIdList.Count;
// Mark as ready
mail.SetRecipientCount(countTotal);
mail.SetResolved();
// TODO: Set recipient count of mail
// Create a mail to the author
string mailBody = "Your outbound mail with the title \"" + mail.Title +
"\" has been resolved for recipients and " +
"will be sent to " + countTotal.ToString("#,##0") + " people.\r\n\r\nOut of these " +
countTotal.ToString("#,##0") + ", " + (downwardCount - declineCount).ToString("#,##0") +
" are people within the requested " +
"organization/geography (" + Organization.FromIdentity(mail.OrganizationId).Name + "/" +
Geography.FromIdentity(mail.GeographyId).Name + "), and " +
upwardCount.ToString("#,##0") + " are people in the chain of command who are " +
"copied on the mail to know what's happening in the organization. There is normally some overlap between these two groups.\r\n\r\n";
if (declineCount > 1)
{
mailBody += declineCount.ToString("#,##0") +
" people will not receive the message because they have declined local mail.\r\n\r\n";
}
else if (declineCount == 1)
{
mailBody += "One person will not receive the message because he or she has declined local mail.\r\n\r\n";
}
mailBody +=
"Transmissions will begin " + (mail.ReleaseDateTime < DateTime.Now
? "immediately"
:
"in " + (mail.ReleaseDateTime - DateTime.Now).Minutes.ToString() +
" minutes") + ".\r\n";
new MailTransmitter(
"PirateWeb", "noreply@pirateweb.net",
"Mail resolved: " + mail.Title + " (" + countTotal.ToString() + " recipients)", mailBody,
Person.FromIdentity(mail.AuthorPersonId), true).Send();
}
static private People ApplySubscription (People input, int feedId)
{
People output = new People();
foreach (Person person in input)
{
if (person.IsSubscribing(feedId))
{
output.Add(person);
}
}
return output;
}
public static string CreateWelcomeMail (Person person, Organization organization)
{
// for this person, iterate over all applicable geographies and organizations
Organizations orgLine = organization.GetLine();
Geographies geoLine = person.Geography.GetLine();
orgLine.Reverse(); // Start at the most local org
Dictionary<int,bool> orgMailedLookup = new Dictionary<int, bool>();
int delay = 0;
string result = string.Empty;
Random random = new Random();
foreach (Organization org in orgLine)
{
foreach (Geography geo in geoLine) // but at the top geography
{
AutoMail autoMail = AutoMail.FromTypeOrganizationAndGeography(AutoMailType.Welcome, org, geo);
if (autoMail == null)
{
continue;
}
Person lead = null;
string geoName = geo.Name;
try
{
lead = Roles.GetLocalLead(org, geo);
orgMailedLookup[org.Identity] = true; // Make sure that the chairman doesn't mail at a lower level
}
catch (ArgumentException)
{
}
if (lead == null && !orgMailedLookup.ContainsKey(org.Identity))
{
// 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;
lead = Roles.GetChairman(org);
geoName = "Chairman";
}
catch (ArgumentException)
{
}
}
if (lead == null)
{
// ok, give up if there isn't a chairman either or if we've already mailed this org from the chairman
continue;
}
// TODO: fetch lead from roles
WelcomeMail welcomemail = new WelcomeMail();
welcomemail.pOrgName = org.MailPrefixInherited;
welcomemail.pGeographyName = "";
if (geo.Identity != Geography.RootIdentity)
{
welcomemail.pGeographyName = geo.Name;
}
welcomemail.pBodyContent = autoMail.Body;
welcomemail.pSubject = autoMail.Title;
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);
if (delay == 0)
{
result += "sent now";
delay += 37;
}
else
{
result += "sending at " + DateTime.Now.AddMinutes(delay).ToString("HH:mm");
delay += 31 + random.Next(52);
}
result += ")\r\n";
}
}
if (result.Length < 4)
{
result = "none\r\n";
}
return result;
}
}
}
+528
View File
@@ -0,0 +1,528 @@
using System;
using System.Drawing;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using Activizr.Basic.Enums;
using Activizr.Logic.Pirates;
using Activizr.Logic.Structure;
using Activizr.Logic.Support;
namespace Activizr.Utility.BotCode
{
public class Mappery
{
public static void CreateUngPiratUptakeMap()
{
string svg = string.Empty;
string legendTemplate = string.Empty;
using (
StreamReader reader = new StreamReader("content/se-up-uptake-municipalities-template.svg",
Encoding.Default))
{
svg = reader.ReadToEnd();
}
using (
StreamReader reader = new StreamReader("content/se-up-uptakemap-legend-template.txt", Encoding.Default))
{
legendTemplate = reader.ReadToEnd();
}
Organizations effectiveOrgs = new Organizations();
Organizations possibleOrgs = Organization.FromIdentity(2).GetTree();
foreach (Organization org in possibleOrgs)
{
if (org.AcceptsMembers && org.AutoAssignNewMembers)
{
effectiveOrgs.Add(org);
}
}
string legend = string.Empty;
effectiveOrgs.Sort();
Dictionary<int, string> colorLookup = new Dictionary<int, string>();
int position = 0;
float curLight = .35f;
float curSaturation = 1f;
foreach (Organization org in effectiveOrgs)
{
curLight += .25f;
if (curLight > .85f)
{
curLight = .35f;
}
else if (curLight > .8f)
{
curLight = .75f;
}
curSaturation = 1.45f - curSaturation;
Color color = ColorFromAhsb(128, (float) position*360/(float) effectiveOrgs.Count, curSaturation,
curLight);
if (org.CatchAll)
{
color = Color.FromArgb(240, 240, 240);
}
string colorString = String.Format("#{0:x2}{1:x2}{2:x2}", color.R, color.G, color.B);
colorLookup[org.Identity] = colorString;
string orgLegend = legendTemplate.
Replace("%%NAME%%", Encoding.Default.GetString(Encoding.UTF8.GetBytes(org.NameShort))).
Replace("%%YPOS%%", (position*17).ToString()).
Replace("%%COLOR%%", colorString).
Replace("%%GROUPID%%", "org" + org.Identity.ToString());
legend += orgLegend;
position++;
}
Mappery mappery = new Mappery();
mappery.OrgColorLookup = colorLookup; // Ugly way to transfer data to delegate
svg = svg.Replace("<!--%%LEGEND%%-->", legend);
Regex regex =
new Regex("(?<start>\\<path.+?fill:)(?<color>.+?)(?<middle>;.+?id=\\\")(?<id>.+?)(?<end>\\\".+?/\\>)",
RegexOptions.Singleline);
MatchEvaluator matchEvaluator = new MatchEvaluator(mappery.UPUptakeLookupReplacer);
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)
{
string resultColor = "#000000";
string id = match.Groups["id"].Value;
if (!id.StartsWith("text"))
{
Geography geo = Geography.FromOfficialDesignation(1, GeographyLevel.Municipality, id);
Organization org = Organizations.GetMostLocalOrganization(geo.Identity, Organization.UPSEid);
resultColor = OrgColorLookup[org.Identity];
}
return match.Groups["start"].Value + resultColor + match.Groups["middle"].Value + id +
match.Groups["end"].Value;
}
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));
}
float fMax, fMid, fMin;
int iSextant, iMax, iMid, iMin;
if (0.5 < b)
{
fMax = b - (b*s) + s;
fMin = b + (b*s) - s;
}
else
{
fMax = b + (b*s);
fMin = b - (b*s);
}
iSextant = (int) Math.Floor(h/60f);
if (300f <= h)
{
h -= 360f;
}
h /= 60f;
h -= 2f*(float) Math.Floor(((iSextant + 1f)%6f)/2f);
if (0 == iSextant%2)
{
fMid = h*(fMax - fMin) + fMin;
}
else
{
fMid = fMin - h*(fMax - fMin);
}
iMax = Convert.ToInt32(fMax*255);
iMid = Convert.ToInt32(fMid*255);
iMin = Convert.ToInt32(fMin*255);
switch (iSextant)
{
case 1:
return Color.FromArgb(a, iMid, iMax, iMin);
case 2:
return Color.FromArgb(a, iMin, iMax, iMid);
case 3:
return Color.FromArgb(a, iMin, iMid, iMax);
case 4:
return Color.FromArgb(a, iMid, iMin, iMax);
case 5:
return Color.FromArgb(a, iMax, iMin, iMid);
default:
return Color.FromArgb(a, iMax, iMid, iMin);
}
}
public static void CreatePiratpartietOrganizationStrengthCircuitMap()
{
string svg = string.Empty;
using (
StreamReader reader = new StreamReader("content/se-circuits-orgstrength-template.svg", Encoding.Default)
)
{
svg = reader.ReadToEnd();
}
Regex regex =
new Regex("(?<start>\\<path.+?fill:)(?<color>.+?)(?<middle>;.+?id=\\\")(?<id>.+?)(?<end>\\\".+?/\\>)",
RegexOptions.Singleline);
MatchEvaluator matchEvaluator = new MatchEvaluator(new Mappery().SwedishCircuitMapOrgStrengthLookupReplacer);
Persistence.Key["CircuitOrgStrength-1"] = regex.Replace(svg, matchEvaluator);
}
public static void CreatePiratpartietOrganizationStrengthCityMap()
{
string svg = string.Empty;
using (
StreamReader reader = new StreamReader("content/se-municipalities-orgstrength-template.svg",
Encoding.Default))
{
svg = reader.ReadToEnd();
}
svg = svg.Replace("%COUNT%", GetCityLeadCount(1, 1).ToString());
Regex regex =
new Regex("(?<start>\\<path.+?fill:)(?<color>.+?)(?<middle>;.+?id=\\\")(?<id>.+?)(?<end>\\\".+?/\\>)",
RegexOptions.Singleline);
MatchEvaluator matchEvaluator = new MatchEvaluator(new Mappery().SwedishCityMapOrgStrengthLookupReplacer);
Persistence.Key["CityOrgStrength-1"] = regex.Replace(svg, matchEvaluator);
}
public static int GetCityLeadCount (int organizationId, int countryId)
{
Geographies cities = Geographies.FromLevel(countryId, GeographyLevel.Municipality);
int leadCount = 0;
foreach (Geography city in cities)
{
RoleLookup roles = RoleLookup.FromGeographyAndOrganization(city.Identity, organizationId);
if (roles[RoleType.LocalLead].Count > 0)
{
leadCount++;
}
}
return leadCount;
}
public string SwedishCircuitMapOrgStrengthLookupReplacer (Match match)
{
// Five groups: "color" and "id" are the keys, "start", "middle" and "end" are what to paste in between.
Dictionary<string, int> lookup = new Dictionary<string, int>();
lookup["2N"] = 2;
lookup["2S"] = 38;
lookup["1"] = 40;
Organization org = Organization.FromIdentity(1); // Replace later for more generic
string resultColorString = "#000000";
string id = match.Groups["id"].Value;
int geoId = 0;
try
{
if (lookup.ContainsKey(id))
{
geoId = lookup[id];
}
else
{
geoId = Int32.Parse(id);
}
Geography geo = Geography.FromIdentity(geoId);
RoleLookup officers = RoleLookup.FromGeographyAndOrganization(geo.Identity, org.Identity);
bool hasLead = officers[RoleType.LocalLead].Count > 0;
bool hasSecond = officers[RoleType.LocalDeputy].Count > 0;
Geographies geoTree = geo.GetTree();
int cities = 0;
int citiesWithLead = 0;
foreach (Geography localGeo in geoTree)
{
if (localGeo.Identity == geo.Identity)
{
continue;
}
if (localGeo.Name.EndsWith("kommun"))
{
cities++;
officers = RoleLookup.FromGeographyAndOrganization(localGeo.Identity, org.Identity);
if (officers[RoleType.LocalLead].Count > 0)
{
citiesWithLead++;
}
}
}
int cityLeadPercent = 100;
if (cities > 0)
{
cityLeadPercent = citiesWithLead*100/cities;
}
// Determine color
Color color = Color.Red;
if (!hasLead)
{
color = Color.Red;
}
else if (cityLeadPercent > 80 && hasSecond)
{
color = Color.Green;
}
else
{
// Find a hue between Orange and Light Green. Say, between 30 and 120.
cityLeadPercent += 30;
if (cityLeadPercent > 120)
{
cityLeadPercent = 120;
}
color = ColorFromAhsb(100, cityLeadPercent, 1.0f, 0.5f);
}
resultColorString = String.Format("#{0:x2}{1:x2}{2:x2}", color.R, color.G, color.B);
}
catch (Exception)
{
// Ignore - color will be black
}
return match.Groups["start"].Value + resultColorString + match.Groups["middle"].Value + id +
match.Groups["end"].Value;
}
public string SwedishCityMapOrgStrengthLookupReplacer (Match match)
{
// Five groups: "color" and "id" are the keys, "start", "middle" and "end" are what to paste in between.
Organization org = Organization.FromIdentity(1); // Replace later for more generic
string resultColorString = "#000000";
string id = match.Groups["id"].Value;
// If not constructed for this instance, construct the volunteer cache
if (this.volunteerCache == null)
{
this.volunteerCache = new Dictionary<int, bool>();
Volunteers volunteers = Volunteers.GetOpen();
foreach (Volunteer volunteer in volunteers)
{
volunteerCache[volunteer.Geography.Identity] = true;
}
}
try
{
Geography geo = Geography.FromOfficialDesignation(1, GeographyLevel.Municipality, id);
int circuitLeadCount = 0;
int cityLeadCount = 0;
int cityVolunteerCount = 0;
RoleLookup lookup = RoleLookup.FromGeographyAndOrganization(geo.Identity, 1);
if (lookup[RoleType.LocalLead].Count > 0)
{
cityLeadCount = 1;
if (lookup[RoleType.LocalDeputy].Count > 0)
{
cityLeadCount = 2;
}
}
if (volunteerCache.ContainsKey(geo.Identity))
{
cityVolunteerCount = 1;
}
// Move up to circuit level
while (!(geo.AtLevel(GeographyLevel.ElectoralCircuit)))
{
geo = geo.Parent;
}
lookup = RoleLookup.FromGeographyAndOrganization(geo.Identity, 1);
if (lookup[RoleType.LocalLead].Count > 0)
{
circuitLeadCount = 1;
if (lookup[RoleType.LocalDeputy].Count > 0)
{
circuitLeadCount = 2;
}
}
float saturation = 1.0f;
float brightness = 0.15f + 0.2f*circuitLeadCount;
float hue = cityLeadCount*60; // red, yellow, green hues at 0°, 60°, 120°
if (cityLeadCount < 2 && cityVolunteerCount > 0)
{
hue += 30; // There are volunteers? Place at orange (for none) or yellow-green (for one).
}
Color color = ColorFromAhsb(255, hue, saturation, brightness);
resultColorString = String.Format("#{0:x2}{1:x2}{2:x2}", color.R, color.G, color.B);
}
catch (Exception)
{
}
/*
try
{
if (lookup.ContainsKey(id))
{
geoId = lookup[id];
}
else
{
geoId = Int32.Parse(id);
}
Geography geo = Geography.FromIdentity(geoId);
RoleLookup officers = RoleLookup.FromGeographyAndOrganization(geo.Identity, org.Identity);
bool hasLead = officers[RoleType.LocalLead].Count > 0;
bool hasSecond = officers[RoleType.LocalDeputy].Count > 0;
Geographies geoTree = geo.GetTree();
int cities = 0;
int citiesWithLead = 0;
foreach (Geography localGeo in geoTree)
{
if (localGeo.Identity == geo.Identity)
{
continue;
}
if (localGeo.Name.EndsWith("kommun"))
{
cities++;
officers = RoleLookup.FromGeographyAndOrganization(localGeo.Identity, org.Identity);
if (officers[RoleType.LocalLead].Count > 0)
{
citiesWithLead++;
}
}
}
int cityLeadPercent = 100;
if (cities > 0)
{
cityLeadPercent = citiesWithLead * 100 / cities;
}
// Determine color
Color color = Color.Red;
if (!hasLead)
{
color = Color.Red;
}
else if (cityLeadPercent > 80 && hasSecond)
{
color = Color.Green;
}
else
{
// Find a hue between Orange and Light Green. Say, between 30 and 120.
cityLeadPercent += 30;
if (cityLeadPercent > 120)
{
cityLeadPercent = 120;
}
color = ColorFromAhsb(100, cityLeadPercent, 1.0f, 0.5f);
}
resultColorString = String.Format("#{0:x2}{1:x2}{2:x2}", color.R, color.G, color.B);
}
catch (Exception)
{
// Ignore - color will be black
}
*/
return match.Groups["start"].Value + resultColorString + match.Groups["middle"].Value + id +
match.Groups["end"].Value;
}
private Dictionary<int, bool> volunteerCache;
}
}
+68
View File
@@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using Activizr.Logic.Media;
using NRss;
namespace Activizr.Utility.BotCode
{
public class MediaWatcher
{
public class ReaderException : Exception
{
public ReaderException (string message, Exception innerException)
: base(message, innerException)
{ }
}
public static void Run ()
{
// Get keywords. Read Frisim. Parse. Store.
string[] keywords = MediaEntries.GetOldMediaKeywords();
foreach (string keyword in keywords)
{
// string rssUrl = String.Format("http://sesam.se/search/?c=m&q={0}&&output=rss", keyword.ToLower());
string rssUrl = String.Format("http://www.frisim.com/rss/?q={0}&k=nyheter", keyword.ToLower());
// Read the RSS URL into memory, then feed RssReader from a MemoryStream
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.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();
RssReader reader = new RssReader(resp.GetResponseStream());
try
{
Rss rss = reader.Read();
foreach (RssChannelItem item in rss.Channel.Items)
{
// We want the title, media name, link and pubdate.
string url = item.Link;
DateTime dateTime = item.PubDate;
string title = item.Title;
string mediaName = item.Categories[0].Name;
MediaEntry.CreateFromKeyword(keyword, mediaName, false, url, title, dateTime);
}
}
catch (Exception e)
{
throw new ReaderException("feed:" + rssUrl + "Status=" + resp.StatusCode, e);
}
finally
{
request.GetResponse().GetResponseStream().Close();
}
}
}
}
}
+256
View File
@@ -0,0 +1,256 @@
using System;
using System.Collections.Generic;
using System.Text;
using Activizr.Logic.Pirates;
using Activizr.Logic.Structure;
using Activizr.Logic.Support;
using Activizr.Utility.Mail;
using Activizr.Utility.Special.Sweden;
using Activizr.Logic.Special.Sweden;
using NRss;
using Activizr.Logic.Communications;
namespace Activizr.Utility.BotCode
{
public class NewsletterChecker
{
const int ForumIdTestPost = 262;//vBulletin, old forum was 326;
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>();
public static void Run ()
{
//TODO: This list should reside in database/by organisation and possibly geography.
CheckOneBlog("http://rickfalkvinge.se/feed", 1);
CheckOneBlog("http://christianengstrom.wordpress.com/feed", 5);
CheckOneBlog("http://opassande.se/index.php/feed/", 367);
CheckOneBlog("http://www.annatroberg.com/feed/", 11443);
}
private static void CheckOneBlog (string readerFeedUrl, int personId)
{
try
{
Person sender = Person.FromIdentity(personId);
string senderName = sender.Name + " (Piratpartiet)";
string senderAddress = sender.PartyEmail;
if (personId == 5)
{
senderName = "=?utf-8?Q?Christian_Engstr=C3=B6m_(Piratpartiet)?="; // compensate for Mono bug
}
if (personId == 1)
{
senderAddress = "rick.falkvinge@piratpartiet.se";
}
RssReader reader = new RssReader(readerFeedUrl);
People recipients = null;
DateTime highWaterMark = DateTime.MinValue;
string persistenceKey = "Newsletter-Highwater-" + personId.ToString();
string highWaterMarkString = Persistence.Key[persistenceKey];
try
{
highWaterMark = DateTime.Parse(highWaterMarkString);
}
catch (FormatException)
{
highWaterMark = DateTime.MinValue;
}
catch (Exception e)
{
throw new ReaderException("feed:" + readerFeedUrl, e);
}
try
{
Rss rss = reader.Read();
// TODO: Read the high water mark from db
foreach (RssChannelItem item in rss.Channel.Items)
{
// Ignore any items older than the highwater mark.
if (item.PubDate < highWaterMark)
{
continue;
}
// For each item, look for the "Nyhetsbrev" category.
bool publish = false;
foreach (RssCategory category in item.Categories)
{
if (category.Name.ToLowerInvariant() == "nyhetsbrev")
{
publish = true;
}
}
if (publish)
{
// Set highwater datetime mark. We do this first as a defense against mail floods, should something go wrong.
Persistence.Key[persistenceKey] = item.PubDate.AddMinutes(5).ToString();
// Verify that it was written correctly to database. This is defensive programming to avoid a mail flood.
if (DateTime.Parse(Persistence.Key[persistenceKey]) < item.PubDate)
{
throw new Exception(
"Unable to commit new highwater mark to database in NewsletterChecker.Run()");
}
bool testMode = false;
if (item.Title.ToLower().Contains("test"))
{
// Newsletter blog entry contains "test" in title -> testmode
testMode = true;
}
// Post to forum
string forumText = Blog2Forum(item.Content);
string mailText = Blog2Mail(item.Content);
int forumPostId = 0;
try
{
forumPostId = SwedishForumDatabase.GetDatabase().CreateNewPost(
testMode ? ForumIdTestPost : ForumIdNewsletter, sender,
"Nyhetsbrev " + DateTime.Today.ToString("yyyy-MM-dd"),
item.Title, forumText);
}
catch (Exception ex)
{
if (!System.Diagnostics.Debugger.IsAttached)
{ // ignore when debugging
throw ex;
}
}
// Establish people to send to, if not already done.
if (recipients == null || recipients.Count == 1)
{
recipients = People.FromNewsletterFeed(NewsletterFeed.TypeID.ChairmanBlog);
}
/*
* Disabled sending to activists -- this was done leading up to the election in 2009
*/
// Add activists (HACK)
// Should probably be better to select by organization, not geography.
/*
People activists = Activists.FromGeography(Country.FromCode("SE").Geography).People;
recipients = recipients.LogicalOr(activists);*/
// OVERRIDE: If this is a TEST newsletter, send ONLY to the originator
if (testMode)
{
recipients = People.FromSingle(sender);
item.Title += " [TEST MODE]";
}
//TODO: hardcoded Org & geo ... using PP & World
Organization org = Organization.PPSE;
Geography geo = Geography.Root;
NewsletterMail newslettermail = new NewsletterMail();
newslettermail.pSubject = item.Title;
newslettermail.pDate = DateTime.Now;
newslettermail.pForumPostUrl =
String.Format("http://vbulletin.piratpartiet.se/showthread.php?t={0}", forumPostId);
newslettermail.pBodyContent = Blog2Mail(item.Content);
newslettermail.pOrgName = org.MailPrefixInherited;
OutboundMail newMail = newslettermail.CreateOutboundMail(sender, OutboundMail.PriorityLow, org, geo);
int recipientCount = 0;
foreach (Person recipient in recipients)
{
if (!Formatting.ValidateEmailFormat(recipient.Email)
|| recipient.MailUnreachable
|| recipient.NeverMail)
{
continue;
}
++recipientCount;
newMail.AddRecipient(recipient, false);
}
newMail.SetRecipientCount(recipientCount);
newMail.SetResolved();
newMail.SetReadyForPickup();
}
}
}
finally
{
reader.Close();
}
}
catch (Exception ex)
{
lock (feedErrorSignaled)
{
if (!feedErrorSignaled.ContainsKey(readerFeedUrl) || feedErrorSignaled[readerFeedUrl].AddMinutes(60) < DateTime.Now)
{
feedErrorSignaled[readerFeedUrl] = DateTime.Now;
throw new ReaderException("NewsletterChecker got error " + ex.Message + "\n when checking feed:" + readerFeedUrl + "\n(feed will be continually checked, bu will not signal error again for an hour)", ex);
}
}
}
}
private static string Blog2Forum (string text)
{
return text.
Replace("<h3>", "<h2>").
Replace("</h3>", "</h2>").
Replace("<blockquote>", "[quote]").
Replace("</blockquote>", "[/quote]");
}
private static string Blog2Mail (string text)
{
return text.
Replace("<h3>", "<h2>").
Replace("</h3>", "</h2>").
Replace("&#8220;", "\"").
Replace("&#8221;", "\"").
Replace("&#8216;", "'").
Replace("&#8217;", "'").
Replace("&#8212;", "--").
Replace("&#8230;", "...");
}
}
}
+251
View File
@@ -0,0 +1,251 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using Activizr.Basic.Enums;
using Activizr.Logic.Media;
using Activizr.Logic.Pirates;
using Activizr.Logic.Support;
using Activizr.Utility.Mail;
using NRss;
using Activizr.Logic.Communications;
using Activizr.Logic.Structure;
namespace Activizr.Utility.BotCode
{
public class PressReleaseChecker
{
public static void Run ()
{
//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)
{
string persistenceKey = String.Format("Pressrelease-Highwater-{0}", persistAsKey);
DateTime highWaterMark = DateTime.MinValue;
RssReader reader = null;
try
{
string highWaterMarkString = Persistence.Key[persistenceKey];
if (string.IsNullOrEmpty(highWaterMarkString))
{
//Initialize highwatermark if never used
highWaterMark = DateTime.Now;
Persistence.Key[persistenceKey] = DateTime.Now.ToString();
}
else
{
try
{
highWaterMark = DateTime.Parse(highWaterMarkString);
}
catch (Exception ex)
{
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);
}
}
DateTime storedHighWaterMark = highWaterMark;
reader = new RssReader(readerUrl);
Rss rss = reader.Read();
foreach (RssChannelItem item in rss.Channel.Items)
{
// Ignore any items older than the highwater mark.
// Also ignore if older than two days
if (item.PubDate < highWaterMark || item.PubDate < DateTime.Now.AddDays(-2))
{
continue;
}
// This is an item we should publish.
// Set highwater datetime mark. We do this first, BEFORE processing, as a defense against mail floods,
// if should something go wrong and unexpected exceptions happen.
// We used to add 70 minutes as a defense against mistakes on DST switch in spring and fall (yes, it has happened), but have reduced to two.
if (item.PubDate > storedHighWaterMark)
{
Persistence.Key[persistenceKey] = item.PubDate.AddMinutes(2).ToString();
storedHighWaterMark = item.PubDate.AddMinutes(2);
// Verify that it was written correctly to database. This is defensive programming to avoid a mail flood,
// in case we can't write to the database for some reason.
string newStoredHighWaterString = "";
try
{
newStoredHighWaterString = Persistence.Key[persistenceKey];
DateTime temp = DateTime.Parse(newStoredHighWaterString);
}
catch (Exception ex)
{
throw new Exception(
"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)
{
throw new Exception(
"Unable to commit new highwater mark to database in PressReleaseChecker.Run()");
}
}
bool allReporters = false;
bool international = false;
MediaCategories categories = new MediaCategories();
foreach (RssCategory category in item.Categories)
{
if (category.Name == "Alla")
{
allReporters = true;
}
else if (category.Name == "Uncategorized")
{
continue;
}
else
{
try
{
MediaCategory mediaCategory = MediaCategory.FromName(category.Name);
categories.Add(mediaCategory);
if (category.Name.StartsWith("International"))
{
international = true;
}
}
catch (Exception)
{
ExceptionMail.Send(new Exception("Unrecognized media category in press release: " + category.Name));
}
}
}
string mailText = Blog2Mail(item.Content);
// Create recipient list of relevant reporters
Reporters reporters = null;
if (allReporters)
{
reporters = Reporters.GetAll();
}
else
{
reporters = Reporters.FromMediaCategories(categories);
}
// Add officers if not int'l
People officers = new People();
Dictionary<int, bool> officerLookup = new Dictionary<int, bool>();
if (!international)
{
int[] officerIds = Roles.GetAllDownwardRoles(1, 1);
foreach (int officerId in officerIds)
{
officerLookup[officerId] = true;
}
}
else
{
officerLookup[1] = true;
}
// Send press release
//TODO: hardcoded geo ... using World
Organization org = Organization.FromIdentity(orgIdForTemplate);
Geography geo = Geography.Root;
PressReleaseMail pressreleasemail = new PressReleaseMail();
pressreleasemail.pSubject = item.Title;
pressreleasemail.pDate = DateTime.Now;
pressreleasemail.pBodyContent = Blog2Mail(item.Content);
pressreleasemail.pOrgName = org.MailPrefixInherited;
if (allReporters)
{
pressreleasemail.pPostedToCategories = "Alla"; // TODO: TRANSLATE
}
else if (international)
{
pressreleasemail.pPostedToCategories = "International/English"; // TODO: THIS IS HARDCODED
}
else
{
pressreleasemail.pPostedToCategories = PressReleaseMail.GetConcatenatedCategoryString(categories);
}
OutboundMail newMail = pressreleasemail.CreateFunctionalOutboundMail(MailAuthorType.PressService, OutboundMail.PriorityHighest, org, geo);
int recipientCount = 0;
foreach (Reporter recipient in reporters)
{
if (!Formatting.ValidateEmailFormat(recipient.Email))
{
continue;
}
++recipientCount;
newMail.AddRecipient(recipient);
}
foreach (int key in officerLookup.Keys)
{
Person recipient = Person.FromIdentity(key);
if (!Formatting.ValidateEmailFormat(recipient.Email))
{
continue;
}
++recipientCount;
newMail.AddRecipient(recipient, true);
}
newMail.SetRecipientCount(recipientCount);
newMail.SetResolved();
newMail.SetReadyForPickup();
}
}
catch (Exception ex)
{
ExceptionMail.Send(new Exception("PressReleaseChecker failed:" + ex.Message + "\r\nwhen checking " + readerUrl, ex));
}
finally
{
reader.Close();
}
}
private static string Blog2Mail (string text)
{
return text.
Replace("<h3>", "<h2>").
Replace("</h3>", "</h2>").
Replace("&#8220;", "\"").
Replace("&#8221;", "\"").
Replace("&#8216;", "'").
Replace("&#8217;", "'").
Replace("&#8212;", "--").
Replace("&#8230;", "...");
}
}
}
+845
View File
@@ -0,0 +1,845 @@
using System;
using System.Collections.Generic;
using System.Text;
using Activizr.Basic;
using Activizr.Basic.Enums;
using Activizr.Basic.Types;
using Activizr.Database;
using Activizr.Utility.Mail;
using Activizr.Logic.Communications;
using Activizr.Logic.Pirates;
using Activizr.Logic.Security;
using Activizr.Logic.Structure;
using Activizr.Logic.Support;
using System.Diagnostics;
namespace Activizr.Utility.BotCode
{
public class RosterHousekeeping
{
// 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)
{
Organizations orgs = Organization.FromIdentity(organizationIdRoot).GetTree();
StringBuilder result = new StringBuilder();
result.Append(
String.Format("All members joining tree of " + orgs[0].Name + " between " +
membersAfter.ToString("yyyy-MMM-dd") + " and " + membersBefore.ToString("yyyy-MMM-dd") +
"\r\n\r\n"));
membersAfter = membersAfter.Date;
membersBefore = membersBefore.AddDays(1).Date;
foreach (Organization org in orgs)
{
if (org.AcceptsMembers)
{
Memberships memberships = org.GetMemberships();
string orgSummary = org.Name + "\r\n";
// Iterate over membership roster and filter by date
List<int> relevantPersonIds = new List<int>();
foreach (Membership membership in memberships)
{
if (membership.MemberSince > membersAfter && membership.MemberSince < membersBefore)
{
relevantPersonIds.Add(membership.PersonId);
}
}
People listMembers = People.FromIdentities(relevantPersonIds.ToArray());
List<string> csvResultList = new List<string>();
foreach (Person person in listMembers)
{
csvResultList.Add(
String.Format("{0},{1},{2},{3:yyyy-MMM-dd},{4}",
person.Name, person.Street, person.PostalCodeAndCity, person.Birthdate,
person.IsMale ? "Male" : "Female"));
}
string[] csvResults = csvResultList.ToArray();
Array.Sort(csvResults);
orgSummary += String.Join("\r\n", csvResults) + "\r\n\r\n";
result.Append(orgSummary);
}
}
return result.ToString();
}
// This should run daily.
public static void RemindAllExpiries ()
{
RemindExpiriesMail(); // Send on ALL days, but only if DayOfWeek == OrganizationId % 7. This scatters reminder mails.
//RemindExpiriesSms(DateTime.Now.AddDays(7).Date,
// "Piratpartiet: Ditt medlemskap går ut om bara ett par dagar. Svara på detta SMS med texten \"PP IGEN\" för att förnya (5 kr).");
RemindExpiriesSms(DateTime.Now.AddDays(1).Date,
"Piratpartiet: Ditt medlemskap går ut vid midnatt ikväll. Svara på detta SMS med texten \"PP IGEN\" för att förnya.");
}
public static void RemindExpiriesMail ()
{
// Get expiring
Console.WriteLine("Inside RemindExpiriesMail()");
Organizations orgs = Organization.Root.GetTree();
Dictionary<int, bool> personLookup = new Dictionary<int, bool>();
Dictionary<string, int> dateLookup = new Dictionary<string, int>();
DateTime lowerBound = DateTime.Today;
DateTime upperBound = lowerBound.AddDays(31);
List<string> failedReminders = new List<string>();
int weekDayInteger = (int) DateTime.Today.DayOfWeek;
foreach (Organization org in orgs)
{
Memberships memberships = Memberships.GetExpiring(org, lowerBound, upperBound);
foreach (Membership membership in memberships)
{
if (membership.OrganizationId % 7 != weekDayInteger)
{
continue;
}
try
{
Console.Write("Reminding " + membership.Person.Canonical + " about " +
membership.Organization.Name + ".");
SendReminderMail(membership);
Console.Write(".");
PWLog.Write(PWLogItem.Person, membership.PersonId,
PWLogAction.MembershipRenewReminder,
"Mail was sent to " + membership.Person.Email +
" reminding to renew membership in " + membership.Organization.Name + ".", string.Empty);
Console.Write(".");
string dateString = membership.Expires.ToString("yyyy-MM-dd");
if (!dateLookup.ContainsKey(dateString))
{
dateLookup[dateString] = 0;
}
dateLookup[dateString]++;
Console.WriteLine(" done.");
}
catch (Exception x)
{
string logText = "FAILED sending mail to " + membership.Person.Email +
" 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);
ExceptionMail.Send(new Exception(logText, x));
}
}
}
string notifyBody = String.Format("Sending renewal reminders to {0} people:\r\n\r\n", personLookup.Count);
Console.WriteLine("Sending renewal reminders to {0} people", personLookup.Count);
List<string> dateSummary = new List<string>();
int total = 0;
foreach (string dateString in dateLookup.Keys)
{
dateSummary.Add(string.Format("{0}: {1,5}", dateString, dateLookup[dateString]));
total += dateLookup[dateString];
}
dateSummary.Sort();
foreach (string dateString in dateSummary)
{
notifyBody += dateString + "\r\n";
Console.WriteLine(dateString);
}
notifyBody += string.Format("Total sent: {0,5}\r\n\r\n", total);
Console.WriteLine("Total sent: {0,5}\r\n\r\n", total);
notifyBody += "FAILED reminders:\r\n";
Console.WriteLine("FAILED reminders:");
foreach (string failed in failedReminders)
{
notifyBody += failed + "\r\n";
Console.WriteLine(failed);
}
if (failedReminders.Count == 0)
{
notifyBody += "none.\r\n";
Console.WriteLine("none.");
}
Person.FromIdentity(1).SendOfficerNotice("Reminders sent today", notifyBody, 1);
}
// This should run daily, suggested right after midnight.
public static void ChurnExpiredMembers ()
{
// For the time being, use org 1 as master.
int[] organizationIds = new int[] { Organization.PPSEid };
foreach (int organizationId in organizationIds)
{
Memberships memberships = Memberships.GetExpired(Organization.FromIdentity(organizationId));
// Mail each expiring member
foreach (Membership membership in memberships)
{
//only remove expired memberships
if (membership.Expires > DateTime.Now.Date)
continue;
Person person = membership.Person;
// Remove all roles and responsibilities for this person in the org
Authority authority = person.GetAuthority();
foreach (BasicPersonRole basicRole in authority.LocalPersonRoles)
{
PersonRole personRole = PersonRole.FromBasic(basicRole);
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.Delete();
}
}
// Mail
Memberships personMemberships = person.GetMemberships();
Memberships membershipsToDelete = new Memberships();
foreach (Membership personMembership in personMemberships)
{
if (personMembership.Expires <= DateTime.Now.Date)
{
membershipsToDelete.Add(personMembership);
}
}
ExpiredMail expiredmail = new ExpiredMail();
string membershipsIds = "";
if (membershipsToDelete.Count > 1)
{
foreach (Membership personMembership in membershipsToDelete)
{
membershipsIds += "," + personMembership.MembershipId.ToString();
}
membershipsIds = membershipsIds.Substring(1);
string expiredMemberships = "";
foreach (Membership personMembership in membershipsToDelete)
{
if (personMembership.OrganizationId != organizationId)
{
expiredMemberships += ", " + personMembership.Organization.Name;
}
}
expiredMemberships += ". ";
expiredmail.pMemberships = expiredMemberships.Substring(2).Trim();
}
//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 stdLink = "https://pirateweb.net/Pages/Public/SE/People/MemberRenew.aspx?MemberId=" +
person.Identity.ToString() +
"&SecHash=" + SHA1.Hash(tokenBase).Replace(" ", "").Substring(0, 8) +
"&MID=" + membershipsIds;
expiredmail.pStdRenewLink = stdLink;
expiredmail.pOrgName = Organization.FromIdentity(organizationId).MailPrefixInherited;
person.SendNotice(expiredmail, organizationId);
person.DeleteSubscriptionData();
string orgIdString = string.Empty;
foreach (Membership personMembership in membershipsToDelete)
{
if (personMembership.Active)
{
orgIdString += " " + personMembership.OrganizationId;
personMembership.Terminate(EventSource.PirateBot, null, "Member churned in housekeeping.");
}
}
}
}
}
internal static void RemindExpiries (DateTime dateExpiry)
{
Organizations orgs = Organization.Root.GetTree();
foreach (Organization org in orgs)
{
Memberships memberships = Memberships.GetExpiring(org, dateExpiry);
// Mail each expiring member
foreach (Membership membership in memberships)
{
try
{
SendReminderMail(membership);
PWLog.Write(PWLogItem.Person, membership.PersonId,
PWLogAction.MembershipRenewReminder,
"Mail was sent to " + membership.Person.Email +
" 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));
}
}
}
}
internal static void RemindExpiriesSms (DateTime dateExpiry, string message)
{
// For the time being, only remind for org 1.
int[] organizationIds = new int[] { Organization.PPSEid };
foreach (int organizationId in organizationIds)
{
Memberships memberships = Memberships.GetExpiring(Organization.FromIdentity(organizationId), dateExpiry);
// Mail each expiring member
foreach (Membership membership in memberships)
{
Person person = membership.Person;
if (People.FromPhoneNumber("SE", person.Phone).Count == 1)
{
if (SendReminderSms(person, message))
{
PWLog.Write(PWLogItem.Person, membership.PersonId,
PWLogAction.MembershipRenewReminder,
"SMS was sent to " + membership.Person.Phone +
" reminding to renew membership.", string.Empty);
}
else
{
PWLog.Write(PWLogItem.Person, membership.PersonId,
PWLogAction.MembershipRenewReminder,
"Unable to send SMS to " + membership.Person.Phone +
"; tried to remind about renewing membership.", string.Empty);
}
}
}
}
}
internal static bool SendReminderSms (Person person, string message)
{
bool result = false;
try
{
person.SendPhoneMessage(message);
result = true;
}
// ignore exceptions
catch (Exception)
{
}
return result;
}
public static void SendReminderMail (Membership membership)
{
// First, determine the organization template to use. Prioritize a long ancestry.
// This is a hack for the Swedish structure.
ReminderMail remindermail = new ReminderMail();
// NEW December 2010: Organizations are separated as per common agreement, there are no common reminder mails. Every membership renews on its own.
int longestAncestry = 0; // "ancestry" as a length means distance to organization tree root
int shortestAncestry = 999;
Organization lowOrg = membership.Organization;
DateTime currentExpiry = membership.Expires;
Person person = membership.Person;
DateTime newExpiry = currentExpiry;
//do not mess with lifetime memberships (100 years)
if (newExpiry < DateTime.Today.AddYears(10))
{
newExpiry = newExpiry.AddYears(1);
}
remindermail.pPreamble = "<p> Nu är det dags att <strong>förnya ditt medlemskap</strong> i " + membership.Organization.Name + ".";
remindermail.pExpirationDate = currentExpiry;
remindermail.pNextDate = newExpiry;
remindermail.pOrgName = membership.Organization.MailPrefixInherited;
string tokenBase = person.PasswordHash + "-" + membership.Identity.ToString() + "-" + currentExpiry.Year.ToString();
// REMOVED DEC2010: suggestion that people older than 25 may leave UP, as renewal mails are separated
// HACK for UPSE:
Organization expectedLowOrg = Organizations.GetMostLocalOrganization(person.GeographyId, Organization.UPSEid);
if (expectedLowOrg != null && lowOrg.Inherits(Organization.UPSEid) && lowOrg.Identity != expectedLowOrg.Identity)
{
// Is this person in the wrong locale?
remindermail.pCurrentOrg = lowOrg.Name;
remindermail.pOtherOrg = expectedLowOrg.Name;
remindermail.pGeographyName = person.Geography.Name;
//mailBody += "Du är medlem i " + lowOrg.Name + ", men när du bor i [b]" + person.Geography.Name +
// "[/b] så rekommenderar " +
// "vi att du byter till din lokala organisation, [b]" + expectedLowOrg.Name +
// "[/b]. Klicka här för att göra det:\r\n\r\n";
string link = "https://pirateweb.net/Pages/Public/SE/People/MemberRenew.aspx?PersonId=" +
person.Identity.ToString() + "&Transfer=" + lowOrg.Identity.ToString() + "," +
expectedLowOrg.Identity.ToString() +
"&MembershipId=" + membership.Identity.ToString() +
"&SecHash=" + SHA1.Hash(tokenBase + "-Transfer" + lowOrg.Identity.ToString() + "/" +
expectedLowOrg.Identity.ToString()).Replace(" ", "").Substring(0, 8);
remindermail.pOtherRenewLink = link;
remindermail.pTooOldForYouthOrgSpan = " "; //clear the other span
//mailBody += "[a href=\"" + link + "\"]" + link + "[/a]\r\n\r\n" +
// "Det är naturligtvis inget krav, utan du kan fortsätta precis som förut om du vill. " +
// "För att fortsätta i dina befintliga föreningar, klicka här:\r\n\r\n";
}
else
{
remindermail.pTooOldForYouthOrgSpan = " "; //clear the other span
remindermail.pWrongOrgSpan = " "; //clear the other span
//mailBody += "Klicka på den här länken för att förnya för ett år till:\r\n\r\n";
}
string stdLink = "https://pirateweb.net/Pages/Public/SE/People/MemberRenew.aspx?PersonId=" +
person.Identity.ToString() +
"&MembershipId=" + membership.Identity.ToString() +
"&SecHash=" + SHA1.Hash(tokenBase).Replace(" ", "").Substring(0, 8);
remindermail.pStdRenewLink = stdLink;
tokenBase = person.PasswordHash + "-" + membership.Identity.ToString();
string terminateLink = "https://pirateweb.net/Pages/Public/SE/People/MemberTerminate.aspx?MemberId=" +
person.Identity.ToString() +
"&SecHash=" + SHA1.Hash(tokenBase).Replace(" ", "").Substring(0, 8) +
"&MID=" + membership.Identity.ToString();
remindermail.pTerminateLink = terminateLink;
//mailBody += "[a href=\"" + stdLink + "\"]" + stdLink + "[/a]\r\n\r\n" +
// "[br]Välkommen att vara med oss i [b]ett år till![/b]\r\n\r\n" +
// "Hälsningar,[br]Medlemsservice\r\n\r\n"; // +
/*"PS: [b]Du fick ett likadant mail alldeles nyss. Om du har å, ä eller ö i ditt namn fungerade " +
"inte länken i det mailet. Tack till alla som hörde av sig om det; felet är fixat nu och länken ovan ska fungera.[/b]\r\n\r\n";*/
//OutboundMail mail = remindermail.CreateOutboundMail(sender, OutboundMail.PriorityNormal, topOrg, Geography.Root);
OutboundMail mail = remindermail.CreateFunctionalOutboundMail(MailAuthorType.MemberService, OutboundMail.PriorityNormal, membership.Organization, Geography.Root);
if (mail.Body.Trim() == "")
{
throw new InvalidOperationException("Failed to create a mailBody");
}
else
{
mail.AddRecipient(person.Identity, false);
mail.SetRecipientCount(2);
mail.SetResolved();
mail.SetReadyForPickup();
}
}
public static void TimeoutVolunteers ()
{
Volunteers volunteers = Volunteers.GetOpen();
DateTime threshold = DateTime.Today.AddDays(-30);
foreach (Volunteer volunteer in volunteers)
{
if (volunteer.OpenedDateTime < threshold)
{
// timed out
OfficerChain officers = OfficerChain.FromOrganizationAndGeography(Organization.PPSE,
volunteer.Geography);
new MailTransmitter(Strings.MailSenderName, Strings.MailSenderAddress,
"Volunteer Timed Out: [" + volunteer.Geography.Name + "]",
String.Empty, officers, true).Send();
volunteer.Close("Timed out");
}
}
}
/*
* Handle UP special: Monthly reminder to members that are in wrong organisation
* (member in an org that no longer accepts members) or member of an org where a "better fit" exists geographically
*
*/
private class ChangeOrgReport
{
public Organization FromOrg = null;
public Organization ToOrg = null;
}
public static void RemindChangeOrg ()
{
HeartBeater.Instance.Beat();
// Get expiring
DateTime starttime = DateTime.Now;
Organizations orgs = Organization.FromIdentity(Organization.UPSEid).GetTree();
Dictionary<int, Person> personLookup = new Dictionary<int, Person>();
Dictionary<int, Memberships> personMembershipsLookup = new Dictionary<int, Memberships>();
Dictionary<int, Organization> orgLookup = new Dictionary<int, Organization>();
Dictionary<int, Organization> mostLocalOrganizationCache = new Dictionary<int, Organization>();
List<ChangeOrgReport> report = new List<ChangeOrgReport>();
foreach (Organization org in orgs)
{
orgLookup[org.OrganizationId] = org;
}
Memberships allMemberships = Memberships.ForOrganizations(orgs);
foreach (Membership ms in allMemberships)
{
//Handle defunct Memberships.ForOrganizations
if (orgLookup.ContainsKey(ms.OrganizationId))
{
if (!personLookup.ContainsKey(ms.PersonId))
{
personLookup[ms.PersonId] = null;
personMembershipsLookup[ms.PersonId] = new Memberships();
}
personMembershipsLookup[ms.PersonId].Add(ms);
}
}
allMemberships = null;
People peeps = People.FromIdentities((new List<int>(personLookup.Keys)).ToArray());
foreach (Person p in peeps)
{
personLookup[p.PersonId] = p;
}
if (Debugger.IsAttached)
Console.WriteLine("Found " + personLookup.Count + " people");
int processedCounter = 0;
int sentCounter = 0;
int failCounter = 0;
DateTime lastDisplay = DateTime.Now;
foreach (Person person in personLookup.Values)
{
++processedCounter;
if ((processedCounter % 50) == 0)
{
HeartBeater.Instance.Beat();
if (Debugger.IsAttached)
Console.WriteLine("Processed " + processedCounter + " t=" + DateTime.Now.Subtract(lastDisplay).TotalSeconds);
lastDisplay = DateTime.Now;
}
int geoid = person.GeographyId;
//check for error, geography broken.
if (person.GeographyId == 0)
{
geoid = person.Geography.GeographyId; //Will force resolve Geography
if (geoid != 0)
person.Geography = person.Geography; ; //repair person.
}
if (geoid == 0)
continue; //give up on that...
Organization expectedLowOrg = null;
if (mostLocalOrganizationCache.ContainsKey(geoid))
{
expectedLowOrg = mostLocalOrganizationCache[geoid];
}
else
{
expectedLowOrg = Organizations.GetMostLocalOrganization(geoid, Organization.UPSEid);
mostLocalOrganizationCache[geoid] = expectedLowOrg;
}
bool found = false;
Dictionary<int, Membership> personMS = new Dictionary<int, Membership>();
foreach (Membership ms in personMembershipsLookup[person.PersonId])
{
if (orgLookup.ContainsKey(ms.OrganizationId))
{ //Its an UP org
personMS[ms.OrganizationId] = ms;
}
if (ms.OrganizationId == expectedLowOrg.Identity)
{
found = true;
break;
}
}
if (found == false)
{
//OK we didnt find the recommended org. Find out why.
// loop thru the persons up orgs to find an inactive
List<Organization> foundInactiveOrg = new List<Organization>();
List<Organization> foundActiveOrg = new List<Organization>();
Membership membership = null;
try
{
Organization org = null;
foreach (Membership ms in personMS.Values)
{
org = orgLookup[ms.OrganizationId];
if (org.AcceptsMembers == false)
{
foundInactiveOrg.Add(org);
}
else if (org.AutoAssignNewMembers == true)
{
foundActiveOrg.Add(org);
}
}
if (foundInactiveOrg.Count > 0)
{
//inactive
membership = personMS[foundInactiveOrg[0].Identity];
}
else if (foundActiveOrg.Count > 0)
{
//change
membership = personMS[foundActiveOrg[0].Identity];
}
else
{
//already a member but not of an autoassign org
if (Debugger.IsAttached)
Console.WriteLine("Debug:nochange " + person.Name + ";" + person.Geography.Name + ";" + (org != null ? org.Name : "UnknownOrg") + ";" + expectedLowOrg.Name);
continue;
}
DateTime lastReminder = PWLog.CheckLatest(PWLogItem.Person, membership.PersonId, PWLogAction.MembershipRenewReminder);
if (DateTime.Now.Subtract(lastReminder).TotalDays > 25)
{
if (Debugger.IsAttached)
{
Console.Write("Debug:" + person.Name + ";" + person.Geography.Name + ";" + membership.Organization.Name + ";" + expectedLowOrg.Name);
foreach (var o in foundActiveOrg)
Console.Write(";" + o.Name);
Console.WriteLine("");
}
SendChangeOrgMail(person, membership, expectedLowOrg);
report.Add(new ChangeOrgReport { FromOrg = membership.Organization, ToOrg = expectedLowOrg });
++sentCounter;
PWLog.Write(PWLogItem.Person, membership.PersonId,
PWLogAction.MembershipRenewReminder,
"Mail was sent to " + membership.Person.Email +
" for recommendation of organisation change in " + membership.Organization.Name + ".",
membership.Organization.Identity.ToString() + "/" + expectedLowOrg.Identity.ToString());
}
}
catch (Exception x)
{
++failCounter;
string logText = "FAILED sending mail to " + membership.Person.Email +
" for recommendation of organisation change in " + membership.Organization.Name + ".";
PWLog.Write(PWLogItem.Person, membership.PersonId,
PWLogAction.MembershipRenewReminder,
logText, string.Empty);
ExceptionMail.Send(new Exception(logText, x));
}
}
}
Dictionary<Organization, Dictionary<Organization, int>> fromdict = new Dictionary<Organization, Dictionary<Organization, int>>();
StringBuilder fromOrgReport = new StringBuilder();
report.ForEach(delegate(ChangeOrgReport r)
{
if (!fromdict.ContainsKey(r.FromOrg))
fromdict[r.FromOrg] = new Dictionary<Organization, int>();
if (!fromdict[r.FromOrg].ContainsKey(r.ToOrg))
fromdict[r.FromOrg][r.ToOrg] = 0;
fromdict[r.FromOrg][r.ToOrg]++;
});
foreach (var fd in fromdict.Keys)
{
StringBuilder tmp = new StringBuilder();
int cnt = 0;
foreach (var td in fromdict[fd].Keys)
{
tmp.Append(", " + td.Name);
cnt += fromdict[fd][td];
}
fromOrgReport.Append("\r\nFrån " + fd.Name + " (" + cnt + " st) till " + tmp.ToString().Substring(2));
}
Dictionary<Organization, Dictionary<Organization, int>> todict = new Dictionary<Organization, Dictionary<Organization, int>>();
StringBuilder toOrgReport = new StringBuilder();
report.ForEach(delegate(ChangeOrgReport r)
{
if (!todict.ContainsKey(r.ToOrg))
todict[r.ToOrg] = new Dictionary<Organization, int>();
if (!todict[r.ToOrg].ContainsKey(r.FromOrg))
todict[r.ToOrg][r.FromOrg] = 0;
todict[r.ToOrg][r.FromOrg]++;
});
foreach (var td in todict.Keys)
{
StringBuilder tmp = new StringBuilder();
int cnt = 0;
foreach (var fd in todict[td].Keys)
{
tmp.Append(", " + fd.Name);
cnt += todict[td][fd];
}
toOrgReport.Append("\r\nTill " + td.Name + " (" + cnt + " st) från " + tmp.ToString().Substring(2));
}
string reportMessage = string.Format(
"Result from running recommendation to change org mails:\r\n"
+ "Time: {0,10:#0.0} minutes. \r\n"
+ "Checked: {1,10:g}\r\n"
+ "Sent: {2,10:g}\r\n"
+ "Failed: {3,10:g}\r\n",
DateTime.Now.Subtract(starttime).TotalMinutes, processedCounter, sentCounter, failCounter)
+ fromOrgReport + "\r\n"
+ toOrgReport;
BasicPersonRole[] UPSecretary = PirateDb.GetDatabase().GetPeopleWithRoleType(RoleType.OrganizationSecretary,
new int[] { Organization.UPSEid },
new int[] { });
if (UPSecretary.Length > 0)
{
Person.FromIdentity(UPSecretary[0].PersonId).SendOfficerNotice("ChangeOrg Mails Job report", reportMessage, Organization.UPSEid);
}
Person.FromIdentity(7838).SendOfficerNotice("ChangeOrgMails run", reportMessage, Organization.UPSEid);//Debug
}
public static void SendChangeOrgMail (Person person, Membership membership, Organization newOrg)
{
// HACK for UPSE
// This is a hack for the Swedish structure.
ChangeOrgMail changeorgmail = new ChangeOrgMail();
Organization topOrg = Organization.FromIdentity(Organization.UPSEid);
Organization lowOrg = membership.Organization;
DateTime currentExpiry = membership.Expires;
DateTime newExpiry = DateTime.Today.AddYears(1);
changeorgmail.pCurrentOrg = lowOrg.Name;
changeorgmail.pCurrentGeo = person.Geography.Name;
changeorgmail.pNextDate = newExpiry;
string tokenBase = person.PasswordHash + "-" + membership.Identity.ToString() + "-" + currentExpiry.Year.ToString();
if (newOrg.AnchorGeographyId == Geography.RootIdentity && newOrg.AutoAssignNewMembers)
{//Fallback org
changeorgmail.pNoLocalOrg = newOrg.Name;
changeorgmail.pChangeOrg = "";
}
else
{
changeorgmail.pNoLocalOrg = "";
changeorgmail.pChangeOrg = newOrg.Name;
}
if (lowOrg.AcceptsMembers)
{
changeorgmail.pInactiveOrg = "";
changeorgmail.pInactiveEnding = " ";
}
else
{
changeorgmail.pInactiveOrg = newOrg.Name;
}
changeorgmail.pStdRenewLink = "https://pirateweb.net/Pages/Public/SE/People/MemberRenew.aspx?PersonId=" +
person.Identity.ToString() + "&Transfer=" + lowOrg.Identity.ToString() + "," +
newOrg.Identity.ToString() +
"&MembershipId=" + membership.Identity.ToString() +
"&SecHash=" + SHA1.Hash(tokenBase + "-Transfer" + lowOrg.Identity.ToString() + "/" +
newOrg.Identity.ToString()).Replace(" ", "").Substring(0, 8);
OutboundMail mail = changeorgmail.CreateFunctionalOutboundMail(MailAuthorType.MemberService, OutboundMail.PriorityNormal, topOrg, Geography.Root);
string test = mail.RenderHtml(person, person.PreferredCulture);
test = mail.RenderText(person, person.PreferredCulture);
if (mail.Body.Trim() == "")
{
throw new InvalidOperationException("Failed to create a mailBody");
}
else
{
//mail.AddRecipient(7838, true);
mail.AddRecipient(person.Identity, false);
mail.SetRecipientCount(1);
mail.SetResolved();
mail.SetReadyForPickup();
}
}
}
}
+69
View File
@@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Activizr.Basic.Enums;
using Activizr.Logic.Financial;
using Activizr.Logic.Support;
namespace Activizr.Utility.BotCode
{
public class SalaryProcessor
{
static public void Run()
{
DateTime today = DateTime.Today;
string lastRun = Persistence.Key["LastSalaryRun"];
string expectedLastRun = today.ToString("yyyyMM", CultureInfo.InvariantCulture);
if (lastRun != null && String.Compare(lastRun,expectedLastRun) >= 0)
{
// nothing to do, return
return;
}
Persistence.Key["LastSalaryRun"] = expectedLastRun;
// Process the payroll for all organizations. Assume payday is 25th.
Payroll payroll = Payroll.GetAll();
DateTime payday = new DateTime(today.Year, today.Month, 25);
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);
}
}
/*
public static void RecreateFirstTransaction()
{
Salary salary = Salary.FromIdentity(1);
PayrollItem payrollItem = salary.PayrollItem;
DateTime payday = salary.PayoutDate;
PWEvents.CreateEvent(EventSource.PirateBot, EventType.SalaryCreated, 0, payrollItem.OrganizationId,
0, payrollItem.PersonId, salary.Identity, string.Empty);
double cost = salary.GrossSalary + salary.AdditiveTax;
double tax = salary.SubtractiveTax + salary.AdditiveTax;
double net = salary.GrossSalary - salary.SubtractiveTax;
FinancialTransaction transaction =
FinancialTransaction.Create(payrollItem.OrganizationId, DateTime.Now,
"Salary #" + salary.Identity + ": " + payrollItem.PersonCanonical + " " +
payday.ToString("yyyy-MMM", CultureInfo.InvariantCulture));
transaction.AddRow(payrollItem.BudgetId, cost, 0);
transaction.AddRow(payrollItem.Organization.FinancialAccounts.DebtsSalary, -net, null);
transaction.AddRow(payrollItem.Organization.FinancialAccounts.DebtsTax, -tax, null);
transaction.Dependency = salary;
}*/
}
}
+281
View File
@@ -0,0 +1,281 @@
using System;
using System.Collections.Generic;
using System.Text;
using Activizr.Logic.Governance;
namespace Activizr.Utility.BotCode
{
/// <summary>
/// This class computes a Condorcet/Single-Transferable-Vote result according to the Schulze Method.
/// </summary>
public class SchulzeProcessor
{
public MeetingElectionVotes Votes { set; private get; }
public MeetingElectionCandidates Candidates { set; private get; }
public void Process()
{
CreateCandidateIdList();
CalculateIntercandidatePreferences();
CalculateLinkStrengths();
AssembleFinalOrder();
}
private void CreateCandidateIdList()
{
// This function creates a list of all the candidate Ids in the election, as
// well as a reverse lookup into the list in the form of a dictionary. So,
// if candidate #4711 is placed into the fifth spot:
//
// candidateIds[4] = 4711;
// indexOfCandidateId[4711] = 4;
//
// We use this translation later as we use indexes as identities in the preference matrix.
Console.Write("Creating list of candidates and index lookup...");
candidateIds = new List<int>();
indexOfCandidateId = new Dictionary<int, int>();
int index = 0;
foreach (MeetingElectionCandidate candidate in Candidates)
{
candidateIds.Add(candidate.Identity);
indexOfCandidateId[candidate.Identity] = index;
index++;
}
Console.WriteLine(" done.");
}
private void CalculateIntercandidatePreferences()
{
// Iterate over all votes and set the preferences, as in "how many voters prefer candidate X over
// candidate Y?". This data is needed for the next step, the link strengths.
//
// We do this by, for each vote, getting the list of candidates (in order of voting). We go from
// the #1 candidate on the vote to the #n candidate on the vote, checking them off as we go, and
// recording all ALREADY-CHECKED-OFF candidates as superior to the one we are CURRENTLY at.
//
// 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
int count = 1;
Console.WriteLine("Calculating raw preference matrix.");
foreach (MeetingElectionVote vote in Votes)
{
Console.Write("\r - vote {0:D5} of {1:D5}...", count, Votes.Count);
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]]++;
}
// check this candidate off as iterated
candidateIdSeen[candidateId] = true;
}
// We have now gone through the list of candidates on the vote cast. The final step is that these are all
// 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)
{
if (!candidateIdSeen.ContainsKey(candidateId))
{
// Not on vote, so inferior to all candidates on the vote
foreach (int voteCandidateId in voteCandidateIds)
{
preferenceXtoY[indexOfCandidateId[voteCandidateId], indexOfCandidateId[candidateId]]++;
}
}
}
count++;
}
Console.WriteLine(" done.");
}
private void CalculateLinkStrengths()
{
// This code is copied from the Wikipedia article on the Schulze method to avoid misimplementation.
//
// http://en.wikipedia.org/wiki/Schulze_method
linkStrengthXtoY = new int[candidateIds.Count,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++)
{
Console.Write("\r - Step 1: {0:D4} of {1:D4}...", outerIndex+1, candidateIds.Count);
for (int innerIndex = 0; innerIndex < candidateIds.Count; innerIndex++)
{
if (innerIndex == outerIndex)
{
continue;
}
if (preferenceXtoY[outerIndex, innerIndex] > preferenceXtoY[innerIndex, outerIndex])
{
linkStrengthXtoY[outerIndex, innerIndex] = preferenceXtoY[outerIndex, innerIndex];
}
// else set to zero, but this is handled by the framework on initialization
}
}
Console.WriteLine(" done.");
// 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++)
{
Console.Write("\r - Step 2: {0:D4} of {1:D4}...", outerIndex + 1, candidateIds.Count);
for (int middleIndex = 0; middleIndex < candidateIds.Count; middleIndex++)
{
if (outerIndex == middleIndex)
{
continue;
}
for (int innerIndex = 0; innerIndex < 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]));
}
}
}
Console.WriteLine(" done.");
}
private void AssembleFinalOrder()
{
Console.WriteLine("Assembling final list.");
MeetingElectionCandidates result = new MeetingElectionCandidates();
Dictionary<int, bool> candidateAdded = new Dictionary<int, bool>();
int candidatesRemaining = candidateIds.Count;
int count = 1;
while (candidatesRemaining > 0)
{
Console.Write("\r - remaining: {0:D4}", candidatesRemaining);
// Find the first nontaken candidate
int winningCandidateIndex = 0;
while (candidateAdded.ContainsKey(winningCandidateIndex))
{
winningCandidateIndex++;
}
// Iterate over all linkStrength[X,*] and [*,X]; this candidate is only a winner if
// all [X,*] are >= all [*,X].
bool allSuperior = false;
while (!allSuperior)
{
allSuperior = true;
for (int compareCandidateIndex = 0; compareCandidateIndex < candidateIds.Count; compareCandidateIndex++)
{
if (candidateAdded.ContainsKey(compareCandidateIndex))
{
continue;
}
if (linkStrengthXtoY[winningCandidateIndex, compareCandidateIndex] <
linkStrengthXtoY[compareCandidateIndex,winningCandidateIndex])
{
// the compareCandidateIndex had a greater link strength, so jump there and take it as
// a new potential winner, restarting the comparison
winningCandidateIndex = compareCandidateIndex;
allSuperior = false;
break;
}
}
}
// We have the winning candidate among the not-yet-ranked candidates:
MeetingElectionCandidate candidate = MeetingElectionCandidate.FromIdentity(candidateIds[winningCandidateIndex]);
candidateAdded[winningCandidateIndex] = true;
result.Add(candidate);
candidatesRemaining--;
count++;
}
FinalOrder = result;
Console.WriteLine(", done.");
}
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)
{
// 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)
{
return 0;
}
int candidateIdX = FinalOrder[finalOrderIndex].Identity;
int candidateIdY = FinalOrder[finalOrderIndex + 1].Identity;
int indexX = indexOfCandidateId[candidateIdX];
int indexY = indexOfCandidateId[candidateIdY];
int distance = preferenceXtoY[indexX, indexY] - preferenceXtoY[indexY, indexX];
return distance;
}
}
}
+108
View File
@@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using System.Text;
using Activizr.Database;
using Activizr.Logic.Communications;
using Activizr.Logic.Special.Sweden;
using Activizr.Logic.Structure;
using Activizr.Logic.Support;
using Activizr.Utility.Special.Sweden;
namespace Activizr.Utility.BotCode
{
public class TurnaroundTracker
{
public static void Run()
{
const string persistenceKey = "PPSE-LastSupportDeltaId";
string lastDeltaIdString = Persistence.Key[persistenceKey];
int lastDeltaId = 0;
if (!String.IsNullOrEmpty(lastDeltaIdString))
{
lastDeltaId = Int32.Parse(lastDeltaIdString);
}
SupportCaseDelta[] deltas = SupportDatabase.GetCaseDeltas(lastDeltaId);
foreach (SupportCaseDelta delta in deltas)
{
if (delta.Verb == "Incoming email")
{
try
{
CommunicationTurnaround.Create(Organization.PPSE, delta.SupportCaseId, delta.DateTime);
}
catch (Exception)
{
// Ignore if can't create
}
}
else if (delta.Verb == "Replied")
{
try
{
CommunicationTurnaround turnaround = CommunicationTurnaround.FromIdentity(Organization.PPSE, 1,
delta.SupportCaseId);
turnaround.SetResponded(delta.DateTime, null);
}
catch (Exception)
{
}
}
else if (delta.Verb == "Closed")
{
try
{
CommunicationTurnaround turnaround = CommunicationTurnaround.FromIdentity(Organization.PPSE, 1,
delta.SupportCaseId);
turnaround.Close(delta.DateTime, null);
}
catch (Exception)
{
// if can't find, ignore
}
}
else if (delta.Changes.Contains("'Spam'"))
{
try
{
CommunicationTurnaround turnaround = CommunicationTurnaround.FromIdentity(Organization.PPSE, 1,
delta.SupportCaseId);
turnaround.Close(delta.DateTime, null);
}
catch (Exception)
{
}
}
if (delta.SupportCaseDeltaId > lastDeltaId)
{
lastDeltaId = delta.SupportCaseDeltaId;
}
}
Persistence.Key[persistenceKey] = lastDeltaId.ToString();
}
public static void Housekeeping()
{
CommunicationTurnarounds turnarounds = CommunicationTurnarounds.ForOrganization(Organization.PPSE);
foreach (CommunicationTurnaround turnaround in turnarounds)
{
if (!SupportDatabase.IsCaseOpen(turnaround.CommunicationId))
{
DateTime? dateTimeClosed = SupportDatabase.GetCaseCloseDateTime(turnaround.CommunicationId);
if (dateTimeClosed == null)
{
dateTimeClosed = turnaround.DateTimeOpened;
}
PirateDb.GetDatabase().SetCommunicationTurnaroundClosed(Organization.PPSEid, 1, turnaround.CommunicationId, (DateTime) dateTimeClosed, 0);
}
}
}
}
}
+250
View File
@@ -0,0 +1,250 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Activizr.Basic.Enums;
using Activizr.Logic.Special.Sweden;
using Activizr.Logic.Structure;
using Activizr.Logic.Support;
namespace Activizr.Utility.BotCode
{
public class UpdateStatsCache
{
static public void Run()
{
BotLog.Write(1, "UpdateStatsCache", "Entering (obsoleted does nothing");
UpdateBallotDistroData();
BotLog.Write(1, "UpdateStatsCache", "Exiting");
}
private static void UpdateBallotDistroData ()
{
//Empty method now this is done from the web app.
}
private static void ObsoletedUpdateBallotDistroData ()
{
#region Obsoleted commented code
//BotLog.Write(2, "BallotDistroData", "Entering");
//BotLog.Write(2, "BallotDistroData", "Getting geographic voter counts...");
//Dictionary<int, int> voterCount = Optimizations.GetGeographyVoterCounts();
//BotLog.Write(2, "BallotDistroData", "...done. Getting advance voting data...");
//WebRequest myWebRequest = WebRequest.Create("http://valsedlar.piratpartiet.se/export/municipalities_book_data/");
//// Send the 'WebRequest' and wait for response.
//WebResponse myWebResponse = myWebRequest.GetResponse();
//BotLog.Write(2, "BallotDistroData", "...reading response...");
//string data = null;
//// Obtain a 'Stream' object associated with the response object.
//using (Stream receiveStream = myWebResponse.GetResponseStream())
//{
// Encoding encode = Encoding.UTF8;
// // Pipe the stream to a higher level stream reader with the required encoding format.
// using (StreamReader readStream = new StreamReader(receiveStream, encode))
// {
// data = readStream.ReadToEnd();
// }
//}
//BotLog.Write(2, "BallotDistroData", "...done. Decoding data per city.");
//string[] lines = data.Split('\n');
//int advanceStationCount = 0;
//int advanceStationDistroCount = 0;
//int stationCount = 0;
//int stationSingleDistroCount = 0;
//int stationDoubleDistroCount = 0;
//int stationFullCoverage = 0;
//GeographyBallotCoverageData coverageData = new GeographyBallotCoverageData();
//Dictionary<int, GeographyBallotCoverageDataPoint> lookup = new Dictionary<int, GeographyBallotCoverageDataPoint>();
//foreach (string line in lines)
//{
// if (line.Contains(";") && !line.StartsWith("#"))
// {
// string[] parts = line.Split(';');
// string cityName = parts[0];
// if (cityName.StartsWith("Göteborg") ||
// cityName.StartsWith("Gotland") ||
// cityName.StartsWith("Malmö"))
// {
// cityName = cityName.Replace("kommun", "valkrets");
// }
// Geography city = Geography.FromName(cityName);
// int booked = Int32.Parse(parts[2]);
// int total = Int32.Parse(parts[1]);
// string bookingUrl = parts[8];
// advanceStationCount += total * voterCount[city.Identity];
// advanceStationDistroCount += booked * voterCount[city.Identity];
// GeographyBallotCoverageDataPoint dataPoint =
// new GeographyBallotCoverageDataPoint
// {
// GeographyId = city.Identity,
// AdvanceVotingStationsDistro = booked * voterCount[city.Identity],
// AdvanceVotingStationsTotal = total * voterCount[city.Identity],
// BookingUrl = bookingUrl
// };
// lookup[city.Identity] = dataPoint;
// BotLog.Write(3, "BallotDistroData", city.Name + " Advance: " + booked.ToString() + "/" + total.ToString());
// }
//}
//BotLog.Write(2, "BallotDistroData", "Done collecting advance data. Collecting election day data...");
//myWebRequest = WebRequest.Create("http://valsedlar.piratpartiet.se/export/votingstation_coverage/");
//// Send the 'WebRequest' and wait for response.
//myWebResponse = myWebRequest.GetResponse();
//BotLog.Write(2, "BallotDistroData", "...reading response...");
//data = null;
//// Obtain a 'Stream' object associated with the response object.
//using (Stream receiveStream = myWebResponse.GetResponseStream())
//{
// Encoding encode = Encoding.UTF8;
// // Pipe the stream to a higher level stream reader with the required encoding format.
// using (StreamReader readStream = new StreamReader(receiveStream, encode))
// {
// data = readStream.ReadToEnd();
// }
//}
//BotLog.Write(2, "BallotDistroData", "...done. Decoding election day data per city.");
//lines = data.Split('\n');
//foreach (string line in lines)
//{
// if (line.Contains(";") && !line.StartsWith("#") && !line.StartsWith(";"))
// {
// string[] parts = line.Split(';');
// string cityName = parts[1];
// if (cityName.StartsWith("Göteborg") ||
// cityName.StartsWith("Gotland") ||
// cityName.StartsWith("Malmö"))
// {
// cityName = cityName.Replace("kommun", "valkrets");
// }
// Geography city = Geography.FromName(cityName);
// int total = Int32.Parse(parts[2]);
// int singleDistro = Int32.Parse(parts[4]);
// int doubleDistro = Int32.Parse(parts[5]);
// int fullCoverage = Int32.Parse(parts[6]);
// stationCount += total;
// stationSingleDistroCount += singleDistro;
// stationDoubleDistroCount += doubleDistro;
// stationFullCoverage += fullCoverage;
// lookup[city.Identity].VotingStationsTotal = total;
// lookup[city.Identity].VotingStationsDistroSingle = singleDistro;
// lookup[city.Identity].VotingStationsDistroDouble = doubleDistro;
// lookup[city.Identity].VotingStationsComplete = fullCoverage;
// BotLog.Write(3, "BallotDistroData", city.Name + " ElectionDay: " + (singleDistro + doubleDistro + fullCoverage).ToString() + "/" + total.ToString());
// }
//}
//coverageData.Add(new GeographyBallotCoverageDataPoint
// {
// GeographyId = Geography.FromName("Sverige").Identity,
// AdvanceVotingStationsDistro = advanceStationDistroCount,
// AdvanceVotingStationsTotal = advanceStationCount,
// VotingStationsComplete = stationFullCoverage,
// VotingStationsDistroDouble = stationDoubleDistroCount,
// VotingStationsDistroSingle = stationSingleDistroCount,
// VotingStationsTotal = stationCount
// });
//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.
//// For each circuit, get the geography tree, and for every node that has coverage data,
//// aggreagate that data.
//Geographies circuits = Geographies.FromLevel(Country.FromCode("SE"), GeographyLevel.ElectoralCircuit);
//foreach (Geography circuit in circuits)
//{
// BotLog.Write(3, "BallotDistroData", circuit.Name + " --");
// GeographyBallotCoverageDataPoint circuitDataPoint =
// new GeographyBallotCoverageDataPoint { GeographyId = circuit.Identity };
// Geographies circuitTree = circuit.GetTree();
// foreach (Geography circuitNode in circuitTree)
// {
// if (lookup.ContainsKey(circuitNode.Identity))
// {
// BotLog.Write(4, "BallotDistroData", "Adding " + circuitNode.Name);
// circuitDataPoint.AdvanceVotingStationsDistro +=
// lookup[circuitNode.Identity].AdvanceVotingStationsDistro;
// circuitDataPoint.AdvanceVotingStationsTotal +=
// lookup[circuitNode.Identity].AdvanceVotingStationsTotal;
// circuitDataPoint.VotingStationsDistroSingle +=
// lookup[circuitNode.Identity].VotingStationsDistroSingle;
// circuitDataPoint.VotingStationsDistroDouble +=
// lookup[circuitNode.Identity].VotingStationsDistroDouble;
// circuitDataPoint.VotingStationsComplete +=
// lookup[circuitNode.Identity].VotingStationsComplete;
// circuitDataPoint.VotingStationsTotal +=
// lookup[circuitNode.Identity].VotingStationsTotal;
// }
// }
// BotLog.Write(3, "BallotDistroData",
// "...done. Total for " + circuit.Name + ": " + circuitDataPoint.AdvanceVotingStationsDistro +
// "/" + circuitDataPoint.AdvanceVotingStationsTotal + ".");
// coverageData.Add(circuitDataPoint);
//}
//foreach (int key in lookup.Keys)
//{
// coverageData.Add(lookup[key]);
//}
//BotLog.Write(2, "BallotDistroData", "Writing to db");
//Persistence.Key["BallotCoverage-SE"] = coverageData.ToXml();
//BotLog.Write(2, "BallotDistroData", "Exiting");
#endregion
}
}
}