<%@ Page Language="C#" EnableSessionState="false" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.Security" %>
<%@ Import Namespace="System.Web.UI" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<%@ Import Namespace="System.Web.UI.WebControls.WebParts" %>
<%@ Import Namespace="System.Web.UI.HtmlControls" %>


<script runat="server">
  
  private void validateProjectName(string projectName)
  {
    if (projectName.Contains("/") || projectName.Contains(@"\") || projectName.Split('_').Length < 2)
      throw new ArgumentException("projectname is invalid");
  }
  
  private void Page_Load(object sender, EventArgs e)
  {
    Response.Cache.SetNoStore();
    
    try
    {
      string projectName = Request.QueryString["projectname"];
      validateProjectName(projectName);
      
      if (!Directory.Exists(Server.MapPath(projectName)))
        Directory.CreateDirectory(Server.MapPath(projectName));
      
      string[] fileKeys = Request.Files.AllKeys;
      foreach (string key in fileKeys)
      {
        HttpPostedFile file = Request.Files[key];
        string fileName = Server.MapPath(projectName + @"\" + file.FileName);
        if (fileName.EndsWith(".vxml"))
        {
          using (StreamReader reader = new StreamReader(file.InputStream, Encoding.ASCII))
          {
            string fileContent = reader.ReadToEnd();
            fileContent = fileContent.Replace("audio src=\"", "audio src=\"file:///" + Server.MapPath(projectName + @"\"))
                                     .Replace("<var name=\"application.project$_WorkingDirectory$\" expr=\"''\" />", "<var name=\"application.project$_WorkingDirectory$\" expr=\"'" + Server.MapPath(projectName).Replace("\\", "\\\\") + "'\" />");
            File.WriteAllText(fileName, fileContent, Encoding.ASCII);
          }
        }
        else
          file.SaveAs(fileName);
      }
      
      Response.Write("OK");
    }
    catch (Exception exc)
    {
      Response.Write("ERROR: " + exc.Message);
    }
  }
  
</script>
