Beispiel #1
0
		private AppFunc WebSocketHandler(AppFunc next)
		{
			return (env) =>
			{
				var request = new OwinRequest(env);

				if (request.Path == "/Echo" && request.CanAccept)
				{
					request.Accept(async (socket) =>
					{
						const int maxMessageSize = 1024;
						byte[] receiveBuffer = new byte[maxMessageSize];

						Console.WriteLine("WebSocket connection established.");

						while (true)
						{
							ArraySegment<byte> buffer = new ArraySegment<byte>(receiveBuffer);
							var received = await socket.ReceiveAsync(buffer, CancellationToken.None);
							if (received.MessageType == 0x8) // close
							{
								await socket.CloseAsync(CancellationToken.None);
								return;
							}
							else if (received.MessageType == 0x2) // binary
							{
								await socket.CloseAsync((int)WebSocketCloseStatus.InvalidMessageType, "Cannot accept binary frame", CancellationToken.None);
							}
							else
							{
								int count = received.Count;

								while (received.EndOfMessage == false)
								{
									if (count >= maxMessageSize)
									{
										throw new NotSupportedException();
									}

									received = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer, count, maxMessageSize - count), CancellationToken.None);
									count += received.Count;
								}

								var receivedString = Encoding.UTF8.GetString(receiveBuffer, 0, count);
								var echoString = receivedString;
								ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(echoString));
								await socket.SendAsync(outputBuffer, (int)WebSocketMessageType.Text, true, CancellationToken.None);
							}
						}
					});
					return TaskHelpers.Completed();
				}
				else if (request.Path == "/Echo")
				{
					var response = new OwinResponse(env);
					return response.RespondString(HtmlContentEcho, "text/html");
				}
				else if (request.Path == "/")
				{
					var response = new OwinResponse(env);
					return response.RespondString(HtmlContent, "text/html");
				}
				else
				{
					return next(env);
				}
			};
		}
        public Task Invoke(IDictionary<string, object> env)
        {
            var request = new OwinRequest(env);
            var response = new OwinResponse(env);

            var requestPath = Uri.UnescapeDataString(request.Path);

            var backgrounds = DataManager.ActualBackgroundStorage;

            if (requestPath.StartsWith("/backgrounds/"))
            {
                if (request.Method != "GET")
                    return response.RespondMethodNotAllowed();

                var query = requestPath.Substring("/backgrounds".Length);

                if (query.EndsWith("/list"))
                {
                    string path = query.Substring(0, query.Length - "list".Length);
                    var dir = backgrounds.GetDirectory(path);

                    try
                    {
                        StringBuilder sb = new StringBuilder();
                        ListBackgroundEntries(dir, sb);

                        return response.RespondString(sb.ToString());
                    }
                    catch (FileNotFoundException)
                    {
                        return response.RespondNotFound();
                    }
                }
                else if (query == "/listall")
                {
                    StringBuilder sb = new StringBuilder();
                    ListBackgroundEntries(backgrounds.Root, sb, true);
                    return response.RespondString(sb.ToString());
                }
                else
                {
                    bool preview = false;
                    if (query.EndsWith("/preview"))
                    {
                        preview = true;
                        query = query.Substring(0, query.Length - "/preview".Length);
                    }

                    try
                    {
                        var file = backgrounds.GetFile(query);
                        var contentType = file.MimeType;

                        if (!String.IsNullOrEmpty(contentType))
                        {
                            response.SetHeader("Content-Type", contentType);
                        }
                        return response.RespondDownloaded(preview ? file.PreviewUri : file.Uri);
                    }
                    catch (FileNotFoundException)
                    {
                        return response.RespondNotFound();
                    }
                }
            }
            else
            {
                return next(env);
            }
        }
Beispiel #3
0
		public Task Invoke(IDictionary<string, object> env)
		{
			var request = new OwinRequest(env);
			var response = new OwinResponse(env);

			var requestPath = Uri.UnescapeDataString(request.Path);

			var songs = DataManager.ActualSongStorage;

			if (requestPath.StartsWith("/songs/"))
			{
				string query = requestPath.Substring("/songs/".Length);
				if (query == "list")
				{
					if (request.Method != "GET")
						return response.RespondMethodNotAllowed();

					return response.RespondCompressedString(JsonConvert.SerializeObject(songs.All()), "application/json");
				}
				else if (query == "count")
				{
					if (request.Method != "GET")
						return response.RespondMethodNotAllowed();

					return response.RespondString(songs.Count().ToString());
				}
				else if (query.StartsWith("filter/"))
				{
					if (request.Method != "GET")
						return response.RespondMethodNotAllowed();

					query = query.Substring("filter/".Length);
					var i = query.IndexOf('/');
					if (i < 0)
						return response.RespondNotFound();

					var filter = query.Substring(0, i);
					var filterQuery = SongData.NormalizeSearchString(query.Substring(i + 1));

					if (filter == "text")
					{
						return response.RespondCompressedString(JsonConvert.SerializeObject(songs.WhereTextContains(filterQuery)), "application/json");
					}
					else if (filter == "title")
					{
						return response.RespondCompressedString(JsonConvert.SerializeObject(songs.WhereTitleContains(filterQuery)), "application/json");
					}
					else if (filter == "source")
					{
						return response.RespondCompressedString(JsonConvert.SerializeObject(songs.WhereSourceContains(filterQuery)), "application/json");
					}
					else if (filter == "copyright")
					{
						return response.RespondCompressedString(JsonConvert.SerializeObject(songs.WhereCopyrightContains(filterQuery)), "application/json");
					}
					else
					{
						return response.RespondNotFound(); // unsupported filter method
					}
				}
				else
				{
					if (request.Method == "GET")
					{
						return RespondGetSong(response, songs, query);
					}
					else if (request.Method == "PUT")
					{
						return RespondPutSong(request, response, songs, query);
					}
					else if (request.Method == "DELETE")
					{
						try
						{
							songs.Delete(query);
							return TaskHelpers.Completed();
						}
						catch (FileNotFoundException)
						{
							return response.RespondNotFound();
						}
					}
					else
					{
						return response.RespondMethodNotAllowed();
					}
				}
			}
			else
			{
				return next(env);
			}
		}