WebDav explorer [Beta]

This commit is contained in:
vfedosevich 2014-12-30 01:49:58 -08:00
parent 6c6b4b29a5
commit 3396e34c8e
27 changed files with 2119 additions and 1713 deletions

View file

@ -6072,6 +6072,44 @@ RETURN
GO
IF OBJECTPROPERTY(object_id('dbo.GetExchangeAccountByAccountNameWithoutItemId'), N'IsProcedure') = 1
DROP PROCEDURE [dbo].[GetExchangeAccountByAccountNameWithoutItemId]
GO
CREATE PROCEDURE [dbo].[GetExchangeAccountByAccountNameWithoutItemId]
(
@PrimaryEmailAddress nvarchar(300)
)
AS
SELECT
E.AccountID,
E.ItemID,
E.AccountType,
E.AccountName,
E.DisplayName,
E.PrimaryEmailAddress,
E.MailEnabledPublicFolder,
E.MailboxManagerActions,
E.SamAccountName,
E.AccountPassword,
E.MailboxPlanId,
P.MailboxPlan,
E.SubscriberNumber,
E.UserPrincipalName,
E.ArchivingMailboxPlanId,
AP.MailboxPlan as 'ArchivingMailboxPlan',
E.EnableArchiving
FROM
ExchangeAccounts AS E
LEFT OUTER JOIN ExchangeMailboxPlans AS P ON E.MailboxPlanId = P.MailboxPlanId
LEFT OUTER JOIN ExchangeMailboxPlans AS AP ON E.ArchivingMailboxPlanId = AP.MailboxPlanId
WHERE
E.PrimaryEmailAddress = @PrimaryEmailAddress
RETURN
GO
-- wsp-10269: Changed php extension path in default properties for IIS70 and IIS80 provider
update ServiceDefaultProperties
set PhpPath='%PROGRAMFILES(x86)%\PHP\php-cgi.exe'

View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<solution>
<add key="disableSourceControlIntegration" value="true" />
</solution>
</configuration>

Binary file not shown.

View file

@ -0,0 +1,144 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">$(MSBuildProjectDirectory)\..\</SolutionDir>
<!-- Enable the restore command to run before builds -->
<RestorePackages Condition=" '$(RestorePackages)' == '' ">false</RestorePackages>
<!-- Property that enables building a package from a project -->
<BuildPackage Condition=" '$(BuildPackage)' == '' ">false</BuildPackage>
<!-- Determines if package restore consent is required to restore packages -->
<RequireRestoreConsent Condition=" '$(RequireRestoreConsent)' != 'false' ">true</RequireRestoreConsent>
<!-- Download NuGet.exe if it does not already exist -->
<DownloadNuGetExe Condition=" '$(DownloadNuGetExe)' == '' ">false</DownloadNuGetExe>
</PropertyGroup>
<ItemGroup Condition=" '$(PackageSources)' == '' ">
<!-- Package sources used to restore packages. By default, registered sources under %APPDATA%\NuGet\NuGet.Config will be used -->
<!-- The official NuGet package source (https://www.nuget.org/api/v2/) will be excluded if package sources are specified and it does not appear in the list -->
<!--
<PackageSource Include="https://www.nuget.org/api/v2/" />
<PackageSource Include="https://my-nuget-source/nuget/" />
-->
</ItemGroup>
<PropertyGroup Condition=" '$(OS)' == 'Windows_NT'">
<!-- Windows specific commands -->
<NuGetToolsPath>$([System.IO.Path]::Combine($(SolutionDir), ".nuget"))</NuGetToolsPath>
</PropertyGroup>
<PropertyGroup Condition=" '$(OS)' != 'Windows_NT'">
<!-- We need to launch nuget.exe with the mono command if we're not on windows -->
<NuGetToolsPath>$(SolutionDir).nuget</NuGetToolsPath>
</PropertyGroup>
<PropertyGroup>
<PackagesProjectConfig Condition=" '$(OS)' == 'Windows_NT'">$(MSBuildProjectDirectory)\packages.$(MSBuildProjectName.Replace(' ', '_')).config</PackagesProjectConfig>
<PackagesProjectConfig Condition=" '$(OS)' != 'Windows_NT'">$(MSBuildProjectDirectory)\packages.$(MSBuildProjectName).config</PackagesProjectConfig>
</PropertyGroup>
<PropertyGroup>
<PackagesConfig Condition="Exists('$(MSBuildProjectDirectory)\packages.config')">$(MSBuildProjectDirectory)\packages.config</PackagesConfig>
<PackagesConfig Condition="Exists('$(PackagesProjectConfig)')">$(PackagesProjectConfig)</PackagesConfig>
</PropertyGroup>
<PropertyGroup>
<!-- NuGet command -->
<NuGetExePath Condition=" '$(NuGetExePath)' == '' ">$(NuGetToolsPath)\NuGet.exe</NuGetExePath>
<PackageSources Condition=" $(PackageSources) == '' ">@(PackageSource)</PackageSources>
<NuGetCommand Condition=" '$(OS)' == 'Windows_NT'">"$(NuGetExePath)"</NuGetCommand>
<NuGetCommand Condition=" '$(OS)' != 'Windows_NT' ">mono --runtime=v4.0.30319 "$(NuGetExePath)"</NuGetCommand>
<PackageOutputDir Condition="$(PackageOutputDir) == ''">$(TargetDir.Trim('\\'))</PackageOutputDir>
<RequireConsentSwitch Condition=" $(RequireRestoreConsent) == 'true' ">-RequireConsent</RequireConsentSwitch>
<NonInteractiveSwitch Condition=" '$(VisualStudioVersion)' != '' AND '$(OS)' == 'Windows_NT' ">-NonInteractive</NonInteractiveSwitch>
<PaddedSolutionDir Condition=" '$(OS)' == 'Windows_NT'">"$(SolutionDir) "</PaddedSolutionDir>
<PaddedSolutionDir Condition=" '$(OS)' != 'Windows_NT' ">"$(SolutionDir)"</PaddedSolutionDir>
<!-- Commands -->
<RestoreCommand>$(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir $(PaddedSolutionDir)</RestoreCommand>
<BuildCommand>$(NuGetCommand) pack "$(ProjectPath)" -Properties "Configuration=$(Configuration);Platform=$(Platform)" $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols</BuildCommand>
<!-- We need to ensure packages are restored prior to assembly resolve -->
<BuildDependsOn Condition="$(RestorePackages) == 'true'">
RestorePackages;
$(BuildDependsOn);
</BuildDependsOn>
<!-- Make the build depend on restore packages -->
<BuildDependsOn Condition="$(BuildPackage) == 'true'">
$(BuildDependsOn);
BuildPackage;
</BuildDependsOn>
</PropertyGroup>
<Target Name="CheckPrerequisites">
<!-- Raise an error if we're unable to locate nuget.exe -->
<Error Condition="'$(DownloadNuGetExe)' != 'true' AND !Exists('$(NuGetExePath)')" Text="Unable to locate '$(NuGetExePath)'" />
<!--
Take advantage of MsBuild's build dependency tracking to make sure that we only ever download nuget.exe once.
This effectively acts as a lock that makes sure that the download operation will only happen once and all
parallel builds will have to wait for it to complete.
-->
<MsBuild Targets="_DownloadNuGet" Projects="$(MSBuildThisFileFullPath)" Properties="Configuration=NOT_IMPORTANT;DownloadNuGetExe=$(DownloadNuGetExe)" />
</Target>
<Target Name="_DownloadNuGet">
<DownloadNuGet OutputFilename="$(NuGetExePath)" Condition=" '$(DownloadNuGetExe)' == 'true' AND !Exists('$(NuGetExePath)')" />
</Target>
<Target Name="RestorePackages" DependsOnTargets="CheckPrerequisites">
<Exec Command="$(RestoreCommand)"
Condition="'$(OS)' != 'Windows_NT' And Exists('$(PackagesConfig)')" />
<Exec Command="$(RestoreCommand)"
LogStandardErrorAsError="true"
Condition="'$(OS)' == 'Windows_NT' And Exists('$(PackagesConfig)')" />
</Target>
<Target Name="BuildPackage" DependsOnTargets="CheckPrerequisites">
<Exec Command="$(BuildCommand)"
Condition=" '$(OS)' != 'Windows_NT' " />
<Exec Command="$(BuildCommand)"
LogStandardErrorAsError="true"
Condition=" '$(OS)' == 'Windows_NT' " />
</Target>
<UsingTask TaskName="DownloadNuGet" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup>
<OutputFilename ParameterType="System.String" Required="true" />
</ParameterGroup>
<Task>
<Reference Include="System.Core" />
<Using Namespace="System" />
<Using Namespace="System.IO" />
<Using Namespace="System.Net" />
<Using Namespace="Microsoft.Build.Framework" />
<Using Namespace="Microsoft.Build.Utilities" />
<Code Type="Fragment" Language="cs">
<![CDATA[
try {
OutputFilename = Path.GetFullPath(OutputFilename);
Log.LogMessage("Downloading latest version of NuGet.exe...");
WebClient webClient = new WebClient();
webClient.DownloadFile("https://www.nuget.org/nuget.exe", OutputFilename);
return true;
}
catch (Exception ex) {
Log.LogErrorFromException(ex);
return false;
}
]]>
</Code>
</Task>
</UsingTask>
</Project>

View file

@ -2682,6 +2682,17 @@ namespace WebsitePanel.EnterpriseServer
);
}
public static IDataReader GetExchangeAccountByAccountNameWithoutItemId(string primaryEmailAddress)
{
return SqlHelper.ExecuteReader(
ConnectionString,
CommandType.StoredProcedure,
"GetExchangeAccountByAccountNameWithoutItemId",
new SqlParameter("@PrimaryEmailAddress", primaryEmailAddress)
);
}
public static IDataReader GetExchangeMailboxes(int itemId)
{
return SqlHelper.ExecuteReader(

View file

@ -1207,6 +1207,20 @@ namespace WebsitePanel.EnterpriseServer
return account;
}
public static ExchangeAccount GetAccountByAccountName(string primaryEmailAddress)
{
ExchangeAccount account = ObjectUtils.FillObjectFromDataReader<ExchangeAccount>(
DataProvider.GetExchangeAccountByAccountNameWithoutItemId(primaryEmailAddress));
if (account == null)
return null;
// decrypt password
account.AccountPassword = CryptoUtils.Decrypt(account.AccountPassword);
return account;
}
public static bool CheckAccountCredentials(int itemId, string email, string password)
{
// place log record

View file

@ -205,6 +205,12 @@ namespace WebsitePanel.EnterpriseServer
return ExchangeServerController.GetAccount(itemId, accountId);
}
[WebMethod]
public ExchangeAccount GetAccountByAccountNameWithoutItemId(string accountName)
{
return ExchangeServerController.GetAccountByAccountName(accountName);
}
[WebMethod]
public ExchangeAccount SearchAccount(ExchangeAccountType accountType, string primaryEmailAddress)
{

View file

@ -2,6 +2,7 @@ using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
@ -159,6 +160,8 @@ namespace WebsitePanel.WebDav.Core
request.Method = "PROPFIND";
request.ContentType = "application/xml";
request.Headers["Depth"] = "1";
//TODO Disable SSL
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
var credentials = (NetworkCredential) _credentials;
if (credentials != null && credentials.UserName != null)

View file

@ -73,11 +73,13 @@ namespace WebsitePanel.WebDav.Core
public Uri Href
{
get { return _href; }
set { SetHref(value.ToString(), new Uri(value.Scheme + "://" + value.Host + value.Segments[0] + value.Segments[1])); }
}
public ItemType ItemType
{
get { return _itemType; }
set { SetItemType(value); }
}
public DateTime LastModified

View file

@ -2,6 +2,7 @@
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
@ -122,6 +123,8 @@ namespace WebsitePanel.WebDav.Core
var webClient = new WebClient();
webClient.Credentials = credentials;
webClient.Headers.Add("Authorization", auth);
//TODO Disable SSL
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate{ return true; });
return webClient.OpenRead(_href);
}

View file

@ -11,7 +11,7 @@ namespace WebsitePanel.WebDav.Core
{
public class WebDavSession
{
public ICredentials Credentials { get; set; }
public NetworkCredential Credentials { get; set; }
/// <summary>
/// Returns IFolder corresponding to path.

View file

@ -10,15 +10,16 @@ namespace WebsitePanel.WebDavPortal
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "FilePathRoute",
url: "root/{*pathPart}",
defaults: new { controller = "FileSystem", action = "ShowContent", pathPart = UrlParameter.Optional }
name: "Office365DocumentRoute",
url: "office365/{org}/{*pathPart}",
defaults: new { controller = "FileSystem", action = "ShowOfficeDocument", pathPart = UrlParameter.Optional }
);
routes.MapRoute(
name: "Office365DocumentRoute",
url: "office365/root/{*pathPart}",
defaults: new { controller = "FileSystem", action = "ShowOfficeDocument", pathPart = UrlParameter.Optional }
name: "FilePathRoute",
url: "{org}/{*pathPart}",
defaults: new { controller = "FileSystem", action = "ShowContent", pathPart = UrlParameter.Optional },
constraints: new { org = new WebsitePanel.WebDavPortal.Constraints.OrganizationRouteConstraint() }
);
routes.MapRoute(

View file

@ -0,0 +1,44 @@
using Ninject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using WebsitePanel.WebDavPortal.Config;
using WebsitePanel.WebDavPortal.DependencyInjection;
using WebsitePanel.WebDavPortal.Models;
namespace WebsitePanel.WebDavPortal.Constraints
{
public class OrganizationRouteConstraint : IRouteConstraint
{
private static string actualOrgName;
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
object value;
if (!values.TryGetValue(parameterName, out value))
return false;
var str = value as string;
if (str == null)
return false;
if (routeDirection == RouteDirection.IncomingRequest)
return actualOrgName == str;
if (httpContext.Session == null)
return false;
IKernel kernel = new StandardKernel(new WebDavExplorerAppModule());
var webDavManager = kernel.Get<IWebDavManager>();
if (webDavManager != null && str == webDavManager.OrganizationName)
{
actualOrgName = str;
return true;
}
return false;
}
}
}

View file

@ -1,7 +1,6 @@
using System;
using System.Configuration;
using System.DirectoryServices;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
@ -20,6 +19,9 @@ using WebsitePanel.WebDavPortal.Cryptography;
using WebsitePanel.WebDavPortal.DependencyInjection;
using WebsitePanel.WebDavPortal.Exceptions;
using WebsitePanel.WebDavPortal.Models;
using System.Collections.Generic;
using WebsitePanel.Providers.OS;
using WebDAV;
namespace WebsitePanel.WebDavPortal.Controllers
{
@ -30,27 +32,6 @@ namespace WebsitePanel.WebDavPortal.Controllers
[HttpGet]
public ActionResult Login()
{
try
{
const string userName = "serveradmin";
string correctPassword = "wsp_2012" + Environment.NewLine;
const bool createPersistentCookie = true;
var authTicket = new FormsAuthenticationTicket(2, userName, DateTime.Now, DateTime.Now.AddMinutes(60), true, correctPassword);
var encryptedTicket = FormsAuthentication.Encrypt(authTicket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
if (createPersistentCookie)
authCookie.Expires = authTicket.Expiration;
Response.Cookies.Add(authCookie);
const string organizationId = "System";
var itemId = ES.Services.Organizations.GetOrganizationById(organizationId).Id;
var folders = ES.Services.EnterpriseStorage.GetEnterpriseFolders(itemId);
}
catch (System.Exception exception)
{
}
//============
object isAuthentication = _kernel.Get<AccountModel>();
if (isAuthentication != null)
return RedirectToAction("ShowContent", "FileSystem");
@ -60,35 +41,35 @@ namespace WebsitePanel.WebDavPortal.Controllers
[HttpPost]
public ActionResult Login(AccountModel model)
{
var ldapConnectionString = WebDavAppConfigManager.Instance.ConnectionStrings.LdapServer;
if (ldapConnectionString == null || !Regex.IsMatch(ldapConnectionString, @"^LDAP://([\w-]+.)+[\w-]+(/[\w- ./?%&=])?$"))
return View(new AccountModel { LdapError = "LDAP server address is invalid" });
//var ldapConnectionString = WebDavAppConfigManager.Instance.ConnectionStrings.LdapServer;
//if (ldapConnectionString == null || !Regex.IsMatch(ldapConnectionString, @"^LDAP://([\w-]+.)+[\w-]+(/[\w- ./?%&=])?$"))
// return View(new AccountModel { LdapError = "LDAP server address is invalid" });
var principal = new WebDavPortalIdentity(model.Login, model.Password);
bool isAuthenticated = principal.Identity.IsAuthenticated;
var organizationId = principal.GetOrganizationId();
//var principal = new WebDavPortalIdentity(model.Login, model.Password);
//bool isAuthenticated = principal.Identity.IsAuthenticated;
//var organizationId = principal.GetOrganizationId();
AutheticationToServicesUsingWebsitePanelUser();
var exchangeAccount = ES.Services.ExchangeServer.GetAccountByAccountNameWithoutItemId(model.Login);
var isAuthenticated = exchangeAccount != null && exchangeAccount.AccountPassword == model.Password;
ViewBag.LdapIsAuthentication = isAuthenticated;
if (isAuthenticated)
{
AutheticationToServicesUsingWebsitePanelUser();
var organization = ES.Services.Organizations.GetOrganizationById(organizationId);
if (organization == null)
throw new NullReferenceException();
Session[WebDavAppConfigManager.Instance.SessionKeys.ItemId] = organization.Id;
Session[WebDavAppConfigManager.Instance.SessionKeys.ItemId] = exchangeAccount.ItemId;
try
{
Session[WebDavAppConfigManager.Instance.SessionKeys.WebDavManager] = new WebDavManager(new NetworkCredential(WebDavAppConfigManager.Instance.UserDomain + "\\" + model.Login, model.Password));
Session[WebDavAppConfigManager.Instance.SessionKeys.AccountInfo] = model;
Session[WebDavAppConfigManager.Instance.SessionKeys.WebDavManager] = new WebDavManager(new NetworkCredential(model.Login, model.Password, WebDavAppConfigManager.Instance.UserDomain), exchangeAccount.ItemId);
//Session[WebDavAppConfigManager.Instance.SessionKeys.WebDavManager] = new WebDavManager(new NetworkCredential("Administrator", "WSP99cc$$1", WebDavAppConfigManager.Instance.UserDomain), exchangeAccount.ItemId);
}
catch (ConnectToWebDavServerException exception)
{
return View(new AccountModel { LdapError = exception.Message });
}
return RedirectToAction("ShowContent", "FileSystem");
return RedirectToAction("ShowContent", "FileSystem", new { org = _kernel.Get<IWebDavManager>().OrganizationName });
}
return View(new AccountModel { LdapError = "The user name or password is incorrect" });
}

View file

@ -12,17 +12,29 @@ using WebsitePanel.WebDavPortal.CustomAttributes;
using WebsitePanel.WebDavPortal.DependencyInjection;
using WebsitePanel.WebDavPortal.Extensions;
using WebsitePanel.WebDavPortal.Models;
using WebsitePanel.Portal;
using WebsitePanel.Providers.OS;
using System.Net;
namespace WebsitePanel.WebDavPortal.Controllers
{
[LdapAuthorization]
public class FileSystemController : Controller
{
private readonly IKernel _kernel = new StandardKernel(new WebDavExplorerAppModule());
public ActionResult ShowContent(string pathPart = "")
[HttpGet]
public ActionResult ShowContent(string org, string pathPart = "")
{
var webDavManager = _kernel.Get<IWebDavManager>();
var webDavManager = new StandardKernel(new WebDavExplorerAppModule()).Get<IWebDavManager>();
if (org != webDavManager.OrganizationName)
return new HttpStatusCodeResult(HttpStatusCode.NoContent);
var test = Url.Action("ShowContent", "FileSystem");
var tetet = Url.Action("ShowContent", "FileSystem", new { org = "pgrorg" });
string fileName = pathPart.Split('/').Last();
if (webDavManager.IsFile(fileName))
@ -40,15 +52,16 @@ namespace WebsitePanel.WebDavPortal.Controllers
return View(model);
}
catch (UnauthorizedException)
catch (UnauthorizedException exc)
{
throw new HttpException(404, "Not Found");
}
}
public ActionResult ShowOfficeDocument(string pathPart = "")
public ActionResult ShowOfficeDocument(string org, string pathPart = "")
{
const string fileUrl = "http://my-files.ru/DownloadSave/xluyk3/test1.docx";
var webDavManager = _kernel.Get<IWebDavManager>();
string fileUrl = webDavManager.RootPath.TrimEnd('/') + "/" + pathPart.TrimStart('/');
var uri = new Uri(WebDavAppConfigManager.Instance.OfficeOnline.Url).AddParameter("src", fileUrl).ToString();
return View(new OfficeOnlineModel(uri, new Uri(fileUrl).Segments.Last()));

View file

@ -0,0 +1,26 @@
using Ninject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Web.Hosting;
using WebsitePanel.WebDavPortal.DependencyInjection;
using WebsitePanel.WebDavPortal.Models;
namespace WebsitePanel.WebDavPortal.HttpHandlers
{
public class FileTransferRequestHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.WriteFile(context.Request.RawUrl.TrimEnd('?'));
context.Response.End();
}
public bool IsReusable
{
get { return true; }
}
}
}

View file

@ -13,6 +13,14 @@ namespace WebsitePanel.WebDavPortal.Models
[Display(Name = @"Password")]
public string Password { get; set; }
public string UserName
{
get
{
return !string.IsNullOrEmpty(Login) ? Login.Split('@')[0] : string.Empty;
}
}
public string LdapError { get; set; }
}
}

View file

@ -5,6 +5,8 @@ namespace WebsitePanel.WebDavPortal.Models
{
public interface IWebDavManager
{
string RootPath { get; }
string OrganizationName { get; }
void OpenFolder(string pathPart);
IEnumerable<IHierarchyItem> GetChildren();
bool IsFile(string fileName);

View file

@ -7,36 +7,75 @@ using System.Text.RegularExpressions;
using WebsitePanel.WebDav.Core.Client;
using WebsitePanel.WebDavPortal.Config;
using WebsitePanel.WebDavPortal.Exceptions;
using WebsitePanel.Portal;
using WebsitePanel.Providers.OS;
using Ninject;
using WebsitePanel.WebDavPortal.DependencyInjection;
namespace WebsitePanel.WebDavPortal.Models
{
public class WebDavManager : IWebDavManager
{
private readonly WebDavSession _webDavSession = new WebDavSession();
private IList<SystemFile> _rootFolders;
private int _itemId;
private IFolder _currentFolder;
private string _organizationName;
private string _webDavRootPath;
private bool _isRoot = true;
public WebDavManager(ICredentials credentials)
public string RootPath
{
_webDavSession.Credentials = credentials;
ConnectToWebDavServer();
get { return _webDavRootPath; }
}
public WebDavManager()
public string OrganizationName
{
ConnectToWebDavServer();
get { return _organizationName; }
}
public WebDavManager(NetworkCredential credential, int itemId)
{
_webDavSession.Credentials = credential;
_itemId = itemId;
IKernel _kernel = new StandardKernel(new NinjectSettings { AllowNullInjection = true }, new WebDavExplorerAppModule());
var accountModel = _kernel.Get<AccountModel>();
_rootFolders = ConnectToWebDavServer(accountModel.UserName);
if (_rootFolders.Any())
{
var folder = _rootFolders.First();
var uri = new Uri(folder.Url);
_webDavRootPath = uri.Scheme + "://" + uri.Host + uri.Segments[0] + uri.Segments[1];
_organizationName = uri.Segments[1].Trim('/');
}
}
public void OpenFolder(string pathPart)
{
if (string.IsNullOrWhiteSpace(pathPart))
{
_isRoot = true;
return;
}
_isRoot = false;
_currentFolder = _webDavSession.OpenFolder(_webDavRootPath + pathPart);
}
public IEnumerable<IHierarchyItem> GetChildren()
{
IHierarchyItem[] children = _currentFolder.GetChildren();
List<IHierarchyItem> sortedChildren =
children.Where(x => x.ItemType == ItemType.Folder).OrderBy(x => x.DisplayName).ToList();
IHierarchyItem[] children;
if (_isRoot)
{
children = _rootFolders.Select(x => new WebDavHierarchyItem {Href = new Uri(x.Url), ItemType = ItemType.Folder}).ToArray();
}
else
{
children = _currentFolder.GetChildren();
}
List<IHierarchyItem> sortedChildren = children.Where(x => x.ItemType == ItemType.Folder).OrderBy(x => x.DisplayName).ToList();
sortedChildren.AddRange(children.Where(x => x.ItemType != ItemType.Folder).OrderBy(x => x.DisplayName));
return sortedChildren;
@ -44,10 +83,13 @@ namespace WebsitePanel.WebDavPortal.Models
public bool IsFile(string fileName)
{
if (string.IsNullOrWhiteSpace(fileName) | _currentFolder == null)
return false;
try
{
IResource resource = _currentFolder.GetResource(fileName);
Stream stream = resource.GetReadStream();
//Stream stream = resource.GetReadStream();
return true;
}
catch (InvalidOperationException)
@ -84,25 +126,16 @@ namespace WebsitePanel.WebDavPortal.Models
}
}
private void ConnectToWebDavServer()
private IList<SystemFile> ConnectToWebDavServer(string userName)
{
string webDavServerPath = WebDavAppConfigManager.Instance.ConnectionStrings.WebDavServer;
if (webDavServerPath == null ||
!Regex.IsMatch(webDavServerPath, @"^http(s)?://([\w-]+.)+[\w-]+(/[\w- ./?%&=])?$"))
throw new ConnectToWebDavServerException();
if (webDavServerPath.Last() != '/') webDavServerPath += "/";
_webDavRootPath = webDavServerPath;
try
var rootFolders = new List<SystemFile>();
foreach (var folder in ES.Services.EnterpriseStorage.GetEnterpriseFolders(_itemId))
{
_currentFolder = _webDavSession.OpenFolder(_webDavRootPath);
}
catch (WebException exception)
{
throw new ConnectToWebDavServerException(
string.Format("Unable to connect to a remote WebDav server \"{0}\"", webDavServerPath), exception);
var permissions = ES.Services.EnterpriseStorage.GetEnterpriseFolderPermissions(_itemId, folder.Name);
if (permissions.Any(x => x.DisplayName == userName))
rootFolders.Add(folder);
}
return rootFolders;
}
private byte[] ReadFully(Stream input)

View file

@ -1,6 +1,7 @@
using System;
using System.DirectoryServices;
using System.Security.Principal;
using WebsitePanel.WebDavPortal.Constants;
namespace WebsitePanel.WebDavPortal.Models
{

View file

@ -1,7 +1,9 @@
@using WebsitePanel.WebDav.Core.Client
@using Ninject
@model WebsitePanel.WebDavPortal.Models.ModelForWebDav
@{
ViewBag.Title = (string.IsNullOrEmpty(Model.UrlSuffix) ? "root" : Model.UrlSuffix);
var webDavManager = (new StandardKernel(new WebsitePanel.WebDavPortal.DependencyInjection.WebDavExplorerAppModule())).Get<WebsitePanel.WebDavPortal.Models.IWebDavManager>();
ViewBag.Title = (string.IsNullOrEmpty(Model.UrlSuffix) ? webDavManager.OrganizationName : Model.UrlSuffix);
}
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/appScripts")
@ -20,13 +22,13 @@ else
<div class="container">
@if (Model != null)
{
const string header = "root";
<a href="/root/" class="btn btn-primary btn-sm active" role="button">@header</a>
string header = webDavManager.OrganizationName;
<a href="/@header/" class="btn btn-primary btn-sm active" role="button">@header</a>
string[] elements = Model.UrlSuffix.Split(new[] {"/"}, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < elements.Length; i++)
{
<span class="glyphicon glyphicon-chevron-right" style="top: 2px;"></span>
<a href="@string.Concat("/root/", string.Join("/", elements.Take(i + 1)))" class="btn btn-primary btn-sm active" role="button">@elements[i]</a>
<a href="@string.Concat("/" + header + "/", string.Join("/", elements.Take(i + 1)))" class="btn btn-primary btn-sm active" role="button">@elements[i]</a>
}
}
</div>

View file

@ -1,6 +1,7 @@
@using WebsitePanel.WebDav.Core.Client
@using WebsitePanel.WebDavPortal.Config
@using WebsitePanel.WebDavPortal.FileOperations
@using Ninject;
@model IHierarchyItem
@{
@ -17,7 +18,9 @@
break;
default:
isTargetBlank = false;
href = string.Concat(Url.Action("ShowContent", "FileSystem"), Model.DisplayName);
IKernel _kernel = new StandardKernel(new WebsitePanel.WebDavPortal.DependencyInjection.WebDavExplorerAppModule());
var webDavManager = _kernel.Get<WebsitePanel.WebDavPortal.Models.IWebDavManager>();
href = Model.Href.AbsolutePath;
break;
}
}

View file

@ -18,10 +18,10 @@
<add key="SessionValidationKey" value="DAD46D476F85E0198BCA134D7AA5CC1D7" />
</appSettings>
<webDavExplorerConfigurationSettings>
<userDomain value="ITRANSITION"/>
<userDomain value="WEBSITEPANEL"/>
<applicationName value="WebDAV Explorer"/>
<elementsRendering defaultCount="20" addElementsCount="20"/>
<websitePanelConstantUser login="/s+FT5uzVxg1Klox7wS97A==" password="QJAxl7DwlSWWys1dRxT7Aw==" />
<websitePanelConstantUser login="/s+FT5uzVxg1Klox7wS97A==" password="L8FtiUt71E1Do/RmlN6bPA==" />
<rfc2898Cryptography passwordHash="66640c02dcdec47fb220539c1d47d80da5a98cd9c9fcebc317512db29a947e5c54667a85fdfdecfbde17ab76375bb9309e47025f7bb19a2c5df0c1be039d1c3d"
saltKey="f4f3397d550320975770be09e8f1510b1971b4876658ebb960a4b2df5b0d95059e8ac2c64eb8c0e0614df93bfbc31ece0f33121fc9c7bc9219db583eab3fee06"
VIKey="@1B2c3D4e5F6g7H8" />
@ -94,8 +94,9 @@
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="UrlRoutingModule-4.0" />
<add name="ChartImg" path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" resourceType="Unspecified" preCondition="integratedMode" />
<add name="FileHandler" path="root/*" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
<add name="FileHandler" path="*.*" verb="GET" type="WebsitePanel.WebDavPortal.HttpHandlers.FileTransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
</handlers>
<modules>
<add name="SecureSession" type="WebsitePanel.WebPortal.SecureSessionModule" />

View file

@ -21,6 +21,8 @@
<IISExpressWindowsAuthentication>disabled</IISExpressWindowsAuthentication>
<IISExpressUseClassicPipelineMode>false</IISExpressUseClassicPipelineMode>
<TargetFrameworkProfile />
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@ -152,6 +154,7 @@
<Compile Include="Config\IWebDavAppConfig.cs" />
<Compile Include="Config\WebDavAppConfigManager.cs" />
<Compile Include="Constants\DirectoryEntryPropertyNameConstants.cs" />
<Compile Include="Constraints\OrganizationRouteConstraint.cs" />
<Compile Include="Controllers\AccountController.cs" />
<Compile Include="Controllers\ErrorController.cs" />
<Compile Include="Controllers\FileSystemController.cs" />
@ -171,6 +174,7 @@
<Compile Include="Global.asax.cs">
<DependentUpon>Global.asax</DependentUpon>
</Compile>
<Compile Include="HttpHandlers\FileTransferRequestHandler.cs" />
<Compile Include="Models\AccountModel.cs" />
<Compile Include="Models\DirectoryIdentity.cs" />
<Compile Include="Models\ErrorModel.cs" />
@ -264,7 +268,9 @@
<Content Include="Scripts\respond.matchmedia.addListener.min.js" />
<Content Include="Scripts\respond.min.js" />
<Content Include="Scripts\_references.js" />
<Content Include="Web.config" />
<Content Include="Web.config">
<SubType>Designer</SubType>
</Content>
<Content Include="Web.Debug.config">
<DependentUpon>Web.config</DependentUpon>
</Content>
@ -321,7 +327,7 @@
<AutoAssignPort>True</AutoAssignPort>
<DevelopmentServerPort>3289</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:3155/</IISUrl>
<IISUrl>http://localhost:9005/</IISUrl>
<NTLMAuthentication>False</NTLMAuthentication>
<UseCustomServer>False</UseCustomServer>
<CustomServerUrl>
@ -331,6 +337,13 @@
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">

View file

@ -1,6 +1,6 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.30501.0
VisualStudioVersion = 12.0.30723.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{BB38798E-1528-493C-868E-005102316536}"
ProjectSection(SolutionItems) = preProject
@ -20,6 +20,13 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebsitePanel.WebDavPortal",
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebsitePanel.WebDav.Core", "WebsitePanel.WebDav.Core\WebsitePanel.WebDav.Core.csproj", "{BA147805-9EF1-45F2-BF32-A5825D4E950D}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{A4D4ACAB-C9A9-40EA-A497-DEC6775AC259}"
ProjectSection(SolutionItems) = preProject
.nuget\NuGet.Config = .nuget\NuGet.Config
.nuget\NuGet.exe = .nuget\NuGet.exe
.nuget\NuGet.targets = .nuget\NuGet.targets
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU