using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using WebDAVSharp.Server.Adapters;
using WebDAVSharp.Server.Exceptions;
using WebDAVSharp.Server.Stores;
namespace WebDAVSharp.Server.MethodHandlers
{
///
/// This class implements the MOVE HTTP method for WebDAV#.
///
internal class WebDavMoveMethodHandler : WebDavMethodHandlerBase
{
#region Properties
///
/// Gets the collection of the names of the HTTP methods handled by this instance.
///
///
/// The names.
///
public override IEnumerable Names => new[]
{
"MOVE"
};
#endregion
#region Functions
///
/// Processes the request.
///
/// The through which the request came in from the client.
///
/// The
/// object containing both the request and response
/// objects to use.
///
/// The that the is hosting.
public override void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store)
{
MoveItem(server, context, store, context.Request.Url.GetItem(server, store));
}
///
/// Moves the
///
/// The through which the request came in from the client.
///
/// The
/// object containing both the request and response
/// objects to use.
///
/// The that the is hosting.
/// The that will be moved
///
/// If the source path is the same as the
/// destination path
///
/// If one of the preconditions failed
private static void MoveItem(WebDavServer server, IHttpListenerContext context, IWebDavStore store,
IWebDavStoreItem sourceWebDavStoreItem)
{
Uri destinationUri = GetDestinationHeader(context.Request);
IWebDavStoreCollection destinationParentCollection = GetParentCollection(server, store, destinationUri);
bool isNew = true;
string destinationName = Uri.UnescapeDataString(destinationUri.Segments.Last().TrimEnd('/', '\\'));
IWebDavStoreItem destination = destinationParentCollection.GetItemByName(destinationName);
if (destination != null)
{
if (sourceWebDavStoreItem.ItemPath == destination.ItemPath)
throw new WebDavForbiddenException();
// if the overwrite header is F, statuscode = precondition failed
if (!GetOverwriteHeader(context.Request))
throw new WebDavPreconditionFailedException();
// else delete destination and set isNew to false
destinationParentCollection.Delete(destination);
isNew = false;
}
destinationParentCollection.MoveItemHere(sourceWebDavStoreItem, destinationName);
// send correct response
context.SendSimpleResponse(isNew ? (int) HttpStatusCode.Created : (int) HttpStatusCode.NoContent);
}
#endregion
}
}