Ejemplo n.º 1
0
        public static void GET(string Url, Action <UploadTask> UploadingAction)
        {
            string url = Url + "?{?}";

            Handle.GET(url, (string parameters, Request request) => {
                string sessionId;
                string fileName;
                long fileSize;
                string error;

                if (!ResolveUploadParameters(parameters, out sessionId, out fileName, out fileSize, out error))
                {
                    return(new Response()
                    {
                        StatusCode = (ushort)System.Net.HttpStatusCode.BadRequest,
                        Body = error
                    });
                }

                if (!request.WebSocketUpgrade)
                {
                    return(404);
                }

                WebSocket ws    = request.SendUpgrade(WebSocketGroupName);
                UploadTask task = new UploadTask(sessionId, fileName, fileSize, parameters);

                task.StateChange += (s, a) => {
                    UploadingAction(s as UploadTask);
                };

                if (!Uploads.TryAdd(ws.ToUInt64(), task))
                {
                    return(new Response()
                    {
                        StatusCode = (ushort)System.Net.HttpStatusCode.BadRequest,
                        Body = "Unable to create upload task"
                    });
                }

                return(HandlerStatus.Handled);
            }, new HandlerOptions()
            {
                SkipRequestFilters = true
            });

            Handle.WebSocket(WebSocketGroupName, (byte[] data, WebSocket ws) => {
                if (!Uploads.ContainsKey(ws.ToUInt64()))
                {
                    ws.Disconnect("Could not find correct socket to handle the incoming data.", WebSocket.WebSocketCloseCodes.WS_CLOSE_CANT_ACCEPT_DATA);
                    return;
                }

                UploadTask task = Uploads[ws.ToUInt64()];

                task.Write(data);

                if (task.FileSize > 0)
                {
                    ws.Send(task.Progress.ToString());
                }
            });

            Handle.WebSocketDisconnect(WebSocketGroupName, (ws) => {
                UploadTask task;

                if (Uploads.TryRemove(ws.ToUInt64(), out task))
                {
                    task.Close();
                }
            });
        }