Exemple #1
0
        public HTTPResponse GetResponse(HTTPRequest request)
        {
            HTTPResponse  response = new HTTPResponse(200);
            StringBuilder sb       = new StringBuilder();
            string        session  = request.GetRequestByKey("session");
            string        action   = request.GetRequestByKey("action");

            if (action != null)
            {
                action = action.ToLower();
            }
            string username  = request.GetRequestByKey("username");
            string password  = request.GetRequestByKey("password");
            string following = request.GetRequestByKey("following");
            string message   = request.GetRequestByKey("message");

            if (session == null) // no session? show login screen
            {
                if (action == null)
                {
                    sb.Append("<h1>Twitter</h1>");
                    sb = GenLoginPage(sb);
                }
                else
                {
                    if (action.Equals("newuser"))
                    {
                        if (username != null && password != null && username != "" && password != "")
                        {
                            try
                            {
                                Twitter.AddUser(username, password);
                                sb.Append("User added successfully, please go back to <a href=\"/twitter\">login page</a> to login");
                            }
                            catch (Exception ex)
                            {
                                sb.Append(String.Format("Error adding user with error [{0}], please go back to <a href=\"/twitter\">login page</a> to try again", ex.Message));
                            }
                        }
                    }
                    else if (action.Equals("login"))
                    {
                        if (username != null && password != null && username != "" && password != "")
                        {
                            if (Twitter.IsValidUser(username, password))
                            {
                                string newSession = Twitter.GenSession(username);
                                if (newSession != null)
                                {
                                    response.Status = 301;
                                    response.AddCustomHeader("Location", "/twitter?session=" + newSession);
                                    return(response);
                                }
                                response.Status = 500;
                                return(response);
                            }
                            else
                            {
                                sb.Append("Error login, please go back to <a href=\"/twitter\">login page</a> to try again");
                            }
                        }
                    }
                }
            }
            else // session is not null
            {
                User user = Twitter.GetUserFromSession(session);
                if (user == null)
                {
                    response.Status = 404;
                    return(response);
                }
                Twitter twitter = new Twitter(user.Name);
                if (action == null) // No action? go to homepage
                {
                    try
                    {
                        sb.Append(String.Format("<h1>{0}'s Twitter</h1>", user.Name));
                        sb = GenTimeline(twitter, sb);
                    }
                    catch (Exception ex)
                    {
                        sb.Append(String.Format("Error [{0}], please go back to <a href=\"/twitter\">login page</a> to try again", ex.Message));
                    }
                }
                else     //action is not null
                {
                    sb.Append(String.Format("<h1>{0}'s Twitter</h1>", user.Name));
                    if (action.Equals("following"))
                    {
                        try
                        {
                            twitter.AddFollowing(following);
                            sb = GenTimeline(twitter, sb);
                        }
                        catch (Exception ex)
                        {
                            sb.Append(String.Format("Error [{0}], please go back to <a href=\"/twitter\">login page</a> to try again", ex.Message));
                        }
                    }
                    else if (action.Equals("tweet"))
                    {
                        try
                        {
                            twitter.PostTweet(message);
                            sb = GenTimeline(twitter, sb);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                            sb.Append(String.Format("Error [{0}], please go back to <a href=\"/twitter\">login page</a> to try again", ex.Message));
                        }
                    }
                }
            }
            response.Body = Encoding.UTF8.GetBytes(sb.ToString());
            return(response);
        }
Exemple #2
0
        public HTTPResponse GetResponse(HTTPRequest request)
        {
            HTTPResponse  response = new HTTPResponse(200);
            StringBuilder sb       = new StringBuilder();
            ErrorCode     error;

            if (!_isInit)
            {
                init();
                _isInit = true;
            }

            if (request.Method == HTTPRequest.METHOD_GET)
            {
                // Input form, this can be place by any HTML page
                sb.Append("<html><body>");
                sb.Append(GenUploadForm());
                sb.Append("</body></html>");
                response.Body = Encoding.UTF8.GetBytes(sb.ToString());
                return(response);
            }
            else if (request.Method == HTTPRequest.METHOD_POST)
            {
                // Get remote image from URL
                string url = Uri.UnescapeDataString(request.GetRequestByKey("imageUploadUrl"));
                byte[] data;
                try {
                    data = DownloadImageFromUrl(url);
                } catch (Exception) {
                    return(new HTTPResponse(400));
                }
                // https://www.codeproject.com/Articles/502829/GPGPU-image-processing-basics-using-OpenCL-NET
                // Convert image to bitmap binary
                Image inputImage = Image.FromStream(new MemoryStream(data));
                if (inputImage == null)
                {
                    return(new HTTPResponse(500));
                }
                int imagewidth  = inputImage.Width;
                int imageHeight = inputImage.Height;

                Bitmap     bmpImage           = new Bitmap(inputImage);
                BitmapData bitmapData         = bmpImage.LockBits(new Rectangle(0, 0, bmpImage.Width, bmpImage.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                int        inputImageByteSize = bitmapData.Stride * bitmapData.Height;
                byte[]     inputByteArray     = new byte[inputImageByteSize];
                Marshal.Copy(bitmapData.Scan0, inputByteArray, 0, inputImageByteSize);

                // Load kernel source code
                string programPath = System.Environment.CurrentDirectory + "/Kernel.cl";
                if (!System.IO.File.Exists(programPath))
                {
                    return(new HTTPResponse(404));
                }

                string programSource = System.IO.File.ReadAllText(programPath);
                using (OpenCL.Net.Program program = Cl.CreateProgramWithSource(_context, 1, new[] { programSource }, null, out error)) {
                    // Create kernel
                    LogError(error, "Cl.CreateProgramWithSource");
                    error = Cl.BuildProgram(program, 1, new[] { _device }, string.Empty, null, IntPtr.Zero);
                    LogError(error, "Cl.BuildProgram");
                    if (Cl.GetProgramBuildInfo(program, _device, ProgramBuildInfo.Status, out error).CastTo <OpenCL.Net.BuildStatus>()
                        != BuildStatus.Success)
                    {
                        LogError(error, "Cl.GetProgramBuildInfo");
                        return(new HTTPResponse(404));
                    }
                    Kernel kernel = Cl.CreateKernel(program, _parameters["KernelFunction"], out error);
                    LogError(error, "Cl.CreateKernel");

                    // Create image memory objects
                    OpenCL.Net.ImageFormat clImageFormat = new OpenCL.Net.ImageFormat(ChannelOrder.RGBA, ChannelType.Unsigned_Int8);
                    IMem inputImage2DBuffer = Cl.CreateImage2D(_context, MemFlags.CopyHostPtr | MemFlags.ReadOnly,
                                                               clImageFormat, (IntPtr)bitmapData.Width, (IntPtr)bitmapData.Height,
                                                               (IntPtr)0, inputByteArray, out error);
                    LogError(error, "CreateImage2D input");
                    byte[] outputByteArray     = new byte[inputImageByteSize];
                    IMem   outputImage2DBuffer = Cl.CreateImage2D(_context, MemFlags.CopyHostPtr | MemFlags.WriteOnly,
                                                                  clImageFormat, (IntPtr)bitmapData.Width, (IntPtr)bitmapData.Height,
                                                                  (IntPtr)0, outputByteArray, out error);
                    LogError(error, "CreateImage2D output");

                    // Set arguments
                    int IntPtrSize = Marshal.SizeOf(typeof(IntPtr));
                    error  = Cl.SetKernelArg(kernel, 0, (IntPtr)IntPtrSize, inputImage2DBuffer);
                    error |= Cl.SetKernelArg(kernel, 1, (IntPtr)IntPtrSize, outputImage2DBuffer);
                    LogError(error, "Cl.SetKernelArg");

                    // Create command queue
                    CommandQueue cmdQueue = Cl.CreateCommandQueue(_context, _device, (CommandQueueProperties)0, out error);
                    LogError(error, "Cl.CreateCommandQueue");
                    Event clevent;

                    // Copy input image from the host to the GPU
                    IntPtr[] originPtr        = new IntPtr[] { (IntPtr)0, (IntPtr)0, (IntPtr)0 };
                    IntPtr[] regionPtr        = new IntPtr[] { (IntPtr)imagewidth, (IntPtr)imageHeight, (IntPtr)1 };
                    IntPtr[] workGroupSizePtr = new IntPtr[] { (IntPtr)imagewidth, (IntPtr)imageHeight, (IntPtr)1 };
                    error = Cl.EnqueueWriteImage(cmdQueue, inputImage2DBuffer, Bool.True, originPtr, regionPtr, (IntPtr)0,
                                                 (IntPtr)0, inputByteArray, 0, null, out clevent);
                    LogError(error, "Cl.EnqueueWriteImage");

                    // Run the kernel
                    error = Cl.EnqueueNDRangeKernel(cmdQueue, kernel, 2, null, workGroupSizePtr, null, 0, null, out clevent);
                    LogError(error, "Cl.EnqueueNDRangeKernel");

                    // Wait for finish event
                    error = Cl.Finish(cmdQueue);
                    LogError(error, "Cl.Finish");

                    // Read the output image back from GPU
                    error = Cl.EnqueueReadImage(cmdQueue, outputImage2DBuffer, Bool.True, originPtr, regionPtr, (IntPtr)0,
                                                (IntPtr)0, outputByteArray, 0, null, out clevent);
                    LogError(error, "Cl.EnqueueReadImage");
                    error = Cl.Finish(cmdQueue);
                    LogError(error, "Cl.Finih");

                    // Release memory
                    Cl.ReleaseKernel(kernel);
                    Cl.ReleaseCommandQueue(cmdQueue);
                    Cl.ReleaseMemObject(inputImage2DBuffer);
                    Cl.ReleaseMemObject(outputImage2DBuffer);

                    // Convert binary bitmap to JPEG image and return as response
                    GCHandle     pinnedOutputArray = GCHandle.Alloc(outputByteArray, GCHandleType.Pinned);
                    IntPtr       outputBmpPointer  = pinnedOutputArray.AddrOfPinnedObject();
                    Bitmap       outputBitmap      = new Bitmap(imagewidth, imageHeight, bitmapData.Stride, PixelFormat.Format32bppArgb, outputBmpPointer);
                    MemoryStream msOutput          = new MemoryStream();
                    outputBitmap.Save(msOutput, System.Drawing.Imaging.ImageFormat.Jpeg);
                    response.Body = msOutput.ToArray();
                    response.Type = "image/jpeg";
                    return(response);
                }
            }
            return(new HTTPResponse(501));
        }
Exemple #3
0
        public new HTTPResponse GetResponse(HTTPRequest request)
        {
            HTTPResponse  response = new HTTPResponse(200);
            StringBuilder sb       = new StringBuilder();

            session = request.GetPropertyByKey("X-session");
            string[] urlToken = request.Url.Split("/");
            if (urlToken.Length > 2)
            {
                action = urlToken[2];
            }
            else
            {
                action = null;
            }
            requestMethod = request.Method;
            string username = request.GetRequestByKey("username");
            string password = request.GetRequestByKey("password");

            if (IsMethod(HTTP_OPTIONS))
            {
                return(response);
            }

            if (IsAction(USER_ACTION))
            {
                if (IsMethod(HTTP_POST))
                {
                    if (!IsNOE(username) && !IsNOE(password))
                    {
                        try
                        {
                            Twitter.AddUser(username, password);
                            response.Status = 201;
                        }
                        catch (Exception ex)
                        {
                            response.SetBody(ex.Message);
                            response.Status = 500;
                        }
                    }
                    else
                    {
                        response.SetBody("Username and password required");
                        response.Status = 400;
                        return(response);
                    }
                }
            }
            else if (IsAction(LOGIN_ACTION))
            {
                if (IsMethod(HTTP_POST))
                {
                    if (!IsNOE(username) && !IsNOE(password))
                    {
                        if (Twitter.IsValidUser(username, password))
                        {
                            string newSession = Twitter.GenSession(username);
                            if (!IsNOE(newSession))
                            {
                                response.Status = 201;
                                dynamic jobj = new JObject();
                                jobj.Session  = newSession;
                                response.Type = "application/json";
                                string resp = JsonConvert.SerializeObject(jobj);
                                response.Body = Encoding.UTF8.GetBytes(resp);
                                return(response);
                            }
                            response.SetBody("Can't create session");
                            response.Status = 500;
                            return(response);
                        }
                        else
                        {
                            response.SetBody("Invalid username/password");
                            response.Status = 404;
                            return(response);
                        }
                    }
                    else
                    {
                        response.SetBody("Username and password required");
                        response.Status = 400;
                        return(response);
                    }
                }
            }
            else if (!IsNOE(session))
            {
                User user = Twitter.GetUserFromSession(session);
                if (user == null)
                {
                    response.SetBody("User not found, please login again");
                    response.Status = 404;
                    return(response);
                }
                Twitter twitter = new Twitter(user.Name);
                if (IsNOE(action))
                {
                    if (IsMethod(HTTP_GET))
                    {
                        try
                        {
                            response      = new HTTPResponse(200);
                            response.Type = "application/json";
                            string resp = JsonConvert.SerializeObject(twitter.GetFollowingTimeline());
                            if (IsNOE(resp))
                            {
                                response.SetBody("No post in timline");
                                response.Status = 404;
                                return(response);
                            }
                            response.Body = Encoding.UTF8.GetBytes(resp);
                            return(response);
                        }
                        catch (Exception ex)
                        {
                            response.SetBody(ex.Message);
                            response.Status = 500;
                            return(response);
                        }
                    }
                }
                else if (IsAction(LOGOUT_ACTION))
                {
                    if (IsMethod(HTTP_POST))
                    {
                        try {
                            Twitter.RemoveSession(user.Name);
                            response.Status = 200;
                            return(response);
                        }
                        catch (Exception ex)
                        {
                            response.SetBody(ex.Message);
                            response.Status = 500;
                            return(response);
                        }
                    }
                }
                else if (IsAction(TWEET_ACTION))
                {
                    if (IsMethod(HTTP_GET))
                    {
                        try
                        {
                            response      = new HTTPResponse(200);
                            response.Type = "application/json";
                            string resp = null;
                            if (IsNOE(urlToken[3]))
                            {
                                resp = JsonConvert.SerializeObject(twitter.GetTimeline(user));
                            }
                            else
                            {
                                User aUser = Twitter.GetUserFromName(urlToken[3]);
                                if (aUser == null)
                                {
                                    response.SetBody("User not found");
                                    response.Status = 404;
                                    return(response);
                                }
                                resp = JsonConvert.SerializeObject(twitter.GetTimeline(aUser));
                            }
                            if (IsNOE(resp))
                            {
                                response.SetBody("No post in timline");
                                response.Status = 404;
                                return(response);
                            }
                            response.Body = Encoding.UTF8.GetBytes(resp);
                            return(response);
                        }
                        catch (Exception ex)
                        {
                            response.SetBody(ex.Message);
                            response.Status = 500;
                            return(response);
                        }
                    }
                    else if (IsMethod(HTTP_POST))
                    {
                        try
                        {
                            string message = request.GetRequestByKey("message");
                            if (IsNOE(message))
                            {
                                response.SetBody("Message required");
                                response.Status = 400;
                                return(response);
                            }
                            Tweet tweet = new Tweet();
                            tweet.User        = user.Name;
                            tweet.Message     = message;
                            tweet.DateCreated = DateTime.Now;
                            using (var context = new TweetContext())
                            {
                                context.Tweets.Add(tweet);
                                context.SaveChanges();
                            }
                            response.Status = 201;
                            return(response);
                        }
                        catch (Exception ex)
                        {
                            response.SetBody(ex.Message);
                            response.Status = 500;
                            return(response);
                        }
                    }
                    else if (IsMethod(HTTP_DELETE))
                    {
                        try {
                            throw (new NotImplementedException());
                        } catch (Exception ex) {
                            response.SetBody(ex.Message);
                            response.Status = 501;
                            return(response);
                        }
                    }
                }
                //action following
                else if (IsAction(FOLLOWING_ACTION))
                {
                    if (IsMethod(HTTP_GET))
                    {
                        response      = new HTTPResponse(200);
                        response.Type = "application/json";
                        string resp = JsonConvert.SerializeObject(user.Following);
                        if (resp == null)
                        {
                            response.SetBody("No following");
                            response.Status = 404;
                            return(response);
                        }
                        response.Body = Encoding.UTF8.GetBytes(resp);
                        return(response);
                    }
                    //add new following
                    else if (IsMethod(HTTP_POST))
                    {
                        string following = request.GetRequestByKey("followingname");
                        try
                        {
                            twitter.AddFollowing(following);
                            response      = new HTTPResponse(201);
                            response.Type = "application/json";
                            string resp = JsonConvert.SerializeObject(user.Following);
                            if (resp == null)
                            {
                                response.SetBody("No folowing");
                                response.Status = 404;
                                return(response);
                            }
                            response.Body = Encoding.UTF8.GetBytes(resp);
                            return(response);
                        }
                        catch (Exception ex)
                        {
                            response.Status = 400;
                            response.SetBody(ex.Message);
                            return(response);
                        }
                    }
                    else if (IsMethod(HTTP_DELETE))
                    {
                        string following = request.GetRequestByKey("followingname");
                        try
                        {
                            twitter.RemoveFollowing(following);
                            response      = new HTTPResponse(200);
                            response.Type = "application/json";
                            string resp = JsonConvert.SerializeObject(user.Following);
                            if (resp == null)
                            {
                                response.SetBody("No following");
                                response.Status = 404;
                                return(response);
                            }
                            response.Body = Encoding.UTF8.GetBytes(resp);
                            return(response);
                        }
                        catch (Exception ex)
                        {
                            response.Status = 400;
                            response.SetBody(ex.Message);
                            return(response);
                        }
                    }
                }
                //add follow
                else if (IsAction(FOLLOW_ACTION))
                {
                    if (IsMethod(HTTP_POST))
                    {
                        string following = request.GetRequestByKey("followingname");
                        try
                        {
                            twitter.AddFollowing(following);
                            response      = new HTTPResponse(201);
                            response.Type = "application/json";
                            string resp = JsonConvert.SerializeObject(user.Following);
                            if (resp == null)
                            {
                                response.SetBody("No folowing");
                                response.Status = 404;
                                return(response);
                            }
                            response.Body = Encoding.UTF8.GetBytes(resp);
                            return(response);
                        }
                        catch (Exception ex)
                        {
                            response.Status = 400;
                            response.SetBody(ex.Message);
                            return(response);
                        }
                    }
                }
                //unfollow
                else if (IsAction(UNFOLLOW_ACTION))
                {
                    if (IsMethod(HTTP_DELETE))
                    {
                        try
                        {
                            twitter.RemoveFollowing(following);
                            response      = new HTTPResponse(200);
                            response.Type = "application/json";
                            string resp = JsonConvert.SerializeObject(user.Following);
                            if (resp == null)
                            {
                                response.SetBody("No following");
                                response.Status = 404;
                                return(response);
                            }
                            response.Body = Encoding.UTF8.GetBytes(resp);
                            return(response);
                        }

                        catch (Exception ex)
                        {
                            response.Status = 400;
                            response.SetBody(ex.Message);
                            return(response);
                        }
                    }
                }
            }
            response.Status = 400;
            return(response);
        }