using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
namespace PhotoServiceDaemon
static ConcurrentQueue<string[]> _queue;
static public object QueueHandlerSendsPendingLock = new object();
static public int QueueHandlerSendsPending = 0;
static async void Send(string[] args)
lock (QueueHandlerSendsPendingLock)
QueueHandlerSendsPending++;
var result = NetworkCommunication.Send(args);
FileCommunication.WriteSuccess(args);
FileCommunication.WriteResend(args);
while (!NetworkCommunication.Errors.TryRemove(args, out s)) { await Task.Delay(50); }
FileCommunication.WriteError(args, s);
static bool isTimerFiredAtLeastOnce = false;
static async void QueueHandler_Elapsed(object sender, ElapsedEventArgs e)
var _alreadyQueued = Task.Factory.StartNew(FileCommunication.GetResendQueue);
var temporaryCollection = new List<string[]>();
while (!_queue.TryDequeue(out tmp)) await Task.Delay(10);
temporaryCollection.Add(tmp);
while (!_alreadyQueued.Result.IsEmpty)
while (!_alreadyQueued.Result.TryDequeue(out tmp)) await Task.Delay(10);
temporaryCollection.Add(tmp);
var tmpCount = temporaryCollection.Count;
Parallel.ForEach(temporaryCollection, Send);
for (var i = 0; i < tmpCount; i++)
Send(temporaryCollection[i]);
isTimerFiredAtLeastOnce = true;
static void RestartAsAdmin()
var startInfo = new ProcessStartInfo("PhotoServiceDaemon.exe") { Verb = "runas" };
Process.Start(startInfo);
static void ExecuteCommand(string command)
ProcessStartInfo processInfo;
processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
process = Process.Start(processInfo);
static void Main(string[] args)
_queue = new ConcurrentQueue<string[]>();
var QueueHandler = new Timer(5 * 60 * 1000);
QueueHandler.Elapsed += QueueHandler_Elapsed;
QueueHandler.AutoReset = true;
var listener = new HttpListener();
listener.Prefixes.Add("http://127.0.0.1:6556/");
catch (HttpListenerException e)
var context = listener.GetContext();
Console.WriteLine("got request");
var _request = context.Request;
var response = context.Response;
var req = _request.QueryString;
var request = new Dictionary<string, string>();
foreach (var key in req.AllKeys)
request.Add(key, req[key]);
Console.WriteLine("{0}: {1}\n", key, key == "additionalInfo" ? WebUtility.UrlDecode(req[key]) : req[key]);
System.IO.Stream outstream;
if (request.Count < 2 || !request.ContainsKey("imageUrl"))
#region send Bad Request response
response.AddHeader("Access-Control-Allow-Origin", "*");
response.StatusCode = 400;
buff = Encoding.UTF8.GetBytes("Incorrect request: querystring either contains lesser than two params or doesn't specify imageUrl param");
response.ContentLength64 = buff.LongLength;
outstream = response.OutputStream;
outstream.Write(buff, 0, buff.Length);
var img = request["imageUrl"];
if (request.ContainsKey("additionalInfo"))
info = WebUtility.UrlDecode(request["additionalInfo"]);
foreach (var key in request.Keys)
if (key == NetworkCommunication.mail)
foreach (var email in request[key].Split(", ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
_queue.Enqueue(info == null ? new string[] { img, key, email } : new string[] { img, key, email, info });
if (NetworkCommunication.SocialNetworkList.Contains(key))
if (Convert.ToBoolean(request[key]))
_queue.Enqueue(info == null ? new string[] { img, key } : new string[] { img, key, info });
response.AddHeader("Access-Control-Allow-Origin", "*");
buff = Encoding.UTF8.GetBytes("OK");
response.ContentLength64 = buff.LongLength;
outstream = response.OutputStream;
outstream.Write(buff, 0, buff.Length);
if (request.ContainsKey("killdaemon") && Convert.ToBoolean(request["killdaemon"]))
lock (QueueHandlerSendsPendingLock) local = QueueHandlerSendsPending;
while (local > 0 || !isTimerFiredAtLeastOnce || _queue.Count > 0)
System.Threading.Thread.Sleep(10000);
lock (QueueHandlerSendsPendingLock) local = QueueHandlerSendsPending;
FileCommunication.Dispose();