Ejemplo n.º 1
0
        private static void DeleteFile(Args args, CookieContainer cookBox, int fileId)
        {
            string requestUri = string.Format("{0}/servlets/ProjectDocumentDelete", args.Site);

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(requestUri);
            wr.UserAgent = UserAgentName;
            wr.CookieContainer = cookBox;
            using (WebFormWriter wfw = new WebFormWriter(wr, WebRequestPostDataEncoding.WwwFormUrlEncoded, "POST"))
            {
                wfw.AddValue("documentID", fileId.ToString(CultureInfo.InvariantCulture));
                wfw.AddValue("Button", "Confirm delete");
                wfw.AddValue("maxDepth", "");
            }

            using (WebResponse response = wr.GetResponse())
            {
                if (!response.ResponseUri.AbsolutePath.EndsWith("/ProjectDocumentList", StringComparison.OrdinalIgnoreCase))
                    throw new InvalidOperationException("Delete failed");
            }
        }
Ejemplo n.º 2
0
        static bool Run(Args args)
        {
            CookieContainer cookBox = new CookieContainer();

            if (args.IgnoreCertificateErrors)
            {
                ServicePointManager.ServerCertificateValidationCallback =
                    delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
                    {
                        return true;
                    };
            }

            string requestUri = string.Format("{0}/servlets/ProjectDocumentAdd?folderID={1}", args.Site, args.Folder);
            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(requestUri);
            wr.UserAgent = UserAgentName;
            wr.CookieContainer = cookBox;
            string responseUri;
            string text;

            using (WebResponse response = wr.GetResponse())
            {
                responseUri = response.ResponseUri.ToString();
                text = GetText(response);
            }

            MaybeLogin(args, cookBox, requestUri, responseUri, ref text);

            // Ok, we are logged in; let's upload the files

            if (!string.IsNullOrEmpty(args.Result) && File.Exists(args.Result))
                File.Delete(args.Result);

            foreach (string file in args.Files)
            {
                Console.WriteLine("Uploading {0}", Path.GetFileName(file));
                wr = (HttpWebRequest)WebRequest.Create(requestUri + "&action=Add%20document");
                wr.UserAgent = UserAgentName;
                wr.CookieContainer = cookBox;
                wr.Timeout = 1800 * 1000; // Half an hour should be enough
                using (WebFormWriter wfw = new WebFormWriter(wr, WebRequestPostDataEncoding.MultipartFormData, "POST"))
                {
                    wfw.AddValue("name", args.Name ?? Path.GetFileName(file));
                    wfw.AddValue("status", args.Status ?? "Draft");
                    wfw.AddValue("description", args.Description ?? "Description");
                    wfw.AddValue("initiallylocked", "");
                    wfw.AddValue("type", "file");
                    wfw.AddValue("textFormat", "pre");
                    wfw.AddFile("file", file);
                    wfw.AddValue("docUrl", "");
                    wfw.AddValue("submit", "submit");
                    wfw.AddValue("maxDepth", "");
                }

                using (WebResponse response = wr.GetResponse())
                {
                    text = GetText(response);

                    if (text.Contains("\"error"))
                    {
                        Console.Error.WriteLine("Upload failed");
                        return false;
                    }

                    // This page is currently not valid Xml; use regular expressions instead
                    Regex re = new Regex("\\<a[^>]*href=\"(?<url>[^\"]*" + Regex.Escape(Path.GetFileName(file)) + ")\"[^>]*\\>"
                        + "\\s*" + Regex.Escape(args.Name ?? Path.GetFileName(file)) + "\\s*</a>");

                    Match m = re.Match(text);

                    if (m.Success)
                    {
                        if (!string.IsNullOrEmpty(args.Result))
                            File.AppendAllText(args.Result, new Uri(new Uri(requestUri), m.Groups["url"].Value).AbsoluteUri + Environment.NewLine);
                    }
                    else
                    {
                        Console.Error.WriteLine("Failed to retrieve url from upload output");
                        Console.Error.WriteLine();
                        Console.Error.WriteLine("=====================");
                        Console.Error.WriteLine(text);
                        Console.Error.WriteLine("=====================");
                    }
                }
            }

            if (args.List)
            {
                foreach(Document doc in GetDocumentList(args, cookBox))
                {
                    Console.WriteLine(doc.DownloadUri.AbsoluteUri);
                }
            }

            if (args.MaxUploads > 0 || args.Keep != TimeSpan.Zero)
            {
                List<Document> docs = GetDocumentList(args, cookBox);

                RemoveOnStatus(args, docs); // Filter all not interesting documents (status, locks)
                SortDocs(docs);

                if (args.MaxUploads > 0 && docs.Count > args.MaxUploads)
                {
                    int from = docs.Count - args.MaxUploads;
                    docs.RemoveRange(from, docs.Count - from);
                }

                if (args.Keep > TimeSpan.Zero)
                {
                    FilterOnDate(docs, DateTime.Now.Date - args.Keep);
                }

                GC.KeepAlive(docs);
                foreach (Document doc in docs)
                {
                    Console.WriteLine("Deleting {0}", doc.Name);

                    DeleteFile(args, cookBox, doc.FileId);
                }
            }
            return true;
        }
Ejemplo n.º 3
0
        private static void MaybeLogin(Args args, CookieContainer cookBox, string requestUri, string responseUri, ref string text)
        {
            HttpWebRequest wr;
            if (responseUri != requestUri && responseUri.Contains("/Login"))
            {
                // Standard Collabnet login on secondary host..
                XmlDocument doc = new XmlDocument();

                XmlReaderSettings xs = new XmlReaderSettings();
                xs.ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags.None;
                xs.ValidationType = ValidationType.None;
                xs.ProhibitDtd = false;

                int nS = text.IndexOf("<html");

                if (nS > 0)
                    text = text.Substring(nS).Replace("&nbsp;", "&#160;").Replace("&copy;", "&#169;");

                text = Regex.Replace(text, @"(\<input[^>]*[^/])\>", "$1/>");

                int lastForm = text.LastIndexOf("<form ", StringComparison.OrdinalIgnoreCase);

                if (lastForm >= 0)
                {
                    int formClose = text.IndexOf("</form", lastForm, StringComparison.OrdinalIgnoreCase);

                    if (formClose >= 0)
                        text = text.Substring(lastForm, text.IndexOf('>', formClose) - lastForm+1);
                }

                doc.Load(XmlReader.Create(new StringReader(text), xs));

                XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
                nsmgr.AddNamespace("html", "http://www.w3.org/1999/xhtml");
                XmlElement form = (XmlElement)doc.SelectSingleNode("//html:form[@id='loginform']", nsmgr);

                if(form == null)
                    form = (XmlElement)doc.SelectSingleNode("//form[@id='loginform']", nsmgr);

                StringBuilder sb = new StringBuilder();

                wr = (HttpWebRequest)WebRequest.Create(new Uri(new Uri(responseUri), new Uri(form.GetAttribute("action"))));
                wr.UserAgent = UserAgentName;
                wr.CookieContainer = cookBox;
                using (WebFormWriter wfw = new WebFormWriter(wr, WebRequestPostDataEncoding.WwwFormUrlEncoded, "POST"))
                {
                    foreach (XmlElement el in form.SelectNodes(".//html:input[@name] | .//input[@name]", nsmgr))
                    {
                        string name = el.GetAttribute("name");

                        switch (name.ToUpperInvariant())
                        {
                            case "LOGINID":
                                wfw.AddValue(name, args.UserName);
                                break;
                            case "PASSWORD":
                                wfw.AddValue(name, args.Password);
                                break;
                            default:
                                string v = el.GetAttribute("value");
                                wfw.AddValue(name, v ?? "");
                                break;
                        }
                    }
                }

                using (WebResponse response = wr.GetResponse())
                {
                    responseUri = response.ResponseUri.ToString();
                    text = GetText(response);
                }

                if (responseUri != requestUri)
                {
                    throw new InvalidOperationException("Invalid credentials specified");
                }
            }
        }