Esempio n. 1
0
        public static bool Initialize()
        {
            foreach (var user in getAll <User>(Dem2Hub.docDB))
            {
                all.Add(user);
            }
            foreach (var voting in getAll <Voting>(Dem2Hub.docDB))
            {
                all.Add(voting);
            }
            foreach (var vote in getAll <Vote>(Dem2Hub.docDB))
            {
                all.Add(vote);
            }
            foreach (var comment in getAll <Comment>(Dem2Hub.docDB))
            {
                all.Add(comment);
            }
            // var entity = session.Load<Company>(companyId);
            var stats = Dem2Hub.GetStatistics();

            Console.WriteLine("Repository initialized with {0} users, {1} votings, {2} votes and {3} comments", stats.userCount, stats.votingCount, stats.voteCount, stats.commentCount);

            return(true);
        }
Esempio n. 2
0
 void ServerClientEntity_OnChange(ServerClientEntity o, EventArgs e)
 {
     foreach (var subscriber in subscribedUsers)
     {
         var op = new entityOperation()
         {
             operation = 'u', entity = this
         };
         Dem2Hub.sendItTo(op, subscriber.Value.connection);
     }
 }
Esempio n. 3
0
 public void sendTo(IWebSocketConnection socket)
 {
     Dem2Hub.sendItTo(this, socket);
     if (operation == 'u' || operation == 'c')
     {
         var subs = new Subscription()
         {
             onEntityId = entity.Id
         };                                                         //we presume, that the entity will be displayed at the client, so we subscribe him
         subs.subscribe(socket);
     }
 }
Esempio n. 4
0
        internal void resolveEntityRequest(IWebSocketConnection socket, JObject receivedObj)
        {
            switch (operation)
            {
            case 'c':       //create new user generated entity
                /*
                 * //Example shows json which creates new Vote for the present user
                 * {
                 *   "msgType": "entity",
                 *   "operation": "c",
                 *   "className": "Vote",
                 *   "entity": {"subjectID": "voting/215", "Agrees": true}
                 * }
                 *
                 * // TODO implement create spam check here
                 */
            {
                try
                {
                    var  className  = (string)receivedObj["className"];
                    Type type       = Type.GetType("Dem2UserCreated." + className);
                    var  sourceJSON = receivedObj["entity"].ToString();

                    var instance = JsonConvert.DeserializeObject(sourceJSON, type, new IsoDateTimeConverter());
                    entity         = (ServerClientEntity)instance;
                    entity.OwnerId = fromUser.Id;
                    entity.Subscribe(fromUser);
                    switch (className)
                    {
                    case "Vote":
                        var newVote = (Vote)instance;              //the serialized entity must be initialized
                        newVote.InitVote(fromUser);                //the after initialization, we return the entity back
                        Console.WriteLine("Created new vote with Id {0}", newVote.Id);
                        break;

                    case "Comment":
                        var newComment = (Comment)instance;
                        EntityRepository.Add(newComment);
                        Console.WriteLine("Created new comment with Id {0}", newComment.Id);
                        break;

                    case "Listing":
                        var newListing = (Listing)instance;
                        newListing.JSONQuery.sourceJSON = receivedObj["entity"]["JSONQuery"].ToString();;
                        var added = EntityRepository.Add(newListing);
                        if (added == false)
                        {
                            entity = EntityRepository.allListings.Single(x => x.JSONQuery.sourceJSON == sourceJSON);
                            entity.Subscribe(fromUser);
                            sendTo(socket);
                        }

                        Console.WriteLine("Created new listing with Id {0}", newListing.Id);
                        break;

                    default:
                        break;
                    }

                    //var op = new entityOperation() { operation = 'c', entity = instance as ServerClientEntity };
                    //
                    Console.WriteLine("Object {0} created", instance.ToString());
                }
                catch (Exception)
                {
                    throw;
                }
            }
            break;

            case 'r':       //read an entity
                /*
                 * Example shows json for this branch
                 * {
                 * "msgType": "entity",
                 * "operation": "r",
                 * "entity":{
                 *    "Id": "user/132"
                 * }
                 * }*/
                respondToReadRequest(socket);
                break;

            case 'u':       //read an entity
                /*
                 * Example shows json for this branch
                 * {
                 * "msgType": "entity",
                 * "operation": "r",
                 * "entity":{
                 *    "Id": "user/132"
                 * }
                 * }*/
                respondToUpdateRequest(receivedObj);
                break;

            case 'd':     //delete an entity
                /*
                 * {
                 *  "msgType": "entity",
                 *  "operation": "d",
                 *  "entity": {"Id": "voting/215"}
                 * }
                 *
                 */
            {
                string IdPrefixStr = entity.Id.Split('/')[0];
                Type   type        = EntityRepository.GetRepoTypeById(IdPrefixStr);

                var instance = JsonConvert.DeserializeObject(receivedObj["entity"].ToString(), type, new IsoDateTimeConverter());

                {
                    var Id = (string)receivedObj["entity"]["Id"];
                    ServerClientEntity toDelete = EntityRepository.GetEntityFromSetsByID(Id);
                    var deletor = socket.ConnectionInfo.Cookies["user"];
                    if (deletor == toDelete.OwnerId)
                    {
                        var success = toDelete.Delete();
                        if (success)
                        {
                            if (toDelete is Vote)
                            {           // update the subject
                                Vote aVote   = (Vote)toDelete;
                                var  subject = EntityRepository.GetEntityFromSetsByID(aVote.subjectId);
                                subject.IncrementVersion();
                            }
                            var op = new entityOperation()
                            {
                                operation = 'd', entity = new ServerClientEntity(toDelete.Id, toDelete.version)
                            };
                            Dem2Hub.sendItTo(op, socket);
                        }
                    }
                    else
                    {
                        var err = new ServerError()
                        {
                            message = "sorry, you can't delete the entity id " + Id
                        };
                        Dem2Hub.sendItTo(err, socket);
                    }
                }
            }
            break;

            default:
                Console.WriteLine("Unknown type of request: {0}", operation);
                break;
            }
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            ServiceStack.Text.JsConfig.DateHandler = ServiceStack.Text.JsonDateHandler.ISO8601;
            var           allSockets = new List <IWebSocketConnection>();
            DocumentStore docDB      = new DocumentStore {
                Url = "http://localhost:8080"
            };                                                                                //when on the same machine where Raven runs

            //DocumentStore docDB = new DocumentStore { Url = "http://dem2.cz:9191" };            //when on any other

#if IS_RUNNING_ON_SERVER
            FleckLog.Level = LogLevel.Error;
            var WSserver = new WebSocketServer("http://dem2.cz:8181");
#else
            FleckLog.Level = LogLevel.Debug;
            var WSserver = new WebSocketServer("ws://localhost:8181");
#endif
            Dem2Hub.Initialize(docDB);
            // temporary scraping hack
            //var q = new Query() { pageSize = 10, descending = true, sortByProp = "getResolveCount", ofTypeInStr = "comments",
            //    propertiesEqualValues = new Dictionary<string, string>() { {"parentId","votings/162"} }
            //};
            //var l = new Dem2UserCreated.Listing(q);
            //foreach (var item in l.list)
            //{
            //    Console.WriteLine("item " + item.ToString());
            //}
            //for (int i = 874; i < 884; i++)
            //{
            //    var voting = new Voting("http://www.psp.cz/sqw/historie.sqw?t="+i);
            //}


            WSserver.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("Opened connection from IP: {0}", socket.ConnectionInfo.ClientIpAddress);
                    var socketOpened = true;
                    if (allSockets.Any(x => x.ConnectionInfo.ClientIpAddress == socket.ConnectionInfo.ClientIpAddress))
                    {
                        if (allSockets.FindAll(x => x.ConnectionInfo.ClientIpAddress == socket.ConnectionInfo.ClientIpAddress).Count >= oneIPConnectionCap)
                        {
                            socket.Send("Sorry, the server has a cap of 20 simultanoues connections per IP, you cannot connect until there will be less connections");
                            socket.Close();
                            socketOpened = false;
                        }
                    }
                    if (socketOpened)
                    {
                        allSockets.Add(socket);
                        socket.ConnectionInfo.Cookies["authentication"] = "anonymous";
                    }
                };
                socket.OnClose = () =>
                {
                    switch (socket.ConnectionInfo.Cookies["authentication"])
                    {
                    case "awaitingFBResponse":

                        break;

                    case "authenticated":

                        var user = EntityRepository.allUsers.First(x => x.connection == socket);
                        user.lastDisconnected = DateTime.Now;
                        user.UnsubscribeAll();
                        socket.ConnectionInfo.Cookies.Remove("authenticated");
                        socket.ConnectionInfo.Cookies.Remove("user");
                        break;

                    default:
                        break;
                    }

                    Console.WriteLine("Closed connection from IP: {0}", socket.ConnectionInfo.ClientIpAddress);
                    allSockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    //Console.WriteLine("Message from IP: {0}, {1}", socket.ConnectionInfo.ClientIpAddress, message);
                    Dem2Hub.ResolveMessage(message, socket);
                };
            });


            var input = Console.ReadLine();
            while (input != "exit")
            {
                input = Console.ReadLine();
            }
        }