Example #1
0
        public static void UpdateUser(FoeUser user)
        {
            SqlConnection conn = FoeServerDb.OpenDb();
            SqlCommand    cmd  = conn.CreateCommand();

            cmd.CommandText =
                "update Users " +
                "set " +
                "Email=@email, " +
                "UserId=@userId, " +
                "DtCreated=@dtCreated, " +
                "ProcessorEmail=@processorEmail " +
                "where Id=@id";

            cmd.Parameters.Add("@id", SqlDbType.Int);
            cmd.Parameters.Add("@email", SqlDbType.NVarChar, 256);
            cmd.Parameters.Add("@userId", SqlDbType.NVarChar, 128);
            cmd.Parameters.Add("@dtCreated", SqlDbType.DateTime);
            cmd.Parameters.Add("@processorEmail", SqlDbType.NVarChar, 256);

            cmd.Prepare();

            // add user to db
            cmd.Parameters["@id"].Value             = user.Id;
            cmd.Parameters["@email"].Value          = user.Email;
            cmd.Parameters["@userId"].Value         = user.UserId;
            cmd.Parameters["@dtCreated"].Value      = user.DtCreated;
            cmd.Parameters["@processorEmail"].Value = user.ProcessorEmail;

            // execute command
            cmd.ExecuteNonQuery();

            conn.Close();
        }
Example #2
0
        /// <summary>
        /// Add user to db
        /// </summary>
        /// <param name="user">The user object containing the user info.</param>
        public static void AddUser(FoeUser user)
        {
            SqlConnection conn = FoeServerDb.OpenDb();
            SqlCommand    cmd  = conn.CreateCommand();

            cmd.CommandText =
                "insert into Users (Email, UserId, DtCreated, ProcessorEmail) " +
                "values (@email, @userId, @dtCreated, @processorEmail)";

            cmd.Parameters.Add("@email", SqlDbType.NVarChar, 256);
            cmd.Parameters.Add("@userId", SqlDbType.NVarChar, 128);
            cmd.Parameters.Add("@dtCreated", SqlDbType.DateTime);
            cmd.Parameters.Add("@processorEmail", SqlDbType.NVarChar, 256);

            cmd.Prepare();

            // add user to db
            cmd.Parameters["@email"].Value          = user.Email;
            cmd.Parameters["@userId"].Value         = user.UserId;
            cmd.Parameters["@dtCreated"].Value      = user.DtCreated;
            cmd.Parameters["@processorEmail"].Value = user.ProcessorEmail;

            // execute command
            cmd.ExecuteNonQuery();

            conn.Close();
        }
Example #3
0
        static void TestGetUser()
        {
            // Test GetUser()
            try
            {
                PrintTitle("Testing GetUser()");

                FoeUser user = FoeServerUser.GetUser(sampleEmail);
                if (user == null)
                {
                    Console.WriteLine("Cannot find " + sampleEmail);
                }
                else
                {
                    Console.WriteLine("User found.");
                    Console.WriteLine("ID:                " + user.Id);
                    Console.WriteLine("Email:             " + user.Email);
                    Console.WriteLine("User ID:           " + user.UserId);
                    Console.WriteLine("Date Created:      " + user.DtCreated.ToString());
                    Console.WriteLine("Verification Code: " + user.VerificationCode);
                    Console.WriteLine("Is Verified:       " + (user.IsVerified ? "true" : "false"));
                    Console.WriteLine("Date Verified:     " + ((user.DtVerified == null) ? "NULL" : user.DtVerified.ToString()));
                    Console.WriteLine("Processor Email:   " + user.ProcessorEmail);
                }
            }
            catch (Exception except)
            {
                Console.WriteLine(except.ToString());
            }
        }
Example #4
0
 static void TestUpdateUser()
 {
     // Test UpdateUser()
     try
     {
         PrintTitle("Test UpdateUser()");
         Console.WriteLine("Loading user info for " + sampleEmail);
         FoeUser updateUser = FoeServerUser.GetUser(sampleEmail);
         Console.WriteLine("Resetting IsVerified and clear DtVerified.");
         updateUser.IsVerified = false;
         updateUser.DtVerified = null;
         Console.WriteLine("Calling UpdateUser().");
         FoeServerUser.UpdateUser(updateUser);
         Console.WriteLine("Done.");
     }
     catch (Exception except)
     {
         Console.WriteLine(except.ToString());
     }
 }
Example #5
0
        /// <summary>
        /// Register new user.
        /// </summary>
        /// <param name="email">User's email address</param>
        /// <returns>The user object containing the new user's information</returns>
        public static FoeUser RegisterUser(string email)
        {
            FoeUser user = GetUser(email);

            if (user == null)
            {
                // create user info
                user = new FoeUser();

                user.Id             = null;
                user.Email          = email.Trim().ToLower();
                user.UserId         = GenerateUserId(email);
                user.DtCreated      = DateTime.Now;
                user.ProcessorEmail = AssignProcessorEmail(email);

                // add user to database
                AddUser(user);
            }

            return(user);
        }
Example #6
0
        /// <summary>
        /// Get user information in an FoeUser object.
        /// </summary>
        /// <param name="userEmail">user's email address</param>
        /// <returns>A FoeUser object populated with user info. If user is not found, then null is returned.</returns>
        public static FoeUser GetUser(string userEmail)
        {
            FoeUser user = null;

            // open connection to FOE DB
            SqlConnection conn = FoeServerDb.OpenDb();
            SqlCommand    cmd  = conn.CreateCommand();

            // get user
            string sql = "select * from Users where Email=@email";

            cmd.CommandText = sql;
            cmd.Parameters.Add("@email", SqlDbType.NVarChar, 256);
            cmd.Prepare();
            cmd.Parameters["@email"].Value = userEmail.Trim().ToLower();
            SqlDataReader reader = cmd.ExecuteReader();

            // see if user exists
            if (reader.HasRows)
            {
                reader.Read();

                // create a new user object;
                user = new FoeUser();

                // populate user information
                user.Id             = FoeServerDb.GetInt32(reader, "Id");
                user.Email          = FoeServerDb.GetString(reader, "Email");
                user.UserId         = FoeServerDb.GetString(reader, "UserId");
                user.DtCreated      = FoeServerDb.GetDateTime(reader, "DtCreated");
                user.ProcessorEmail = FoeServerDb.GetString(reader, "ProcessorEmail");
            }

            reader.Close();
            conn.Close();

            return(user);
        }
        /// <summary>
        /// Download email messages from the POP3 server for a given Foe message processor.
        /// </summary>
        /// <param name="server">POP3 server information</param>
        /// <param name="processorEmail">The current Foe message processor's email address.</param>
        public static void DownloadMessages(PopServer server, string processorEmail)
        {
            // connect to POP3 server and download messages
            //FoeDebug.Print("Connecting to POP3 server...");
            POPClient popClient = new POPClient();

            popClient.IsUsingSsl = server.SslEnabled;

            popClient.Disconnect();
            popClient.Connect(server.ServerName, server.Port);
            popClient.Authenticate(server.UserName, server.Password);

            FoeDebug.Print("Connected to POP3.");

            // get mail count
            int count = popClient.GetMessageCount();

            FoeDebug.Print("Server reported " + count.ToString() + " messages.");

            // go through each message, from newest to oldest
            for (int i = count; i >= 1; i -= 1)
            {
                //FoeDebug.Print("Opening mail message...");

                OpenPOP.MIMEParser.Message msg = popClient.GetMessage(i, true);
                if (msg != null)
                {
                    // Get subject and verify sender identity
                    // Subject line in the mail header should look like one of the followings:
                    //
                    // Normal request (for news feed and content):
                    //   Subject: Request <Request ID> by <User ID>
                    //
                    // Registration request:
                    //   Subject: Register <Request ID> by Newbie
                    //
                    // where:
                    // Request ID is the request ID generated by the Foe client
                    // User ID is the user's ID as assigned by the server

                    //FoeDebug.Print("Message is not null. Getting message details.");

                    string subject   = msg.Subject;
                    string fromEmail = msg.FromEmail;

                    //FoeDebug.Print("Subject: " + subject);
                    //FoeDebug.Print("From: " + fromEmail);

                    // parse subject line
                    string[] tokens = subject.Trim().Split(new char[] { ' ' });
                    if (tokens.Length == 4)
                    {
                        // check what type of request is it
                        string requestType = tokens[0].ToUpper();
                        string requestId   = tokens[1];
                        string userId      = tokens[3];

                        FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message,
                                         "subject: " + subject + "requestType: " + requestType);
                        if (requestType.ToUpper().CompareTo("REGISTE") == 0)
                        {
                            //FoeDebug.Print("This is a registration message.");
                            // It's a registration request
                            SaveRegistrationRequest(requestId, fromEmail, processorEmail);

                            FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message,
                                             "Received registration request from " + fromEmail);
                        }
                        else if (requestType.ToUpper().CompareTo("CATALOG") == 0)
                        {
                            // get user info by email address
                            FoeUser user = FoeServerUser.GetUser(fromEmail);

                            // verify user's email against the user ID
                            if ((user != null) && (userId == user.UserId) && (processorEmail == user.ProcessorEmail))
                            {
                                FoeDebug.Print("User verified.");

                                // the user's identity is verified
                                SaveCatalogRequest(requestId, user.Email, processorEmail);
                            }
                            else
                            {
                                //FoeDebug.Print("User is not registered. Request not processed.");
                                FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning,
                                                 "Received content request from unregistered user " + fromEmail);
                            }
                        }
                        else if (requestType.ToUpper().CompareTo("CONTENT") == 0)
                        {
                            //FoeDebug.Print("This is a content request message.");

                            // It's a content request.
                            // We need to verify the user's identify first.

                            //FoeDebug.Print("Verifying user identity...");

                            // get user info by email address
                            FoeUser user = FoeServerUser.GetUser(fromEmail);

                            // verify user's email against the user ID
                            if ((user != null) && (userId == user.UserId) && (processorEmail == user.ProcessorEmail))
                            {
                                FoeDebug.Print("User verified.");

                                // the user's identity is verified
                                // get the full message body
                                OpenPOP.MIMEParser.Message wholeMsg = popClient.GetMessage(i, false);
                                string msgBody = (string)wholeMsg.MessageBody[0];

                                try
                                {
                                    // decompress it
                                    byte[] compressedMsg   = Convert.FromBase64String(msgBody);
                                    byte[] decompressedMsg = CompressionManager.Decompress(compressedMsg);
                                    string foe             = Encoding.UTF8.GetString(decompressedMsg);

                                    string[] catalogs = foe.Trim().Split(new char[] { ',' });
                                    // save request
                                    if (catalogs.Length == 0)
                                    {
                                        return;
                                    }
                                    SaveContentRequest(requestId, user.Email, catalogs, processorEmail);

                                    //FoeDebug.Print("Request saved and pending processing.");
                                    FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message,
                                                     "Received content request from verified user " + fromEmail);
                                }
                                catch (Exception except)
                                {
                                    // the message is likely malformed
                                    // so just ignore it
                                    FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning,
                                                     "Received malformed content request from verified user " + fromEmail + "\r\n" +
                                                     except.ToString() +
                                                     "Raw message:\r\n" + msgBody + "\r\n");

                                    //throw except;
                                }
                            }
                            else
                            {
                                //FoeDebug.Print("User is not registered. Request not processed.");
                                FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning,
                                                 "Received content request from unregistered user " + fromEmail);
                            }
                        }
                        else if (requestType.ToUpper().CompareTo("FEED") == 0)
                        {
                            //FoeDebug.Print("This is a content request message.");

                            // It's a content request.
                            // We need to verify the user's identify first.

                            //FoeDebug.Print("Verifying user identity...");

                            // get user info by email address
                            FoeUser user = FoeServerUser.GetUser(fromEmail);

                            // verify user's email against the user ID
                            if ((user != null) && (userId == user.UserId) && (processorEmail == user.ProcessorEmail))
                            {
                                FoeDebug.Print("User verified.");

                                // the user's identity is verified
                                // get the full message body
                                OpenPOP.MIMEParser.Message wholeMsg = popClient.GetMessage(i, false);
                                string msgBody = (string)wholeMsg.MessageBody[0];

                                try
                                {
                                    // decompress it
                                    byte[] compressedMsg   = Convert.FromBase64String(msgBody);
                                    byte[] decompressedMsg = CompressionManager.Decompress(compressedMsg);
                                    string foe             = Encoding.UTF8.GetString(decompressedMsg);

                                    string[] array = foe.Trim().Split(new char[] { ',' });
                                    // save request
                                    if (array.Length == 0)
                                    {
                                        return;
                                    }
                                    SaveFeedRequest(requestId, user.Email, array, processorEmail);

                                    //FoeDebug.Print("Request saved and pending processing.");
                                    FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message,
                                                     "Received feed request from verified user " + fromEmail);
                                }
                                catch (Exception except)
                                {
                                    // the message is likely malformed
                                    // so just ignore it
                                    FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning,
                                                     "Received malformed feed request from verified user " + fromEmail + "\r\n" +
                                                     except.ToString() +
                                                     "Raw message:\r\n" + msgBody + "\r\n");

                                    //throw except;
                                }
                            }
                            else
                            {
                                //FoeDebug.Print("User is not registered. Request not processed.");
                                FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning,
                                                 "Received content request from unregistered user " + fromEmail);
                            }
                        }
                        else
                        {
                            // Non-Foe message
                            FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message,
                                             "Received non-Foe message from " + fromEmail);
                        }
                    }
                    else
                    {
                        // Non-Foe message
                        FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message,
                                         "Received non-Foe message from " + fromEmail);
                    }

                    // Delete the current message
                    popClient.DeleteMessage(i);
                }
            }
            popClient.Disconnect();
        }
        public static void SendRssCache(string catalogCode, string userEmail, string requestId, bool isAutoSubscription)
        {
            // Load RSS
            string rss = FoeServerCatalog.GetRssCache(catalogCode);

            if (rss == null)
            {
                throw new Exception("RSS feed " + catalogCode + " does not exist.");
            }

            // Load User info
            FoeUser user = FoeServerUser.GetUser(userEmail);

            if (user == null)
            {
                throw new Exception("User " + userEmail + " does not exist.");
            }

            // Prepare Foe Message

            /*
             * string rssBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(feed.Rss));
             * FoeMessage foeMessage = new FoeMessage();
             * foeMessage.Add(new FoeMessageItem("CatalogCode", feed.Code));
             * foeMessage.Add(new FoeMessageItem("Rss", rssBase64));
             */

            FoeDebug.Print("Generated Foe Message.");

            // Send reply to user
            try
            {
                FoeServerMessage.SendMessage(
                    FoeServerMessage.GetDefaultSmtpServer(),
                    FoeServerRegistry.Get("ProcessorEmail"),
                    userEmail,
                    SubjectGenerator.ReplySubject(RequestType.Content, catalogCode, requestId, FoeServerUser.GetUser(userEmail).UserId),
                    rss);

                FoeDebug.Print("Sent reply to user.");

                // Add user to auto-subscription list
                if (!isAutoSubscription)
                {
                    FoeServerAutoSubscribe.Add(userEmail, catalogCode, requestId);
                }
                else
                {
                    // If the caller function is just processing AutoSubscription, then
                    // we don't want to recreate the subscription, simply update the
                    // current subscription.
                    FoeServerAutoSubscribe.Update(userEmail, catalogCode, requestId);
                }

                FoeDebug.Print("Added user to Auto Subscription.");
            }
            catch (Exception except)
            {
                FoeDebug.Print("FoeServerCatalog: Error sending email.");
                FoeDebug.Print(except.ToString());
            }
        }
        private void DoFeedAdd()
        {
            //FoeDebug.Print("Loading requests...");
            bool   hasError = false;
            string message  = "";
            // Load content requests
            FoeRequester     req            = null;
            FoeServerRequest requestManager = new FoeServerRequest(RequestType.Feed, FoeServerRegistry.Get("ProcessorEmail"));

            while ((req = requestManager.GetNextRequest()) != null)
            {
                //FoeDebug.Print("Processing request from " + req.UserEmail + " with request ID " + req.RequestId);

                // Check what contents are requested


                // Get user info
                FoeUser user = FoeServerUser.GetUser(req.UserEmail);
                if (user == null)
                {
                    //FoeDebug.Print("User not registered. Skip this request.");
                    //FoeDebug.Print("---------------------------------------");

                    // User is not registered, mark this request as "E" (Error) and skip to the next one
                    requestManager.UpdateRequestStatus(req, "E");

                    FoeServerLog.Add(_processName, FoeServerLog.LogType.Warning, "User " + user.Email + " not registered. Discard content request.");

                    continue;
                }

                //FoeDebug.Print("User verified.");

                // Process request
                List <CatalogItem> catalogs = FoeServerCatalog.GetCatalog(); // get all the catalogs on server

                if (catalogs != null)
                {
                    //FoeDebug.Print("Generated Foe Message.");

                    foreach (CatalogItem catalog in catalogs)
                    {
                        message += catalog.Code + ",";
                    }

                    // Send reply to user
                    try
                    {
                        FoeServerMessage.SendMessage(
                            FoeServerMessage.GetDefaultSmtpServer(),
                            FoeServerRegistry.Get("ProcessorEmail"),
                            req.UserEmail,
                            SubjectGenerator.ReplySubject(RequestType.Catalog, req.RequestId, FoeServerUser.GetUser(req.UserEmail).UserId),
                            message);

                        //FoeDebug.Print("Sent reply to user.");
                    }
                    catch (Exception except)
                    {
                        //FoeDebug.Print("Error sending email.");
                        //FoeDebug.Print(except.ToString());
                        hasError = true;

                        FoeServerLog.Add(_processName, FoeServerLog.LogType.Error, "Error delivering content to " + user.Email + "\r\n" + except.ToString());
                    }
                }

                // If there is no error, then we'll mark the request as 'C' (Completed).
                // Otherwise, we'll leave it as 'P' (Pending).
                if (!hasError)
                {
                    // mark request as "C" (Completed)
                    requestManager.UpdateRequestStatus(req, "C");

                    FoeServerLog.Add(_processName, FoeServerLog.LogType.Message, "Sent " + message + "to " + user.Email + " and added user to AutoSubscription.");

                    //FoeDebug.Print("Marked request as 'C' (Completed).");
                    //FoeDebug.Print("----------------------------------");
                }
                else
                {
                    //FoeDebug.Print("Leave request as 'P' (Pending).");
                    //FoeDebug.Print("-------------------------------");

                    FoeServerLog.Add(_processName, FoeServerLog.LogType.Error,
                                     "Error delivering content but error is likely caused by temporary email downtime. " +
                                     "Leave status as 'P' (Pending) so process can try again later.");
                }
            }

            // Close all requestManager connections
            requestManager.Close();
        }
Example #10
0
        private void DoRegistration()
        {
            SqlConnection conn         = FoeServerDb.OpenDb();
            SqlConnection completeConn = FoeServerDb.OpenDb();

            // Query that gets all pending requests.
            SqlCommand cmd = conn.CreateCommand();

            cmd.CommandText = "select * from Requests where Status='P' and ProcessorEmail=@processorEmail and RequestType=@requestType";
            cmd.Parameters.Add("@processorEmail", System.Data.SqlDbType.NVarChar, 256);
            cmd.Parameters.Add("@requestType", System.Data.SqlDbType.NVarChar, 10);
            cmd.Prepare();

            // Query that marks request as "C" (Completed)
            SqlCommand completeCmd = completeConn.CreateCommand();

            completeCmd.CommandText = "update Requests set DtProcessed=@dtProcessed, Status='C' where id=@id";
            completeCmd.Parameters.Add("@dtProcessed", System.Data.SqlDbType.DateTime);
            completeCmd.Parameters.Add("@id", System.Data.SqlDbType.Int);
            completeCmd.Prepare();

            //FoeDebug.Print("Getting pending requests.");

            // Get all pending requests
            cmd.Parameters["@processorEmail"].Value = FoeServerRegistry.Get("ProcessorEmail");
            cmd.Parameters["@requestType"].Value    = FoeServerRequest.RequestTypeToString(RequestType.Registration);
            SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                int    id        = (int)FoeServerDb.GetInt32(reader, "Id");
                string userEmail = FoeServerDb.GetString(reader, "UserEmail");
                string requestId = FoeServerDb.GetString(reader, "RequestId");

                //FoeDebug.Print("Processing " + userEmail);

                // Create new user account
                FoeUser user = FoeServerUser.RegisterUser(userEmail);

                // Mark request as "C" (Completed)
                completeCmd.Parameters["@dtProcessed"].Value = DateTime.Now;
                completeCmd.Parameters["@id"].Value          = id;
                completeCmd.ExecuteNonQuery();

                // Send response back to user
                SmtpServer server  = FoeServerMessage.GetDefaultSmtpServer();
                string     subject = "Re: Register " + requestId + " by Newbie";

                FoeServerMessage.SendMessage(server, FoeServerRegistry.Get("ProcessorEmail"), user.Email, subject, user.UserId);

                FoeServerLog.Add(_processName, FoeServerLog.LogType.Message, "Completed registration for " + userEmail);

                //FoeDebug.Print("Sent reply to " + userEmail);
                //FoeDebug.Print("");
            }
            reader.Close();

            // Close connections
            conn.Close();
            completeConn.Close();
        }