From e84e20e9bc928c1db54ede3c021692f4b1eb1445 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Wed, 11 Jan 2017 15:00:33 +0100 Subject: [PATCH] Adding a lot of old code to use as template --- FrontSocket/Program.cs | 583 ++++++- FrontSocket/SocketServices/EditingService.cs | 75 + FrontSocket/TemplateCode/Dashboard.aspx | 1481 ++++++++++++++++++ FrontSocket/TemplateCode/Dashboard.aspx.cs | 715 +++++++++ Logic/ExtensionMethods/Bitmap.cs | 270 ++++ Logic/ExtensionMethods/Color.cs | 19 + Logic/ExtensionMethods/DateTime.cs | 18 + 7 files changed, 3155 insertions(+), 6 deletions(-) create mode 100644 FrontSocket/SocketServices/EditingService.cs create mode 100644 FrontSocket/TemplateCode/Dashboard.aspx create mode 100644 FrontSocket/TemplateCode/Dashboard.aspx.cs create mode 100644 Logic/ExtensionMethods/Bitmap.cs create mode 100644 Logic/ExtensionMethods/Color.cs create mode 100644 Logic/ExtensionMethods/DateTime.cs diff --git a/FrontSocket/Program.cs b/FrontSocket/Program.cs index 574f134c..aecf7618 100644 --- a/FrontSocket/Program.cs +++ b/FrontSocket/Program.cs @@ -1,15 +1,586 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Diagnostics; +using System.IO; +using System.Net; +using System.Net.Security; +using System.Runtime.InteropServices; +using System.Security.Cryptography.X509Certificates; +using System.Threading; +using Falconwing.Backend.SocketServices; +using Falconwing.Basic; +using Falconwing.Database; +using Falconwing.Logic; +using Falconwing.Logic.ExtensionMethods; +using Mono.Unix; +using Mono.Unix.Native; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using WebSocketSharp.Server; -namespace FrontSocket +namespace Falconwing.Backend { - class Program + internal class Program { static void Main(string[] args) { + // Disable SSL cert checking (because Mono doesn't have a cert repo, dammit) + + ServicePointManager.ServerCertificateValidationCallback = delegate( + Object obj, X509Certificate certificate, X509Chain chain, + SslPolicyErrors errors) + { + return (true); + }; + + if (args.Length > 0 && args[0].ToLowerInvariant() == "publish") + { + PublishStory(); + return; + } + + if (args.Length > 0 && args[0].ToLowerInvariant() == "test") + { + Story.FromIdentity (584).Facebook (); + return; + } + + // Initiate main loop + + UnixSignal[] killSignals = null; + + if (!Debugger.IsAttached) + { + killSignals = new UnixSignal[] { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGTERM) }; + } + + Console.WriteLine(" * FWN-Internal Backend starting up."); + + Console.Write (" * FWN-Internal Backend initializing websockets..."); + + _socketServer = new WebSocketServer (15615); + //_socketServer.SslConfiguration.ServerCertificate = new X509Certificate2 ("/etc/fwn/fwn-ops-wss.pfx", ""); + _socketServer.AddWebSocketService ("/Editing"); + // _socketServer.KeepClean = false; // as per the author's recommendation - this may be bad in the long run + _socketServer.Start(); + + Console.WriteLine(" done."); + + DateTime cycleStartTime = DateTime.UtcNow; + DateTime cycleEndTime; + + int lastSecond = cycleStartTime.Second; + int lastMinute = cycleStartTime.Minute; + int lastHour = cycleStartTime.Hour; + + bool exitFlag = false; + + while (!exitFlag) // exit is handled by signals handling at end of loop + { + cycleStartTime = DateTime.UtcNow; + cycleEndTime = cycleStartTime.AddSeconds(10); + + try + { + OnEveryTenSeconds(); + + if (cycleStartTime.Second < lastSecond) + { + OnEveryMinute(); + + if (cycleStartTime.Minute%5 == 0) + { + OnEveryFiveMinutes(); + } + + if (cycleStartTime.Minute%30 == 0) + { + OnEveryHalfHour(); + } + } + + if (cycleStartTime.Minute < lastMinute) + { + OnEveryHour(); + + if (DateTime.Now.Hour == 10 && DateTime.Today.DayOfWeek == DayOfWeek.Tuesday) + { + // OnTuesdayMorning(); + } + } + + if (cycleStartTime.Hour >= 12 && lastHour < 12) + { + // OnNoon(); + } + + if (cycleStartTime.Hour < lastHour) + { + // OnMidnight(); + } + } + + catch (Exception e) + { + Console.WriteLine(e.ToString()); + + // Note each "OnEvery..." catches its own errors and sends Exception mails, + // so that failure in one should not stop the others from running. This particular + // code should never run. + + // ExceptionMail.Send (new Exception ("Failed in swarmops-backend main loop", e), true); + } + + lastSecond = cycleStartTime.Second; + lastMinute = cycleStartTime.Minute; + lastHour = cycleStartTime.Hour; + + // Wait for a maximum of ten seconds (the difference between cycleStartTime and cycleEndTime) + + DateTime utcNow = DateTime.UtcNow; + while (utcNow < cycleEndTime && !exitFlag) + { + int signalIndex = 250; + + // Block until a SIGINT or SIGTERM signal is generated, or 1/4 second has passed. + // However, we can't do that in a development environment - it won't have the + // Mono.Posix assembly, and won't understand UnixSignals. So people running this in + // a dev environment will need to stop it manually. + + if (!Debugger.IsAttached) + { + signalIndex = UnixSignal.WaitAny(killSignals, 250); + } + else + { + TimeSpan timeLeft = (cycleEndTime - utcNow); + Thread.Sleep(250); + } + + if (signalIndex < 250) + { + exitFlag = true; + Console.WriteLine (" * FWN-Internal Backend caught signal " + killSignals[signalIndex].Signum + ", exiting"); + } + + utcNow = DateTime.UtcNow; + } + } + + _socketServer.Stop(); + Thread.Sleep (2000); + + Console.WriteLine(" * FWN-Internal Backend exiting"); + } + + private static WebSocketServer _socketServer; + + /* + + static void SocketServer_NewMessageReceived (WebSocketSession session, string message) + { + // Replicate to everybody + + foreach (var otherSession in session.AppServer.GetAllSessions()) + { + otherSession.Send (message); + } + }*/ + + + private static void OnEveryTenSeconds() + { + _socketServer.WebSocketServices.Broadcast ("{\"messageType\":\"Heartbeat\"}"); + } + + + private static void OnEveryMinute() + { + BroadcastTimestamp(); + } + + + private static void OnEveryFiveMinutes() + { + CheckPriorityPublish(); + CheckPublish(); + CheckStoryAges(); + RecordStoryMetrics(); + } + + + private static void OnEveryHalfHour() + { + } + + + + private static void OnEveryHour() + { + } + + + private static void CheckPriorityPublish() + { + Stories candidateStories = Stories.GetGlobalPublicationQueue (1); + + if (candidateStories.Count > 0 && candidateStories[0].Priority > 50) + { + Console.WriteLine("PRIORITY PUBLICATION!"); + candidateStories[0].Publish(); + BroadcastPublication(candidateStories[0]); + _socketServer.WebSocketServices.Broadcast(GetQueueInfoJson()); + } + } + + + private static void CheckPublish() + { + DateTime lastPublishUtc = Stories.GetLastPublished (1)[0].PublishDateTimeUtc; + int storyCount = Stories.GetGlobalPublicationQueueLength(); + DateTime nowUtc = DateTime.UtcNow; + + if (nowUtc.Hour > 18) + { + if (nowUtc.Hour != 19 || nowUtc.Minute != 0) + { + // For all events past 19:01 CET, do not process + return; + } + } + + if (nowUtc.Hour < 7) + { + // For all events before 07:00 CET, do not process + return; + } + + DateTime nextPublish = Stories.GetNextPublication (lastPublishUtc, storyCount, storyCount); + + //Console.WriteLine(" * FWN-Internal: Last pub was {0:HH:mm}, next scheduled for {1:HH:mm}, now {2:HH:mm}", lastPublishUtc, nextPublish, nowUtc); + + if (nowUtc > nextPublish) + { + PublishStory(); + _socketServer.WebSocketServices.Broadcast(GetQueueInfoJson()); + } + } + + private static void CheckStoryAges() + { + Stories stories = Stories.GetGlobalEditQueue (null); + DateTime utcNow = DateTime.UtcNow; + + bool storyTimedout = false; + + foreach (Story story in stories) + { + double ageMinutes = (utcNow - story.CreatedDateTimeUtc).TotalMinutes; + + // Console.WriteLine("Story #{0:N0} is {1:N0} minutes old ({4:N1} hours), last notify at {2} minutes ({3} hours)", story.Identity, ageMinutes, story.NotifiedAgeMinutes, story.NotifiedAgeMinutes / 60, ageMinutes / 60); + + if (ageMinutes > 48*60) // 48 hours: kill story + { + story.NotifiedAgeMinutes = 48*60; + BroadcastEdit(story.Edit (StoryEditType.TimedOut, null, "Story is 48 hours old. Rejected.")); + story.ChangeState (StoryState.TimedOut); + storyTimedout = true; + } + else if (ageMinutes > 36*60 && story.NotifiedAgeMinutes < 36*60) + { + story.NotifiedAgeMinutes = 36 * 60; + BroadcastEdit(story.Edit (StoryEditType.Warning, null, "Story is 36 hours old, and is about to time out.")); + } + else if (ageMinutes > 24 * 60 && story.NotifiedAgeMinutes < 24 * 60) + { + story.NotifiedAgeMinutes = 24 * 60; + BroadcastEdit(story.Edit(StoryEditType.Warning, null, "Story is 24 hours old. Please finalize and greenlight.")); + } + else if (ageMinutes > 12 * 60 && story.NotifiedAgeMinutes < 12 * 60) + { + story.NotifiedAgeMinutes = 12 * 60; + BroadcastEdit(story.Edit(StoryEditType.Warning, null, "Story is 12 hours old.")); + } + else if (ageMinutes > 6 * 60 && story.NotifiedAgeMinutes < 6 * 60) + { + story.NotifiedAgeMinutes = 6 * 60; + BroadcastEdit(story.Edit(StoryEditType.Warning, null, "Story is six hours old.")); + } + } + + if (storyTimedout) + { + _socketServer.WebSocketServices.Broadcast (GetQueueInfoJson()); + } + } + + + private static void BroadcastTimestamp() + { + JObject json = new JObject(); + json["messageType"] = "Timestamp"; + json["Timestamp"] = DateTime.UtcNow.ToUnix(); + + _socketServer.WebSocketServices.Broadcast (json.ToString()); + } + + + + private static void BroadcastEdit (StoryEdit edit, bool markSystem = true) + { + JObject json = new JObject(); + + json["messageType"] = "AddStoryEdit"; + json["EditTimestamp"] = edit.DateTimeUtc.ToUnix(); + json["StoryEditId"] = edit.Identity; + json["EditType"] = edit.EditType.ToString(); + json["Comment"] = edit.Comment; + json["PersonIdString"] = markSystem? "System": string.Empty; + json["StoryId"] = edit.StoryId; + + _socketServer.WebSocketServices.Broadcast(json.ToString()); + } + + + + + public static string GetQueueInfoJson() + { + JObject response = new JObject(); + response["messageType"] = "QueueInfo"; + response["EditCount"] = FwnDb.GetDatabaseForReading().GetStoryGlobalEditQueueCount(); + + int pubStoryCount = FwnDb.GetDatabaseForReading().GetStoryGlobalPublicationQueueCount(); + response["PubCount"] = pubStoryCount; + + if (pubStoryCount > 0) + { + response["PubNext"] = + Stories.GetNextPublication (Stories.GetLastPublished (1)[0].PublishDateTimeUtc, pubStoryCount, + pubStoryCount).ToString ("HH:mm") + " UTC"; + response["PubExtent"] = CountStoryExtent (pubStoryCount); + } + else + { + response["PubNext"] = "---"; + response["PubExtent"] = "Empty!"; + } + + return response.ToString(); + } + + private static string CountStoryExtent (int storyCount) + { + if (storyCount == 0) + { + return "Empty!"; + } + + int pubStoryTotal = FwnDb.GetDatabaseForReading().GetStoryGlobalPublicationQueueCount(); + DateTime lastPublication = Stories.GetLastPublished (1)[0].PublishDateTimeUtc; + + int pubStoryCount = pubStoryTotal; + while (pubStoryCount > 0) + { + lastPublication = Stories.GetNextPublication (lastPublication, pubStoryCount--, pubStoryTotal); + } + + if (lastPublication.Date == DateTime.UtcNow.Date) + { + return lastPublication.ToString ("HH:mm") + " UTC"; + } + return lastPublication.ToString ("ddd HH:mm") + " UTC"; + } + + + private static void PublishStory() + { + int dupeCheckCount = 2; + + Stories justPublishedStories = Stories.GetLastPublished (dupeCheckCount); + + Console.WriteLine ("Publication sequence. Dupecheck: "); + + Stories candidateStories = Stories.GetGlobalPublicationQueue (50); + + foreach (Story candidateStory in candidateStories) + { + Console.Write ("Trying story #{0:N0}... ", candidateStory.Identity); + + if (candidateStory.Priority > 49) + { + // Override everything, just get it out pronto + + Console.Write (" PRIORITY! Publishing..."); + candidateStory.Publish(); + BroadcastPublication (candidateStory); + Console.WriteLine(" done."); + return; + } + + int candidateGeographyId = candidateStory.GeographyId; + int candidateTopicId = candidateStory.TopicId; + + bool geoDupe = false; + bool topicDupe = false; + + foreach (Story justPublished in justPublishedStories) + { + if (justPublished.GeographyId == candidateGeographyId) + { + Console.Write ("repeating " + justPublished.GeographyName + ", "); + geoDupe = true; + } + if (justPublished.TopicId == candidateTopicId) + { + Console.Write ("repeating " + justPublished.Topic.Name + ", "); + topicDupe = true; + } + } + + if (!geoDupe & !topicDupe) + { + Console.Write ("good! Publishing..."); + candidateStory.Publish(); + BroadcastPublication(candidateStory); + Console.WriteLine(" done."); + return; + } + else + { + Console.WriteLine("rejected."); + } + } + + Console.Write ("No good candidates."); + + if (candidateStories.Count > 0) + { + Console.Write ("Publishing first story in queue anyway (#{0:N0})...", candidateStories[0].Identity); + candidateStories[0].Publish(); + BroadcastPublication(candidateStories[0]); + Console.WriteLine(" done."); + } + else + { + Console.WriteLine (" Nothing in queue at all, actually."); + } + + return; + } + + + static void BroadcastPublication (Story story) + { + JObject json = new JObject(); + json["messageType"] = "StoryPublished"; + json["StoryId"] = story.Identity; + + _socketServer.WebSocketServices.Broadcast (json.ToString()); + } + + + static void RecordStoryMetrics() + { + // Get Facebook data for the most recent 25 stories + // ------------------------------------------------ + + Stories stories = Stories.GetLastPublished (25); + foreach (Story story in stories) + { + try + { + story.UpdateFacebookMetrics(); + } + catch (InvalidDataException) + { + // Ignore if this story wasn't published to Facebook + } + } + + + // Get Twitter data (Twitter gives us about 200 stories) + // ----------------------------------------------------- + + ProcessStartInfo processInfo = new ProcessStartInfo("/usr/local/bin/twurl", " /1.1/statuses/user_timeline.json?screen_name=FalconwingNews&exclude_replies=true&count=200&include_rts=false"); + processInfo.EnvironmentVariables["HOME"] = "/root"; + processInfo.RedirectStandardOutput = true; + processInfo.RedirectStandardError = true; + processInfo.UseShellExecute = false; + + int twitterFollowerCount = 0; + + Process tweeting = Process.Start(processInfo); + + string output = tweeting.StandardOutput.ReadToEnd().Trim(); + if (output.Length == 0) + { + output = tweeting.StandardError.ReadToEnd().Trim(); + + if (output.Length == 0) + { + throw new InvalidDataException("Twurl returned zero data"); + } + } + + tweeting.WaitForExit(); + + JArray tweetArray = null; + try + { + tweetArray = JArray.Parse(output); + } + catch (JsonReaderException) + { + Console.WriteLine (output); + File.WriteAllText ("/tmp/JsonReaderException.txt", output); + + throw; + } + + foreach (JObject tweet in tweetArray.Children()) + { + if (twitterFollowerCount == 0) + { + twitterFollowerCount = Int32.Parse ((string) tweet["user"]["followers_count"]); + } + + Story story = Story.FromOutputChannelToken(1, (string)tweet["id_str"]); + StoryChannel storyChannel = StoryChannels.FromStoryAndChannel (story, 1); // the 1 is Twitter + + int shareCount = Int32.Parse ((string) tweet["retweet_count"]); + int starCount = Int32.Parse ((string) tweet["favorite_count"]); + + storyChannel.StoreMetrics (shareCount, starCount, 0); // we're not getting view count from Twitter here + int storyAwards = story.AwardCount; + shareCount = story.Metrics.Shares; // shares TOTAL, this time: sum of all output channels + + if (storyAwards < 1 && shareCount > 9) + { + BroadcastEdit(story.AddEditNote(StoryEditType.StarAward1, null, "Ten shares achieved"), false); + } + if (storyAwards < 2 && shareCount > 30) + { + BroadcastEdit(story.AddEditNote(StoryEditType.StarAward2, null, "Thirty shares achieved"), false); + } + if (storyAwards < 3 && shareCount > 99) + { + BroadcastEdit(story.AddEditNote(StoryEditType.StarAward3, null, "Three-digit share count achieved"), false); + } + if (storyAwards < 4 && shareCount > 310) + { + BroadcastEdit(story.AddEditNote(StoryEditType.StarAward4, null, "Three and a half digits of share count"), false); + } + if (storyAwards < 5 && shareCount > 999) + { + BroadcastEdit(story.AddEditNote(StoryEditType.StarAward5, null, "One thousand shares achieved"), false); + } + if (storyAwards < 6 && shareCount > 3100) + { + BroadcastEdit(story.AddEditNote(StoryEditType.StarAward6, null, "Four and a half digits of share count"), false); + } + } + + StoryChannel.SetFollowerCount (1, twitterFollowerCount); } } } diff --git a/FrontSocket/SocketServices/EditingService.cs b/FrontSocket/SocketServices/EditingService.cs new file mode 100644 index 00000000..4fe89d7f --- /dev/null +++ b/FrontSocket/SocketServices/EditingService.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Newtonsoft.Json.Linq; +using Swarmops.Logic.Security; +using WebSocketSharp; +using WebSocketSharp.Server; + +namespace Falconwing.Backend.SocketServices +{ + internal class EditingService: WebSocketBehavior + { + public EditingService() + { + base.IgnoreExtensions = true; // Necessary to suppress a Deflate exception that kills server otherwise + } + + protected override void OnMessage(WebSocketSharp.MessageEventArgs e) + { + // Basically just echo whatever's sent here + + JObject json = JObject.Parse (e.Data); + string serverRequest = (string) json["serverRequest"]; + + if (string.IsNullOrEmpty (serverRequest)) + { + // Not a server request, so just echo the contents to everybody + Sessions.Broadcast(e.Data); + } + + switch (serverRequest) + { + case "UpdateQueueCounts": + Sessions.Broadcast (Program.GetQueueInfoJson()); + break; + case "Ping": + Sessions.Broadcast("{\"messageType\":\"Heartbeat\"}"); + break; + default: + // do nothing; + break; + } + } + + protected override void OnOpen() + { + string authBase64 = Context.QueryString["Auth"]; + authBase64 = Uri.UnescapeDataString (authBase64); // Defensive programming - % sign does not exist in base64 so this won't ever collapse a working encoding + + _authority = Authority.FromEncryptedXml (authBase64); + + Console.WriteLine(" * FWN-Internal: " + _authority.Person.Name + " connected to socket"); + + base.OnOpen(); + + if (Context.QueryString["Notify"] != "false") + { + Sessions.Broadcast ("{\"messageType\":\"EditorCount\"," + + String.Format("\"editorCount\":\"{0}\"", Sessions.ActiveIDs.ToArray().Length) + '}'); + Send(Program.GetQueueInfoJson()); + } + } + + protected override void OnClose (CloseEventArgs e) + { + base.OnClose (e); + + Sessions.Broadcast("{\"messageType\":\"EditorCount\"," + String.Format("\"editorCount\":\"{0}\"", Sessions.ActiveIDs.ToArray().Length) + '}'); + } + + private Authority _authority = null; + } +} diff --git a/FrontSocket/TemplateCode/Dashboard.aspx b/FrontSocket/TemplateCode/Dashboard.aspx new file mode 100644 index 00000000..0a4427b2 --- /dev/null +++ b/FrontSocket/TemplateCode/Dashboard.aspx @@ -0,0 +1,1481 @@ +<%@ Page Title="" Language="C#" MasterPageFile="~/Master-v5.master" AutoEventWireup="true" CodeFile="Dashboard.aspx.cs" Inherits="Falconwing.Frontend.Dashboard" %> +<%@ Import Namespace="Falconwing.Logic" %> +<%@ Import Namespace="Falconwing.Logic.ExtensionMethods" %> +<%@ Register TagPrefix="Swarmops5" TagName="ComboBudgets" Src="~/Controls/v5/Financial/ComboBudgets.ascx" %> +<%@ Register TagPrefix="Swarmops5" TagName="CurrencyTextBox" Src="~/Controls/v5/Financial/CurrencyTextBox.ascx" %> + + + + + + <%-- ReSharper disable once InvalidValue --%> + + + + + + + +
+
+

STORIES IN YOUR EDIT POOL (...)

+ + +
" priority="<%# Eval ("Priority") %>"> +
+
+ " revisionId="<%#Eval ("RevisionCount") %>" width ="" alt="Story Thumbnail"/> +
+
+ " height="96" width="128" src="/Plugins/FalconwingMedia/Icons/iconshock-padlock-128x96px.png" style="display:none"/> +
+
+ " height="32" src="/Plugins/FalconwingMedia/Icons/iconshock-balloon-wrench-128x96px.png"/> +
+
+ " height="32" src="/Plugins/FalconwingMedia/Icons/iconshock-balloon-defer-128x96px.png"/> +
+
+ " height="32" src="/Images/Icons/iconshock-balloon-no-128x96px.png"/> +
+
+ " height="32" src="/Images/Icons/iconshock-balloon-yes-128x96px.png"/> +
+
+
+ <%#Eval ("Topic.Name") %>, <%# Eval("GeographyName") %>
+

"><%# Uri.UnescapeDataString ((string) Eval("Headline")) %>

+

"><%# Uri.UnescapeDataString ((string) Eval("Body")) %> <%# Eval("SourceLinksHtml") %>

+ " width="100%"> + +
Add a comment...
+
+
+
+ +

+
+
+
+
+

STORIES IN PUBLICATION QUEUE

+ + +
" priority="<%# Eval ("Priority")%>" > +
+
+ " revisionId="<%#Eval ("RevisionCount") %>" width ="" alt="Story Thumbnail"/> +
+
+ " height="96" width="128" src="/Images/Icons/iconshock-red-cross-128x96px.png" style="display:none"/> +
+
+ " height="32" src="/Images/Icons/iconshock-balloon-undo-128x96px.png"/> +
+
+
+ <%#Eval ("Topic.Name") %>, <%# Eval("GeographyName") %>
+

"><%# Uri.UnescapeDataString ((string) Eval("Headline")) %>

+

"><%# Uri.UnescapeDataString ((string) Eval("Body")) %> <%# Eval("SourceLinksHtml") %>

+
+
+
+ +

+
+
+
+
+

RECENTLY PUBLISHED

+ + +
" priority="<%# Eval ("Priority")%>" createdTimestamp="<%# Eval("CreatedUnix") %>" publishedTimestamp ="<%# Eval("PublishedUnix") %>"> +
+
+ " revisionId="<%#Eval ("RevisionCount") %>" width ="" alt="Story Thumbnail"/> +
+
+ " height="96" width="128" src="/Images/Icons/iconshock-red-cross-128x96px.png" style="display:none"/> +
+
+ + + + + + + + +
 SharesStarsViews
Twitter<%# Eval ("Metrics.Twitter.Shares") %><%# Eval ("Metrics.Twitter.Stars") %><%# Eval ("Metrics.Twitter.Views") %>
Facebook<%# Eval ("Metrics.Facebook.Shares") %><%# Eval ("Metrics.Facebook.Stars") %><%# Eval ("Metrics.Facebook.Views") %>
+
+
+
+ <%#Eval ("Topic.Name") %>, <%# Eval("GeographyName") %>
+

"><%# Uri.UnescapeDataString ((string) Eval("Headline")) %>

+

"><%# Uri.UnescapeDataString ((string) Eval("Body")) %> <%# Eval("SourceLinksHtml") %>

+ " width="100%"> +
+
+
+
+ +

+
+
+
+
+

RECENTLY REJECTED

+ + +
" priority="<%# Eval ("Priority")%>" createdTimestamp="<%# Eval("CreatedUnix") %>" publishedTimestamp ="<%# Eval("PublishedUnix") %>"> +
+
+ " revisionId="<%#Eval ("RevisionCount") %>" width ="" alt="Story Thumbnail"/> +
+
+ " height="96" width="128" src="/Images/Icons/iconshock-red-cross-128x96px.png" style="display:none"/> +
+
+
+ <%#Eval ("Topic.Name") %>, <%# Eval("GeographyName") %>
+

"><%# Uri.UnescapeDataString ((string) Eval("Headline")) %>

+

"><%# Uri.UnescapeDataString ((string) Eval("Body")) %> <%# Eval("SourceLinksHtml") %>

+ " width="100%"> +
+
+
+
+ +

+
+
+
+
+

MOST SHARES AND STARS (NOT DYNAMIC YET)

+ + +
" priority="<%# Eval ("Priority")%>" createdTimestamp="<%# Eval("CreatedUnix") %>" publishedTimestamp ="<%# Eval("PublishedUnix") %>"> +
+
+ " revisionId="<%#Eval ("RevisionCount") %>" width ="" alt="Story Thumbnail"/> +
+
+ " height="96" width="128" src="/Images/Icons/iconshock-red-cross-128x96px.png" style="display:none"/> +
+
+ + + + + + + + +
 SharesStarsViews
Twitter<%# Eval ("Metrics.Twitter.Shares") %><%# Eval ("Metrics.Twitter.Stars") %><%# Eval ("Metrics.Twitter.Views") %>
Facebook<%# Eval ("Metrics.Facebook.Shares") %><%# Eval ("Metrics.Facebook.Stars") %><%# Eval ("Metrics.Facebook.Views") %>
+
+
+
+ <%#Eval ("Topic.Name") %>, <%# Eval("GeographyName") %>
+

"><%# Uri.UnescapeDataString ((string) Eval("Headline")) %>

+

"><%# Uri.UnescapeDataString ((string) Eval("Body")) %> <%# Eval("SourceLinksHtml") %>

+ " width="100%"> +
+
+
+
+ +

+
+
+
+
+

YOUR STORIES

+ + +
" priority="<%# Eval ("Priority")%>" createdTimestamp="<%# Eval("CreatedUnix") %>" publishedTimestamp ="<%# Eval("PublishedUnix") %>"> +
+
+ " revisionId="<%#Eval ("RevisionCount") %>" width ="" alt="Story Thumbnail"/> +
+
+ " height="96" width="128" src="/Images/Icons/iconshock-red-cross-128x96px.png" style="display:none"/> +
+
+ + + + + + + + +
 SharesStarsViews
Twitter<%# Eval ("Metrics.Twitter.Shares") %><%# Eval ("Metrics.Twitter.Stars") %><%# Eval ("Metrics.Twitter.Views") %>
Facebook<%# Eval ("Metrics.Facebook.Shares") %><%# Eval ("Metrics.Facebook.Stars") %><%# Eval ("Metrics.Facebook.Views") %>
+
+
+
+ <%#Eval ("Topic.Name") %>, <%# Eval("GeographyName") %>
+

"><%# Uri.UnescapeDataString ((string) Eval("Headline")) %>

+

"><%# Uri.UnescapeDataString ((string) Eval("Body")) %> <%# Eval("SourceLinksHtml") %>

+ " width="100%"> +
+
+
+
+ +

+
+
+
+
+

YOUR REVENUE (UNDER CONSTRUCTION)

+
+
+ + + +

EDITING STORY #X,XYZ

+
+ ​
+ ​ +
+ ​
+ — + ​
+ ​
+ +
+ +
+
+ + + +

CREATING PHOTO

+

We're publishing under EU laws, which means that we may freely republish anything already published openly on the web without + coming into conflict with copyright monopolies (see ECJ Svensson v. Svensson 2014). However, we still need to provide proper photo credit. + If the photo is of a person, write their full name for later searchability (like "Yanis Varoufakis").

+
+ ​
+ ​
+ ​
+ ​
+ +
+ +
+
+ +
+ + + + +

ACTIONS 2

+ +
+
+ +
+
+ +

LAB

+ +
+
+ + + + + + + +
Connected---
Editors online---
Global edit pool---
Publication queue---
Next publication---
Pubqueue lasts until---
+
+
+ +
+ diff --git a/FrontSocket/TemplateCode/Dashboard.aspx.cs b/FrontSocket/TemplateCode/Dashboard.aspx.cs new file mode 100644 index 00000000..4e3ddefc --- /dev/null +++ b/FrontSocket/TemplateCode/Dashboard.aspx.cs @@ -0,0 +1,715 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Imaging; +using System.Globalization; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using System.Web; +using System.Web.Services; +using System.Web.UI; +using System.Web.UI.WebControls; +using Falconwing.Basic; +using Falconwing.Logic; +using Falconwing.Logic.ExtensionMethods; +using NBitcoin.BouncyCastle.Crypto.Generators; +using Newtonsoft.Json.Linq; +using Swarmops.Common.Exceptions; +using Swarmops.Logic.Cache; +using Swarmops.Logic.Structure; +using Swarmops.Logic.Financial; +using Swarmops.Logic.Security; +using Swarmops.Logic.Support; +using WebSocketSharp; + +namespace Falconwing.Frontend +{ + public partial class Dashboard : PageV5Base + { + protected void Page_Load(object sender, EventArgs e) + { + // Stories.Reward (new DateTime(2015,10,1)); + + this.PageTitle = "FWN Dashboard"; + InfoBoxLiteral = "These are stories in the edit queue. Edit or greenlight them for FACTS, FORMAT, FIT, and FUNNY."; + + PageAccessRequired = new Access(AccessAspect.Null); // (AccessAspect.Participant); + + this.RepeaterStories.DataSource = Stories.GetGlobalEditQueue(CurrentUser, 10); + this.RepeaterStories.DataBind(); + + this.RepeaterPublishQueue.DataSource = Stories.GetGlobalPublicationQueue (10); + this.RepeaterPublishQueue.DataBind(); + + this.RepeaterPublished.DataSource = Stories.GetLastPublished (10); + this.RepeaterPublished.DataBind(); + + this.RepeaterRejected.DataSource = Stories.GetLastRejected (10); + this.RepeaterRejected.DataBind(); + + this.RepeaterStars.DataSource = Stories.GetMostShared (20, 28); + this.RepeaterStars.DataBind(); + + this.RepeaterAuthor.DataSource = Stories.GetStoriesFromAuthor (CurrentUser, 10); + this.RepeaterAuthor.DataBind(); + + /* + this.DropCategories.Style[HtmlTextWriterStyle.Width] = "324px"; + this.TextBody.Style[HtmlTextWriterStyle.Width] = "304px";*/ + + if (!Page.IsPostBack) + { + this.DropCategories.Items.Add(new ListItem("-- DRAFT --", "8")); + this.DropCategories.Items.Add(new ListItem("War and Conflict", "1")); + this.DropCategories.Items.Add(new ListItem("Law and Politics", "7")); + this.DropCategories.Items.Add(new ListItem("Finance / Cryptocurrency", "2")); + this.DropCategories.Items.Add(new ListItem("General Local News", "3")); + this.DropCategories.Items.Add(new ListItem("Feelgood News", "4")); + this.DropCategories.Items.Add(new ListItem("Science and Tech", "5")); + this.DropCategories.Items.Add(new ListItem("Gaming / Entertainment", "6")); + + this.DropCountries.Items.Add(new ListItem("-- Global", "--")); + this.DropCountries.Items.Add(new ListItem("AT Austria", "AT")); + this.DropCountries.Items.Add(new ListItem("BE Belgium", "BE")); + this.DropCountries.Items.Add(new ListItem("BG Bulgaria", "BG")); + this.DropCountries.Items.Add(new ListItem("CH Switzerland", "CH")); + this.DropCountries.Items.Add(new ListItem("CY Cyprus", "CY")); + this.DropCountries.Items.Add(new ListItem("CZ Czech Rep.", "CZ")); + this.DropCountries.Items.Add(new ListItem("DE Germany", "DE")); + this.DropCountries.Items.Add(new ListItem("DK Denmark", "DK")); + this.DropCountries.Items.Add(new ListItem("EE Estonia", "EE")); + this.DropCountries.Items.Add(new ListItem("ES Spain", "ES")); + this.DropCountries.Items.Add(new ListItem("FI Finland", "FI")); + this.DropCountries.Items.Add(new ListItem("FR France", "FR")); + this.DropCountries.Items.Add(new ListItem("GR Greece", "GR")); + this.DropCountries.Items.Add(new ListItem("HR Croatia", "HR")); + this.DropCountries.Items.Add(new ListItem("HU Hungary", "HU")); + this.DropCountries.Items.Add(new ListItem("IE Ireland", "IE")); + this.DropCountries.Items.Add(new ListItem("IS Iceland", "IS")); + this.DropCountries.Items.Add(new ListItem("IT Italy", "IT")); + this.DropCountries.Items.Add(new ListItem("LV Latvia", "LV")); + this.DropCountries.Items.Add(new ListItem("LT Lithuania", "LT")); + this.DropCountries.Items.Add(new ListItem("LU Luxembourg", "LU")); + this.DropCountries.Items.Add(new ListItem("MT Malta", "MT")); + this.DropCountries.Items.Add(new ListItem("NO Norway", "NO")); + this.DropCountries.Items.Add(new ListItem("NL Netherlands", "NL")); + this.DropCountries.Items.Add(new ListItem("PL Poland", "PL")); + this.DropCountries.Items.Add(new ListItem("PT Portugal", "PT")); + this.DropCountries.Items.Add(new ListItem("RO Romania", "RO")); + this.DropCountries.Items.Add(new ListItem("SE Sweden", "SE")); + this.DropCountries.Items.Add(new ListItem("SI Slovenia", "SI")); + this.DropCountries.Items.Add(new ListItem("SK Slovakia", "SK")); + this.DropCountries.Items.Add(new ListItem("UK United Kingdom", "UK")); + } + } + + [WebMethod] + public static AjaxCallResult RenderPreview(int topicId, string geographyCode, string headline, string body, int photoId) + { + try + { + if (string.IsNullOrEmpty (geographyCode)) + { + geographyCode = "--"; + } + + int geographyId = 1; + if (geographyCode != "--") + { + geographyId = -Country.FromCode(geographyCode).Identity; + } + + Bitmap renderedStory = Story.RenderThumbnail(headline, body, Topic.FromIdentity(topicId), geographyId, photoId); + MemoryStream stream = new MemoryStream(); + renderedStory.Save(stream, ImageFormat.Png); + + byte[] imageBytes = stream.ToArray(); + string base64Image = Convert.ToBase64String(imageBytes); + + return new AjaxCallResult { Success = true, DisplayMessage = base64Image }; + } + catch (Exception e) + { + return new AjaxCallResult { Success = false, DisplayMessage = e.ToString() }; + } + } + + + [WebMethod] + public static AjaxCallResult RenderThumbnail(int storyId) + { + try + { + string cacheKey = "StoryThumbnail" + storyId; + string renderedThumbnailBase64 = (string) GuidCache.Get (cacheKey); + + if (string.IsNullOrEmpty (renderedThumbnailBase64)) + { + Story story = Story.FromIdentity(storyId); + renderedThumbnailBase64 = story.ThumbnailBase64; + } + + return new AjaxCallResult { Success = true, DisplayMessage = renderedThumbnailBase64 }; + } + catch (Exception e) + { + return new AjaxCallResult { Success = false, DisplayMessage = e.ToString() }; + } + } + + + + [WebMethod] + public static StoryDataCallResult LockStoryForEditing(int storyId, int revisionId) + { + AuthenticationData authData = GetAuthenticationDataAndCulture(); + + try + { + Story story = Story.FromIdentity(storyId); + story.Lock(authData.CurrentUser, StoryEditType.Edit); + + return new StoryDataCallResult { Success = true, + StoryHeadline = story.Headline, + StoryBody = story.Body, + StorySources = story.SourceLinks, + StoryPhotoDescription = (story.PhotoId != 0? story.Photo.Description : "---"), + StoryPhotoId = story.PhotoId, + StoryTopicId = story.TopicId, StoryCountryCode = (story.GeographyId == 1 ? "--" : (story.GeographyId < 0 ? Country.FromIdentity(-story.GeographyId).Code : story.Geography.Country.Code)) }; + } + catch (Exception exception) + { + return new StoryDataCallResult { Success = false, DisplayMessage = exception.ToString() }; + } + } + + [WebMethod] + public static AjaxCallResult CancelStoryEdit(int storyId) + { + AuthenticationData authData = GetAuthenticationDataAndCulture(); + Story story = Story.FromIdentity(storyId); + story.Unlock(authData.CurrentUser); + + return new AjaxCallResult { Success = true }; + } + + [WebMethod] + public static AjaxCallResult CommitStoryEdit(int storyId, int revisionId, string countryCode, int topicId, string headline, string body, string sources, string comment, int photoId) + { + try + { + + AuthenticationData authData = GetAuthenticationDataAndCulture(); + + headline = Uri.UnescapeDataString (headline); + + headline = headline.Trim(); + if (headline.EndsWith (".")) + { + headline = headline.TrimEnd ('.'); + } + headline = headline.Replace (" : ", ": ").Replace (" ?", "?").Replace (" ", " "); + + headline = Uri.EscapeDataString (headline); + + if (string.IsNullOrEmpty(countryCode)) + { + countryCode = "--"; + } + + string uri = "ws://fwn-internal:15615/Editing?Notify=false&Auth=" + + Uri.EscapeDataString(authData.Authority.ToEncryptedXml()); + using ( + var socketClient = + new WebSocket (uri)) + { + socketClient.Connect(); + + if (storyId > 0) + { + Country country = null; + if (countryCode != "--") + { + country = Country.FromCode (countryCode); + } + + Story story = Story.FromIdentity (storyId); + StoryEdit storyEdit = story.Edit (StoryEditType.Edit, authData.CurrentUser, + Topic.FromIdentity (topicId), null, + country, headline, body, sources.Replace (" ", " ").Trim(), comment, photoId); + + story = Story.FromIdentity (storyId); // reload + + string personString = "#" + authData.CurrentUser.Identity.ToString("N0"); + if (authData.CurrentUser.Identity == story.CreatedByPersonId) + { + personString = "Author"; + } + + JObject storyEditedNotify = new JObject(); + storyEditedNotify["messageType"] = "StoryEdited"; + storyEditedNotify["StoryId"] = story.Identity; + storyEditedNotify["Headline"] = headline; + storyEditedNotify["Body"] = body; + storyEditedNotify["Sources"] = story.SourceLinksHtml; + storyEditedNotify["TopicGeography"] = story.Topic.Name + ", " + story.GeographyName; + + socketClient.Send (storyEditedNotify.ToString()); + socketClient.Ping(); + socketClient.Send("{\"messageType\":\"AddStoryEdit\",\"EditTimestamp\":\"" + DateTime.UtcNow.ToUnix() + "\",\"StoryId\":\"" + story.Identity + + "\",\"StoryEditId\":\"" + storyEdit.Identity + + "\",\"EditType\":\"Edit\",\"Comment\":\"" + comment.Replace ("\"", "\\\"") + + "\",\"PersonIdString\":\"" + personString + + "\"}"); + + story.Unlock (authData.CurrentUser); + } + else + { + Story story = Story.Create (headline, body, Topic.FromIdentity (topicId), + (countryCode == "--" ? 1 : -Country.FromCode (countryCode).Identity), sources, + authData.CurrentUser); + if (photoId > 0) + { + story.Photo = Photo.FromIdentity (photoId); + } + socketClient.Send("{\"serverRequest\":\"UpdateQueueCounts\"}"); + socketClient.Ping(); + socketClient.Send("{\"messageType\":\"StoryCreated\"}"); + } + + socketClient.Ping(); + socketClient.Close(); + } + + return new AjaxCallResult { Success = true }; + } + catch (Exception exception) + { + return new AjaxCallResult + { + Success = false, + DisplayMessage = "An exception was thrown [CommitStoryEdit]:

" + exception.ToString() + }; + } + } + + [WebMethod] + public static AjaxCallResult LightStory(int storyId, int revisionId, string lightType, string comment) + { + AuthenticationData authData = GetAuthenticationDataAndCulture(); + + // TODO: Authorize + + Story story = Story.FromIdentity(storyId); + + try + { + + // Begin by not confirming GREENLIGHTS unless the RevisionId is correct. Work from there. + + string encryptedAuth = authData.Authority.ToEncryptedXml(); + encryptedAuth = Uri.EscapeDataString (encryptedAuth); + + string uri = "ws://fwn-internal:15615/Editing?Notify=false&Auth=" + encryptedAuth; + + using ( + var socketClient = + new WebSocket (uri)) + { + socketClient.Connect(); + StoryEdit newEdit = null; + + string personString = "#" + authData.CurrentUser.Identity.ToString("N0"); + if (authData.CurrentUser.Identity == story.CreatedByPersonId) + { + personString = "Author"; + } + + switch (lightType.ToLowerInvariant()) + { + case "comment": + newEdit = story.Edit (StoryEditType.Comment, authData.CurrentUser, comment); + socketClient.Send("{\"messageType\":\"AddStoryEdit\",\"EditTimestamp\":\"" + DateTime.UtcNow.ToUnix() + "\",\"StoryId\":\"" + story.Identity + "\",\"StoryEditId\":\"" + newEdit.Identity + "\",\"EditType\":\"Comment\",\"Comment\":\"" + comment.Replace("\"", "\\\"") + "\",\"PersonIdString\":\"" + personString + "\"}"); + + break; + case "defer": + story.Edit (StoryEditType.Defer, authData.CurrentUser); + break; + case "red": + // Ignore revision, just redlight + + newEdit = story.Edit (StoryEditType.Redlight, authData.CurrentUser, comment); + socketClient.Send("{\"messageType\":\"AddStoryEdit\",\"EditTimestamp\":\"" + DateTime.UtcNow.ToUnix() + "\",\"StoryId\":\"" + story.Identity + "\",\"StoryEditId\":\"" + newEdit.Identity + "\",\"EditType\":\"Redlight\",\"Comment\":\"" + comment.Replace("\"", "\\\"") + "\",\"PersonIdString\":\"" + personString + "\"}"); + if (GetStoryApprovalRating (story) < -3) + { + newEdit = story.Edit (StoryEditType.Rejected, authData.CurrentUser, + "Below rejection threshold"); + story.ChangeState (StoryState.Rejected); + socketClient.Send("{\"serverRequest\":\"UpdateQueueCounts\"}"); + socketClient.Send("{\"messageType\":\"AddStoryEdit\",\"EditTimestamp\":\"" + DateTime.UtcNow.ToUnix() + "\",\"StoryId\":\"" + story.Identity + "\",\"StoryEditId\":\"" + newEdit.Identity + "\",\"EditType\":\"Rejected\",\"Comment\":\"Below rejection threshold\",\"PersonIdString\":\"" + personString + "\"}"); + socketClient.Send("{\"messageType\":\"StoryStateChange\",\"StoryId\":\"" + story.Identity + "\",\"StateChange\":\"StoryRejected\"}"); + } + + break; + case "green": + if (story.TopicId == 8) + { + return new AjaxCallResult + { + Success = false, + DisplayMessage = + "This is a DRAFT story. It cannot be greenlit until taken out of draft mode. Check for placeholders, then move it to a publication-grade topic before greenlighting." + }; + } + + if (story.RevisionCount > revisionId) + { + StoryEdits edits = story.Edits; + for (int index = story.RevisionCount; index < edits.Count; index++) + { + if (edits[index].EditType == StoryEditType.Edit) + { + // The story was edited after being sent to client; concurrency error, order reload + return new AjaxCallResult() {Success = false, DisplayMessage = "Reload"}; + } + } + } + + newEdit = story.Edit (StoryEditType.Greenlight, authData.CurrentUser, comment); + socketClient.Send("{\"messageType\":\"AddStoryEdit\",\"EditTimestamp\":\"" + DateTime.UtcNow.ToUnix() + "\",\"StoryId\":\"" + story.Identity + "\",\"StoryEditId\":\"" + newEdit.Identity + "\",\"EditType\":\"Greenlight\",\"Comment\":\"\",\"PersonIdString\":\"" + personString + "\"}"); + if (GetStoryApprovalRating (story) > 2) // Three people + { + newEdit = story.Edit(StoryEditType.ToPublishQueue, authData.CurrentUser, "Moved to publication queue"); + story.ChangeState(StoryState.PublicationQueue); + socketClient.Send("{\"serverRequest\":\"UpdateQueueCounts\"}"); + socketClient.Send("{\"messageType\":\"AddStoryEdit\",\"EditTimestamp\":\"" + DateTime.UtcNow.ToUnix() + "\",\"StoryId\":\"" + story.Identity + "\",\"StoryEditId\":\"" + newEdit.Identity + "\",\"EditType\":\"ToPublishQueue\",\"Comment\":\"Moved to publication queue\",\"PersonIdString\":\"" + personString + "\"}"); + socketClient.Send("{\"messageType\":\"StoryStateChange\",\"StoryId\":\"" + story.Identity + "\",\"StateChange\":\"ApprovedForPublishing\"}"); + } + + break; + default: + return new AjaxCallResult + { + Success = false, + DisplayMessage = "Unknown lighting color in call" + }; + } + + socketClient.Ping(); // causes a small delay + socketClient.Close(); + } + + return new AjaxCallResult { Success = true }; + } + catch (DatabaseConcurrencyException dbException) + { + return new AjaxCallResult { Success = false, DisplayMessage = "Exception thrown:

" + dbException.ToString() }; + } + } + + private static int GetStoryApprovalRating(Story story) + { + StoryEdits edits = story.Edits; + int approvalRating = 0; + + foreach (StoryEdit edit in edits) + { + if (edit.EditType == StoryEditType.Greenlight) + { + approvalRating++; + if (edit.PersonId == 1) + { + approvalRating++; // mine are slightly heavier + } + } + else if (edit.EditType == StoryEditType.Redlight) + { + approvalRating -= 2; + if (edit.PersonId == 1) + { + approvalRating -= 10000; // yeah, I get to redlight with a vengeance + } + } + else if (edit.EditType == StoryEditType.Edit) + { + approvalRating = 0; // An edit resets rating + } + } + + return approvalRating; + } + + + [WebMethod] + public static StoryQueueCallResult GetStoryEditPool(int count) + { + AuthenticationData authData = GetAuthenticationDataAndCulture(); + return GetDynamicStoryList (Stories.GetGlobalEditQueue (authData.CurrentUser, count), true); + } + + private static StoryQueueCallResult GetDynamicStoryList (Stories stories, bool unpublished = false) + { + List responseList = new List(); + foreach (Story story in stories) + { + responseList.Add(new QueuedStory + { + Body = story.Body + " " + story.SourceLinksHtml, + StoryId = story.Identity, + Priority = story.Priority, + Headline = story.Headline, + RevisionId = story.RevisionCount, + TopicGeography = story.Topic.Name + ", " + story.GeographyName, + CreatedTimestampUnix = story.CreatedUnix, + PublishedTimestampUnix = unpublished? 0: story.PublishedUnix + }); + } + + if (!unpublished) + { + responseList.Reverse(); // published stories come newest-first, unpublished oldest-first + } + + return new StoryQueueCallResult { Success = true, Stories = responseList.ToArray() }; + } + + [WebMethod] + public static StoryQueueCallResult GetStoryPublishQueue(int count) + { + AuthenticationData authData = GetAuthenticationDataAndCulture(); + return GetDynamicStoryList (Stories.GetGlobalPublicationQueue (count)); + } + + [WebMethod] + public static StoryQueueCallResult GetStoriesPublished(int count) + { + AuthenticationData authData = GetAuthenticationDataAndCulture(); + + return GetDynamicStoryList (Stories.GetLastPublished (count)); + } + + [WebMethod] + public static StoryQueueCallResult GetStoriesRejected (int count) + { + AuthenticationData authData = GetAuthenticationDataAndCulture(); + return GetDynamicStoryList (Stories.GetLastRejected (count)); + } + + [WebMethod] + public static StoryQueueCallResult GetStoriesAuthor (int count) + { + AuthenticationData authData = GetAuthenticationDataAndCulture(); + return GetDynamicStoryList (Stories.GetStoriesFromAuthor (authData.CurrentUser, count)); + } + + [WebMethod] + public static AjaxCallResult GetEditPoolCount() + { + AuthenticationData authData = GetAuthenticationDataAndCulture(); + return new AjaxCallResult + { + Success = true, + DisplayMessage = Stories.GetGlobalEditQueueLength (authData.CurrentUser).ToString ("N0") + }; + } + + [WebMethod] + public static StoryQueueCallResult GetStory (int storyId) + { + AuthenticationData authData = GetAuthenticationDataAndCulture(); + Story story = Story.FromIdentity (storyId); + + return GetDynamicStoryList (Stories.FromSingle (story)); + } + + + [WebMethod] + public static StoryEditsCallResult GetStoryEdits (int storyId) + { + AuthenticationData authData = GetAuthenticationDataAndCulture(); + + List result = new List(); + + Story story = Story.FromIdentity (storyId); + StoryEdits edits = story.Edits; + foreach (StoryEdit edit in edits) + { + if (edit.EditType != StoryEditType.Defer) + { + string personString = "#" + edit.PersonId.ToString ("N0"); + if (edit.PersonId == 0) + { + personString = "System"; + } + if (edit.PersonId == story.CreatedByPersonId) + { + personString = "Author"; + } + + result.Add (new QueuedStoryEdit { Comment = edit.Comment, EditType = edit.EditType.ToString(), PersonIdString = personString, StoryEditId = edit.Identity, EditTimestamp = edit.DateTimeUtc.ToUnix() }); + } + } + + return new StoryEditsCallResult {Success = true, StoryId = storyId, StoryEdits = result.ToArray()}; + } + + + [WebMethod] + public static StoryEditsCallResult GetStoryHistory (int storyId) + { + List result = new List(); + + Dictionary approvedTypes = new Dictionary(); + approvedTypes[StoryEditType.Redlight] = + approvedTypes[StoryEditType.Greenlight] = + approvedTypes[StoryEditType.Rejected] = + approvedTypes[StoryEditType.TimedOut] = + approvedTypes[StoryEditType.Warning] = + approvedTypes[StoryEditType.ToPublishQueue] = + approvedTypes[StoryEditType.Published] = true; + + Story story = Story.FromIdentity(storyId); + StoryEdits edits = story.Edits; + foreach (StoryEdit edit in edits) + { + if (approvedTypes.ContainsKey (edit.EditType) || edit.EditType.ToString().StartsWith ("StarAward")) + { + result.Add(new QueuedStoryEdit { Comment = edit.Comment, EditType = edit.EditType.ToString(), PersonIdString = "", StoryEditId = edit.Identity, EditTimestamp = edit.DateTimeUtc.ToUnix() }); + } + } + + return new StoryEditsCallResult { Success = true, StoryId = storyId, StoryEdits = result.ToArray() }; + } + + [WebMethod] + public static AjaxCallResult CreatePhoto (string sourceUrl, string description, string personName, + string photoCredit) + { + AuthenticationData authData = GetAuthenticationDataAndCulture(); + + sourceUrl = sourceUrl.Replace ("https://", "http://"); // because of damn broken Mono cert store + + string guidString = Guid.NewGuid().ToString ("N"); + + string fileNameBase = guidString + "-" + authData.CurrentUser.Identity.ToString("X8").ToLowerInvariant() + "-" + + authData.CurrentOrganization.Identity.ToString("X4").ToLowerInvariant(); + + DateTime utcNow = DateTime.UtcNow; + + string fileFolder = utcNow.Year.ToString("0000") + Path.DirectorySeparatorChar + + utcNow.Month.ToString("00") + Path.DirectorySeparatorChar + + utcNow.Day.ToString("00"); + + string storageRoot = "/var/lib/swarmops/upload/"; + + if (!Directory.Exists("/var/lib/swarmops/upload/" + fileFolder)) + { + Directory.CreateDirectory(storageRoot + fileFolder); + } + + int fileCounter = 0; + string fileName = string.Empty; + + + do + { + fileCounter++; + fileName = fileNameBase + "-" + fileCounter.ToString("X2").ToLowerInvariant(); + } while (File.Exists(storageRoot + fileFolder + Path.DirectorySeparatorChar + fileName) && fileCounter < 512); + + if (fileCounter >= 512) + { + return new AjaxCallResult {Success = false, DisplayMessage = "Unable to determine filename"}; + } + + long fileLength = 0; + + using (WebClient client = new WebClient()) + { + try + { + byte[] newImage = client.DownloadData (sourceUrl); + fileLength = newImage.LongLength; + File.WriteAllBytes (storageRoot + fileFolder + Path.DirectorySeparatorChar + fileName, newImage); + } + catch (Exception e) + { + return new AjaxCallResult {Success = false, DisplayMessage = "Exception thrown:

" + e.ToString()}; + } + } + + try + { + Document document = Document.Create(fileFolder + Path.DirectorySeparatorChar + fileName, sourceUrl, + fileLength, guidString, null, authData.CurrentUser); + + Photo photo = Photo.Create(document, description, personName, photoCredit, sourceUrl); + + return new AjaxCallResult { Success = true, DisplayMessage = photo.Identity.ToString() }; + } + catch (Exception e) + { + return new AjaxCallResult { Success = false, DisplayMessage = "Exception thrown:

" + e.ToString() }; + } + + } + + } + + + public class QueuedStory + { + public int StoryId { get; set; } + public int RevisionId { get; set; } + public int Priority { get; set; } + public string TopicGeography { get; set; } + public string Headline { get; set; } + public string Body { get; set; } + public int CreatedTimestampUnix { get; set; } + public int PublishedTimestampUnix { get; set; } + } + + + public class StoryQueueCallResult : AjaxCallResult + { + public QueuedStory[] Stories { get; set; } + } + + + public class QueuedStoryEdit + { + public int StoryEditId { get; set; } + public string PersonIdString { get; set; } + public string Comment { get; set; } + public string EditType { get; set; } + public int EditTimestamp { get; set; } + } + + + public class StoryEditsCallResult : AjaxCallResult + { + public int StoryId { get; set; } + public QueuedStoryEdit[] StoryEdits { get; set; } + } + + + public class StoryDataCallResult : AjaxCallResult + { + public string StoryHeadline { get; set; } + public string StoryBody { get; set; } + public string StorySources { get; set; } + public string StoryPhotoDescription { get; set; } + public int StoryPhotoId { get; set; } + public int StoryGeographyId { get; set; } + public int StoryGeographyName { get; set; } + public int StoryTopicId { get; set; } + public int StoryTopicName { get; set; } + public string StoryCountryCode { get; set; } + public int StoryRevisionId { get; set; } + public bool StoryVisible { get; set; } + } +} \ No newline at end of file diff --git a/Logic/ExtensionMethods/Bitmap.cs b/Logic/ExtensionMethods/Bitmap.cs new file mode 100644 index 00000000..5e82acce --- /dev/null +++ b/Logic/ExtensionMethods/Bitmap.cs @@ -0,0 +1,270 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using System.Drawing; +using System.Drawing.Imaging; + +namespace Falconwing.Logic.ExtensionMethods +{ + public static partial class DummyContainer { + + public static Bitmap AdjustColor (this Bitmap sourceBitmap, double redTint, double greenTint, double blueTint) + { + BitmapData sourceData = sourceBitmap.LockBits (new Rectangle (0, 0, + sourceBitmap.Width, sourceBitmap.Height), + ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); + + + byte[] pixelBuffer = new byte[sourceData.Stride*sourceData.Height]; + + + Marshal.Copy (sourceData.Scan0, pixelBuffer, 0, pixelBuffer.Length); + + + sourceBitmap.UnlockBits (sourceData); + + + double blue = 0; + double green = 0; + double red = 0; + + + for (int k = 0; k + 4 < pixelBuffer.Length; k += 4) + { + blue = pixelBuffer[k] + (255 - pixelBuffer[k])*blueTint; + green = pixelBuffer[k + 1] + (255 - pixelBuffer[k + 1])*greenTint; + red = pixelBuffer[k + 2] + (255 - pixelBuffer[k + 2])*redTint; + + + if (blue > 255) + { + blue = 255; + } + + + if (green > 255) + { + green = 255; + } + + + if (red > 255) + { + red = 255; + } + + + pixelBuffer[k] = (byte) blue; + pixelBuffer[k + 1] = (byte) green; + pixelBuffer[k + 2] = (byte) red; + + + } + + + Bitmap resultBitmap = new Bitmap (sourceBitmap.Width, sourceBitmap.Height); + + + BitmapData resultData = resultBitmap.LockBits (new Rectangle (0, 0, + resultBitmap.Width, resultBitmap.Height), + ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + + + Marshal.Copy (pixelBuffer, 0, resultData.Scan0, pixelBuffer.Length); + resultBitmap.UnlockBits (resultData); + + + return resultBitmap; + } + + public static Bitmap AdjustSaturation(this Bitmap sourceBitmap, double saturation) + { + BitmapData sourceData = sourceBitmap.LockBits(new Rectangle(0, 0, + sourceBitmap.Width, sourceBitmap.Height), + ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); + + byte[] pixelBuffer = new byte[sourceData.Stride * sourceData.Height]; + + Marshal.Copy(sourceData.Scan0, pixelBuffer, 0, pixelBuffer.Length); + + sourceBitmap.UnlockBits(sourceData); + + double blue = 0; + double green = 0; + double red = 0; + + + for (int k = 0; k + 4 < pixelBuffer.Length; k += 4) + { + double luminance = pixelBuffer[k + 2]*0.2126 + pixelBuffer[k + 1]*0.7152 + pixelBuffer[k]*0.0722; + + blue = pixelBuffer[k]*saturation + (1-saturation) * luminance; + green = pixelBuffer[k + 1] * saturation + (1 - saturation) * luminance; + red = pixelBuffer[k + 2] * saturation + (1 - saturation) * luminance; + + + if (blue > 255) + { + blue = 255; + } + + + if (green > 255) + { + green = 255; + } + + + if (red > 255) + { + red = 255; + } + + + pixelBuffer[k] = (byte)blue; + pixelBuffer[k + 1] = (byte)green; + pixelBuffer[k + 2] = (byte)red; + + + } + + + Bitmap resultBitmap = new Bitmap(sourceBitmap.Width, sourceBitmap.Height); + + + BitmapData resultData = resultBitmap.LockBits(new Rectangle(0, 0, + resultBitmap.Width, resultBitmap.Height), + ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + + + Marshal.Copy(pixelBuffer, 0, resultData.Scan0, pixelBuffer.Length); + resultBitmap.UnlockBits(resultData); + + + return resultBitmap; + } + + + public static Bitmap AdjustBrightness(this Bitmap sourceBitmap, double brightness) + { + BitmapData sourceData = sourceBitmap.LockBits(new Rectangle(0, 0, + sourceBitmap.Width, sourceBitmap.Height), + ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); + + + byte[] pixelBuffer = new byte[sourceData.Stride * sourceData.Height]; + + + Marshal.Copy(sourceData.Scan0, pixelBuffer, 0, pixelBuffer.Length); + + + sourceBitmap.UnlockBits(sourceData); + + + double blue = 0; + double green = 0; + double red = 0; + + + for (int k = 0; k + 4 < pixelBuffer.Length; k += 4) + { + blue = pixelBuffer[k] * brightness; + green = pixelBuffer[k + 1] * brightness; + red = pixelBuffer[k + 2] * brightness; + + + if (blue > 255) + { + blue = 255; + } + + + if (green > 255) + { + green = 255; + } + + + if (red > 255) + { + red = 255; + } + + + pixelBuffer[k] = (byte)blue; + pixelBuffer[k + 1] = (byte)green; + pixelBuffer[k + 2] = (byte)red; + + + } + + + Bitmap resultBitmap = new Bitmap(sourceBitmap.Width, sourceBitmap.Height); + + + BitmapData resultData = resultBitmap.LockBits(new Rectangle(0, 0, + resultBitmap.Width, resultBitmap.Height), + ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + + + Marshal.Copy(pixelBuffer, 0, resultData.Scan0, pixelBuffer.Length); + resultBitmap.UnlockBits(resultData); + + + return resultBitmap; + } + + + public static Bitmap Blur(this Bitmap image, Int32 blurSize) + { + Bitmap blurred = new Bitmap(image.Width, image.Height); + + // make an exact copy of the bitmap provided + using (Graphics graphics = Graphics.FromImage(blurred)) + graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height), + new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel); + + // look at every pixel in the image + for (Int32 xx = 0; xx < image.Width; xx++) + { + for (Int32 yy = 0; yy < image.Height; yy++) + { + Int32 avgR = 0, avgG = 0, avgB = 0, avgA = 0; + Int32 blurPixelCount = 0; + + // average the color of the red, green and blue for each pixel in the + // blur size while making sure you don't go outside the image bounds + for (Int32 x = xx; (x < xx + blurSize && x < image.Width); x++) + { + for (Int32 y = yy; (y < yy + blurSize && y < image.Height); y++) + { + Color pixel = blurred.GetPixel(x, y); + + avgR += pixel.R; + avgG += pixel.G; + avgB += pixel.B; + avgA += pixel.A; + + blurPixelCount++; + } + } + + avgR = avgR / blurPixelCount; + avgG = avgG / blurPixelCount; + avgB = avgB / blurPixelCount; + avgA = avgA / blurPixelCount; + + // now that we know the average for the blur size, set each pixel to that color + for (Int32 x = xx; x < xx + blurSize && x < image.Width && x < image.Width; x++) + for (Int32 y = yy; y < yy + blurSize && y < image.Height && y < image.Height; y++) + blurred.SetPixel(x, y, Color.FromArgb(avgA, avgR, avgG, avgB)); + } + } + + return blurred; + } + } +} diff --git a/Logic/ExtensionMethods/Color.cs b/Logic/ExtensionMethods/Color.cs new file mode 100644 index 00000000..e4ec386c --- /dev/null +++ b/Logic/ExtensionMethods/Color.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using System.Drawing; +using System.Drawing.Imaging; + +namespace Falconwing.Logic.ExtensionMethods +{ + public static partial class DummyContainer + { + public static int GetLuminance (this Color color) + { + return (int) (color.R * 0.2126 + color.G * 0.7152 + color.B * 0.0722); + } + } +} diff --git a/Logic/ExtensionMethods/DateTime.cs b/Logic/ExtensionMethods/DateTime.cs new file mode 100644 index 00000000..6b55d01b --- /dev/null +++ b/Logic/ExtensionMethods/DateTime.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Falconwing.Logic.ExtensionMethods +{ + public static partial class DummyWrapper + { + public static Int32 ToUnix (this DateTime source) + { + // Assumes DateTime is already UTC + + return (Int32)(source.Subtract(new DateTime(1970, 1, 1, 0, 0, 0,DateTimeKind.Utc))).TotalSeconds; + } + } +}