예제 #1
0
        public static List <CalendarEvent> GetUpcomingCalendarEvents(int numberOfEvents = 5)
        {
            if (Credentials == null)
            {
                Credentials = new GDataCredentials("*****@*****.**", "popcorn");
            }
            if (QueryUri == null)
            {
                QueryUri = "http://www.google.com/calendar/feeds/" + Credentials.Username + "/public/full";
            }

            CalendarService service = new CalendarService("Agenda");
            EventQuery      query   = new EventQuery(QueryUri);

            query.FutureEvents     = true;
            query.SingleEvents     = true;
            query.SortOrder        = CalendarSortOrder.ascending;
            query.NumberToRetrieve = numberOfEvents;
            query.ExtraParameters  = "orderby=starttime";
            var events = service.Query(query);

            return((from e in events.Entries
                    where !String.IsNullOrEmpty(e.Title.Text)
                    select new CalendarEvent()
            {
                Title = e.Title.Text,
                URI = e.AlternateUri.Content,
                Description = e.Content.Content,
                StartTime = (e as EventEntry).Times[0].StartTime,
                EndTime = (e as EventEntry).Times[0].EndTime
            }).ToList <CalendarEvent>());
        }
예제 #2
0
        public static void ExportDocList(string outFolder, string username, string password)
        {
            GDataCredentials credentials = new GDataCredentials(username, password);
            RequestSettings  settings    = new RequestSettings("GDocBackup", credentials);

            settings.AutoPaging = true;
            settings.PageSize   = 100;
            DocumentsRequest request = new DocumentsRequest(settings);

            Feed <Document> feed = request.GetEverything();
            List <Document> docs = new List <Document>();

            foreach (Document entry in feed.Entries)
            {
                docs.Add(entry);
            }

            using (StreamWriter outFile = new StreamWriter(Path.Combine(outFolder, "doclist.txt"), false),
                   outFile2 = new StreamWriter(Path.Combine(outFolder, "doclistdetails.txt"), false))
            {
                foreach (Document doc in docs)
                {
                    string s = doc.Title + "\t" + doc.ResourceId;
                    outFile.WriteLine(s);
                    outFile2.WriteLine(s);
                    foreach (string pf in doc.ParentFolders)
                    {
                        outFile2.WriteLine("\t\t\t" + pf);
                    }
                }
                outFile.Close();
                outFile2.Close();
            }
        }
예제 #3
0
 public void Logout()
 {
     _username    = null;
     _password    = null;
     _credentials = null;
     OnLoginStatusChanged();
 }
        private void LoadAppSettings()
        {
            // Get the AppSettings collection.
            NameValueCollection appSettings = ConfigurationSettings.AppSettings;

            if (appSettings[YouTubeUploader.CONFIG_DEVKEY] != null)
            {
                this.developerKey = appSettings[YouTubeUploader.CONFIG_DEVKEY];
            }
            else
            {
                this.developerKey = YouTubeUploader.DeveloperKeyDefault;
            }

            if (String.IsNullOrEmpty(this.developerKey))
            {
                MessageBox.Show("You need to enter a developer key in the source code. Look for DeveloperKeyDefault and paste your key in");
                this.Close();
            }

            if (appSettings[YouTubeUploader.CONFIG_MAXTHREADS] != null)
            {
                this.MaxQueue.Value = Decimal.Parse(appSettings[YouTubeUploader.CONFIG_MAXTHREADS]);
            }
            else
            {
                this.MaxQueue.Value = 3;
            }

            if (appSettings[YouTubeUploader.CONFIG_RETRYCOUNT] != null)
            {
                this.automaticRetries.Value = Decimal.Parse(appSettings[YouTubeUploader.CONFIG_RETRYCOUNT]);
            }
            else
            {
                this.automaticRetries.Value = 10;
            }

            if (appSettings[YouTubeUploader.CONFIG_CHUNKSIZE] != null)
            {
                this.ChunkSize.Value = Decimal.Parse(appSettings[YouTubeUploader.CONFIG_CHUNKSIZE]);
            }
            else
            {
                this.ChunkSize.Value = 25;
            }

            this.csvFileName    = appSettings[YouTubeUploader.CONFIG_CSVFILE];
            this.outputFileName = appSettings[YouTubeUploader.CONFIG_OUTPUTFILE];
            if (appSettings[YouTubeUploader.CONFIG_USERNAME] != null)
            {
                this.credentials = new GDataCredentials(appSettings[YouTubeUploader.CONFIG_USERNAME],
                                                        appSettings[YouTubeUploader.CONFIG_PASSWORD]);
            }
            this.youtubeAccount = appSettings[YouTubeUploader.CONFIG_YTACCOUNT];
        }
        public void CredentialsTest()
        {
            Service          target   = new Service(); // TODO: Initialize to an appropriate value
            GDataCredentials expected = new GDataCredentials("test", "pwd");
            GDataCredentials actual;

            target.Credentials = expected;
            actual             = target.Credentials;
            Assert.AreEqual(expected, actual);
        }
예제 #6
0
        public void NetworkCredentialTest()
        {
            string           username = "******";                              // TODO: Initialize to an appropriate value
            string           password = "******";                              // TODO: Initialize to an appropriate value
            GDataCredentials target   = new GDataCredentials(username, password); // TODO: Initialize to an appropriate value
            ICredentials     actual;

            actual = target.NetworkCredential;
            Assert.IsNotNull(actual);
        }
예제 #7
0
        private void GetDocListExec()
        {
            WriteMessage("*** GetDocList ***");
            WriteMessage("--- START ---");

            try
            {
                string username = tbUserName.Text;;
                string password = tbPassword.Text;

                GDataCredentials credentials = new GDataCredentials(username, password);
                RequestSettings  settings    = new RequestSettings("GDocBackup", credentials);
                settings.AutoPaging = true;
                settings.PageSize   = 100;
                DocumentsRequest request = new DocumentsRequest(settings);

                Feed <Document> feed = request.GetEverything();
                List <Document> docs = new List <Document>();
                foreach (Document entry in feed.Entries)
                {
                    docs.Add(entry);
                }

                StreamWriter outFile  = new StreamWriter("doclist.txt", false);
                StreamWriter outFile2 = new StreamWriter("doclistdetails.txt", false);

                WriteMessage("Exporting document list. Please wait...");

                foreach (Document doc in docs)
                {
                    string s = doc.Title + "\t" + doc.ResourceId;
                    //WriteMessage(s);
                    outFile.WriteLine(s);
                    outFile2.WriteLine(s);
                    foreach (string pf in doc.ParentFolders)
                    {
                        outFile2.WriteLine("\t\t\t" + pf);
                    }
                }

                WriteMessage("Created file: doclist.txt");
                WriteMessage("Created file: doclistdetails.txt");


                outFile.Close();
                outFile2.Close();
            }
            catch (Exception ex)
            {
                WriteMessage("EXCEPTION: " + ex.ToString());
            }


            WriteMessage("--- END ---");
        }
예제 #8
0
        public void UsernameTest()
        {
            string           username = "******";                              // TODO: Initialize to an appropriate value
            string           password = "******";                              // TODO: Initialize to an appropriate value
            GDataCredentials target   = new GDataCredentials(username, password); // TODO: Initialize to an appropriate value
            string           expected = "TestValue";
            string           actual;

            target.Username = expected;
            actual          = target.Username;
            Assert.AreEqual(expected, actual);
        }
예제 #9
0
        /// <summary>
        /// Submits a new atom entry to a particular Google service.
        /// </summary>
        /// <typeparam name="TFeed">Type of feed for the service.</typeparam>
        /// <typeparam name="TEntry">Type of feed entry for the service.</typeparam>
        /// <param name="entry">The atom entry object containing the data to submit.</param>
        /// <param name="applicationName">The name of the application which invokes this method.</param>
        /// <returns>A new atom entry containing some additional data like id, published date etc.</returns>
        protected virtual TEntry SubmitNewEntry <TFeed, TEntry>(TEntry entry, string applicationName)
            where TFeed : GFeed <TEntry>, new()
            where TEntry : GEntry, new()
        {
            if (String.IsNullOrEmpty(GUrl))
            {
                throw new ArgumentNullException(GUrl,
                                                "Feed Url is not provided. Please provide Feed url first through GUrl Property.");
            }

            var request = WebRequest.Create(GUrl) as HttpWebRequest;

            if (request != null)
            {
                var    serializer = new XObjectSerializer <TEntry>();
                string xml        = serializer.StringSerialize(entry);
                long   length     = xml.ToCharArray().LongLength;

                var gc = new GDataCredentials(GUserName, GPassword)
                {
                    AccountType = "GOOGLE"
                };
                string header = GAuthManager.RequestClientLoginHeader(gc, "code", applicationName, true,
                                                                      GoogleAuthentication.URI_HANDLER, ProxySettings);
                if (ProxySettings != null)
                {
                    request.Proxy = ProxySettings;
                }
                request.Method      = "POST";
                request.Credentials = new NetworkCredential
                {
                    UserName = GUserName,
                    Password = GPassword
                };
                request.ContentType   = "application/atom+xml";
                request.ContentLength = length;
                request.Headers.Add(header);

                var sw = new StreamWriter(request.GetRequestStream());
                sw.Write(xml);
                sw.Close();

                var webData = new GWebAsyncData <TFeed, TEntry>
                {
                    Request = request, ResetEvent = new ManualResetEvent(false)
                };
                IAsyncResult result = request.BeginGetResponse(AsyncManager <TFeed, TEntry> .AsyncSubmitNewEntry, webData);

                ((GWebAsyncData <TFeed, TEntry>)result.AsyncState).ResetEvent.WaitOne();
                return(((GWebAsyncData <TFeed, TEntry>)result.AsyncState).EntryResult);
            }
            throw new OutOfMemoryException("Unable to create new WebRequest");
        }
예제 #10
0
 private void Login_Click(object sender, System.EventArgs e)
 {
     try
     {
         this.credentials  = new GDataCredentials(this.Username.Text, this.Password.Text);
         this.DialogResult = DialogResult.OK;
         this.Close();
     }
     catch (AuthenticationException a)
     {
         MessageBox.Show(a.Message);
     }
 }
예제 #11
0
        public override bool Execute()
        {
            GDataCredentials credentials = GetDataCredentials();
            RequestSettings  settings    = new RequestSettings("code.google.com/p/exult/", credentials);

            settings.AutoPaging = true;
            settings.PageSize   = 100;
            Request request = new Request(settings);

            WarnIfUneven(Tuple.Create("Documents", Documents), Tuple.Create("Downloads", Downloads));
            foreach (var tuple in Zip(Documents, Downloads))
            {
                tuple.Item1.LoadCustomMetadata();
                DoDownload(request, tuple.Item1, tuple.Item2);
            }
            return(true);
        }
예제 #12
0
        public override bool Execute()
        {
            GDataCredentials credentials = GetDataCredentials();
            RequestSettings  settings    = new RequestSettings("code.google.com/p/exult/", credentials);

            settings.AutoPaging = true;
            settings.PageSize   = 100;

            DocumentsRequest request = new DocumentsRequest(settings);
            Feed <Document>  feed    = request.GetFolders();

            List <ITaskItem> outputs = new List <ITaskItem>();

            // this takes care of paging the results in
            List <Document> entries = feed.Entries.ToList();
            IDictionary <string, Document> documentDictionary = entries.ToDictionary(item => item.Self);

            RequireDirectory(TargetDirectory);

            foreach (Document entry in entries)
            {
                if (_Cancelled)
                {
                    return(false);
                }

                List <PathMapping> paths = GetPaths(entry, documentDictionary).ToList();

                //handle each path, as we may allow multiple locations for a collection
                foreach (PathMapping path in paths)
                {
                    if (Pattern == null || PatternExpression.IsMatch(path.TitlePath))
                    {
                        Log.LogMessage(MessageImportance.High, "Matched \"{0}\"", path.TitlePath);
                        outputs.Add(BuildFolder(entry, path));
                    }
                    else
                    {
                        Log.LogMessage(MessageImportance.Low, "Skipped \"{0}\"", path.TitlePath);
                    }
                }
            }
            Folders = outputs.ToArray();
            return(true);
        }
예제 #13
0
        private void ss()
        {
            GDataCredentials credentials = new GDataCredentials("*****@*****.**", "198ytdblbvrfpa$$w0rd");
            RequestSettings  settings    = new RequestSettings("Testing", credentials);

            settings.AutoPaging = true;
            settings.PageSize   = 100;
            DocumentsRequest documentsRequest = new DocumentsRequest(settings);
            Feed <Document>  documentFeed     = documentsRequest.GetDocuments();

            Document doc = new Document();

            foreach (Document document in documentFeed.Entries)
            {
            }

            documentsRequest.CreateDocument(new Document());
        }
예제 #14
0
        public static void Exec(string[] args)
        {
            Console.WriteLine("*** GetDocList ***");
            Console.WriteLine("--- START ---");

            string username = args[1];
            string password = args[2];

            GDataCredentials credentials = new GDataCredentials(username, password);
            RequestSettings  settings    = new RequestSettings("GDocBackup", credentials);

            settings.AutoPaging = true;
            settings.PageSize   = 100;
            DocumentsRequest request = new DocumentsRequest(settings);

            Feed <Document> feed = request.GetEverything();
            List <Document> docs = new List <Document>();

            foreach (Document entry in feed.Entries)
            {
                docs.Add(entry);
            }

            StreamWriter outFile  = new StreamWriter("doclist.txt", false);
            StreamWriter outFile2 = new StreamWriter("doclistdetails.txt", false);

            foreach (Document doc in docs)
            {
                string s = doc.Title + "\t" + doc.ResourceId;
                Console.WriteLine(s);
                outFile.WriteLine(s);
                outFile2.WriteLine(s);
                foreach (string pf in doc.ParentFolders)
                {
                    outFile2.WriteLine("\t\t\t" + pf);
                }
            }
            outFile.Close();
            outFile2.Close();

            Console.WriteLine("--- END ---");
        }
예제 #15
0
        public bool Login(string username, string password)
        {
            using (new WaitCursor())
            {
                try
                {
                    _username = username;
                    _password = password;
                    TransientCredentials creds = new TransientCredentials(username, password, null);
                    _credentials = GDataCredentials.FromCredentials(creds);
                    _credentials.EnsureLoggedIn(username, password, GDataCredentials.YOUTUBE_SERVICE_NAME, true, GDataCredentials.YOUTUBE_CLIENT_LOGIN_URL);
                }
                catch (Exception)
                {
                    _credentials = null;
                }
            }

            OnLoginStatusChanged();
            return(IsLoggedIn);
        }
예제 #16
0
 private void Login_Click(object sender, System.EventArgs e)
 {
     try
     {
         this.credentials = new GDataCredentials(this.Username.Text, this.Password.Text);
         RequestSettings settings = new RequestSettings("Authenticate", credentials);
         if (settings != null)
         {
             this.DialogResult = DialogResult.OK;
             this.Close();
         }
         else
         {
             MessageBox.Show("Invalid username or password!!!");
         }
     }
     catch (AuthenticationException a)
     {
         MessageBox.Show(a.Message);
     }
 }
예제 #17
0
        public override bool Execute()
        {
            GDataCredentials credentials = GetDataCredentials();
            RequestSettings  settings    = new RequestSettings("code.google.com/p/exult/", credentials);

            settings.AutoPaging = true;
            settings.PageSize   = 100;

            DocumentsService service = new DocumentsService("Exult");

            service.Credentials = credentials;

            // Instantiate a ChangesQuery object to retrieve changes.
            ChangesQuery query = new ChangesQuery();


            // Make a request to the API and get all changes.
            ChangesFeed feed = service.Query(query);

            // Iterate through all of the changes returned
            foreach (ChangeEntry entry in feed.Entries)
            {
                //if (Pattern == null || PatternExpression.IsMatch(entry.TitlePath))
                //{
                //    Log.LogMessage(MessageImportance.High, "Matched \"{0}\"", path.TitlePath);
                //    outputs.Add(BuildFolder(entry, path));
                //}
                //else
                //{
                //    Log.LogMessage(MessageImportance.Low, "Skipped \"{0}\"", path.TitlePath);
                //}


                // Print the title and changestamp of this document to the screen
                Log.LogMessage(MessageImportance.Normal, entry.Title.Text);
                Log.LogMessage(MessageImportance.Normal, entry.Changestamp);
            }

            return(true);
        }
예제 #18
0
 private void Login_Click(object sender, System.EventArgs e)
 {
     this.credentials = new GDataCredentials(this.Username.Text, this.Password.Text);
     this.Close();
 }
예제 #19
0
        public override bool Execute()
        {
            GDataCredentials credentials = GetDataCredentials();
            RequestSettings  settings    = new RequestSettings("code.google.com/p/exult/", credentials);

            settings.AutoPaging = true;
            settings.PageSize   = 100;

            List <ITaskItem> folderContent = new List <ITaskItem>();

            WarnIfUneven(Tuple.Create("Folders", Folders), Tuple.Create("FolderListings", FolderListings));
            foreach (var tuple in Zip(Folders, FolderListings))
            {
                if (_Cancelled)
                {
                    return(false);
                }

                ITaskItem folder        = tuple.Item1;
                ITaskItem folderListing = tuple.Item2;

                folder.LoadCustomMetadata();
                folder.RequireDocumentType(Document.DocumentType.Folder);

                //yada/hrm.folder -> yada/hrm/
                string folderPath = Path.Combine(Path.GetDirectoryName(folder.ItemSpec), Path.GetFileNameWithoutExtension(folder.ItemSpec));
                RequireDirectory(folderPath);
                PathMapping folderMapping = new PathMapping(folderPath);

                Request request = new Request(settings);

                string resourceId = folder.RequireResourceId();

                Log.LogMessage(MessageImportance.High, "Getting Folder Content \"{0}\"", folder.RequireTitlePath());
                Feed <Document> feed = request.GetFolderContent(resourceId);

                // this takes care of paging the results in
                List <Document> documents = feed.Entries.Where(item => item.Type != Document.DocumentType.Folder).ToList();
                Log.LogMessage(MessageImportance.Normal, "Found {0} Item(s)", documents.Count);

                DateTime folderTimestamp = folder.GetTimestamp();
                DateTime latestTimestamp = folderTimestamp;

                foreach (Document document in documents)
                {
                    if (_Cancelled)
                    {
                        return(false);
                    }

                    if (document.Updated > latestTimestamp)
                    {
                        latestTimestamp = document.Updated;
                    }
                    if (Pattern == null || PatternExpression.IsMatch(document.Title))
                    {
                        Log.LogMessage(MessageImportance.Normal, "Matched \"{0}\"", document.Title);
                        folderContent.Add(BuildContent(folder, document, folderMapping));
                    }
                    else
                    {
                        Log.LogMessage(MessageImportance.Low, "Skipped \"{0}\"", document.Title);
                    }
                }
                folder.CopyMetadataTo(folderListing);
                folderListing.Save(Log, latestTimestamp);
            }
            FolderContent = folderContent.ToArray();
            return(true);
        }
예제 #20
0
        /// <summary>
        /// Exec backup (internal)
        /// </summary>
        private int ExecBackupSingleUser(string username)
        {
            DoFeedback(new string('-', 80));
            DoFeedback("--- ExecBackupSingleUser - username="******" ---");
            DoFeedback(new string('-', 80));

            _lastException      = null;
            _duplicatedDocNames = new List <string>();

            // Setup credentials and connection
            DoFeedback("Setup connection & get doc list");
            RequestSettings settings;

            if (_config.appsMode == false)
            {
                GDataCredentials credentials = new GDataCredentials(_config.userName, _config.password);
                settings            = new RequestSettings("GDocBackup", credentials);
                settings.AutoPaging = true;
                settings.PageSize   = 100;
            }
            else
            {
                settings            = new RequestSettings("GDocBackup", _config.appsDomain, _config.appsOAuthSecret, username, _config.appsDomain);
                settings.AutoPaging = true;
                settings.PageSize   = 100;
                //settings.Maximum = 10000;
            }

            DocumentsRequest request = new DocumentsRequest(settings);

            if (_config.iwebproxy != null)
            {
                request.Proxy = _config.iwebproxy;
            }


            // Get doc list from GDocs
            Feed <Document> feed = request.GetEverything();
            List <Document> docs = new List <Document>();

            foreach (Document entry in feed.Entries)
            {
                docs.Add(entry);
            }


            // Search for duplicated doc names in the same folder
            _duplicatedDocNames = this.FindDuplicatedNames(docs);
            DoFeedback("Duplicated Doc Names [" + _duplicatedDocNames.Count + "]");
            _duplicatedDocNames.ForEach(delegate(string s) { DoFeedback(" - " + s); });


            // Builds/updates local folder structure
            if (_config.appsMode)
            {
                this.BuildFolders(null, docs, Path.Combine(_config.outDir, username));
            }
            else
            {
                this.BuildFolders(null, docs, _config.outDir);
            }
            foreach (String k in _folderDict.Keys)
            {
                DoFeedbackDebug("FolderDict: " + k + " --> " + _folderDict[k]);
            }
            this.DumpAllDocInfo(docs);

            // Main Docs loop!
            int errorCount = 0;

            for (int i = 0; i < docs.Count; i++)
            {
                Document doc = docs[i];
                DoFeedback("ITEM: " + doc.Title + " (" + doc.Type + ") [" + (i + 1).ToString() + "/" + docs.Count + "]", ((double)i) / docs.Count);

                Document.DownloadType[] downloadTypes = null;
                switch (doc.Type)
                {
                case Document.DocumentType.Document:
                    downloadTypes = _config.docExpType;
                    break;

                case Document.DocumentType.Presentation:
                    downloadTypes = _config.presExpType;
                    break;

                case Document.DocumentType.Spreadsheet:
                    downloadTypes = _config.sprdExpType;
                    break;

                case Document.DocumentType.PDF:
                    downloadTypes = new Document.DownloadType[] { Document.DownloadType.pdf };
                    break;

                case Document.DocumentType.Drawing:
                    downloadTypes = _config.drawExpType;
                    break;

                case Document.DocumentType.Unknown:
                    downloadTypes = new Document.DownloadType[] { Document.DownloadType.zip };      // download format not used! It's only a "place-holder".
                    break;

                default:
                    break;
                }


                if (downloadTypes != null)
                {
                    int maxTentativi = 2;
                    for (int tentativi = 0; tentativi < maxTentativi; tentativi++)
                    {
                        try
                        {
                            // * WorkAround for drawing *
                            // Detect if drawing and then force downloadtype to pdf
                            //bool isDrawing = doc.ResourceId.StartsWith("drawing:");   // drawing:14TBycKwlpXJ25N......
                            //if (isDrawing)
                            //    downloadTypes = new Document.DownloadType[] { Document.DownloadType.pdf };
                            // bool isDrawing = false;

                            foreach (Document.DownloadType downloadtype in downloadTypes)
                            {
                                // Build local file path
                                string outFolderPath;
                                if (doc.ParentFolders.Count == 0)
                                {
                                    outFolderPath = _config.appsMode ? Path.Combine(_config.outDir, username) : _config.outDir;
                                }
                                else
                                {
                                    DoFeedback("Try to get folder from dict using key=[" + doc.ParentFolders[0] + "]");
                                    outFolderPath = _folderDict[doc.ParentFolders[0]];
                                }
                                string outFileFP =
                                    (doc.Type == Document.DocumentType.Unknown) ?
                                    Path.Combine(outFolderPath, this.RemoveInvalidChars(doc.Title, true)) :
                                    Path.Combine(outFolderPath, this.RemoveInvalidChars(doc.Title, false) + "." + ConvertDownloadTypeToFileExtension(downloadtype));

                                // Get current local file in infos
                                FileInfo fi = new FileInfo(outFileFP);
                                DateTime locFileDateTime  = fi.LastWriteTime;
                                DateTime gdocFileDateTime = doc.Updated;

                                // Mono and/or Ubuntu (...linux) does not support milliseconds info when saving DataTime to FileInfo.LastWriteTime. So... I remove it!   :)
                                locFileDateTime  = this.RemoveMilliseconds(locFileDateTime);
                                gdocFileDateTime = this.RemoveMilliseconds(gdocFileDateTime);

                                bool downloadDoc = (!fi.Exists || _config.downloadAll);

                                if (_config.dateDiff.HasValue)
                                {
                                    if (Math.Abs(locFileDateTime.Subtract(gdocFileDateTime).TotalSeconds) > _config.dateDiff.Value)
                                    {
                                        downloadDoc = true;
                                    }
                                }
                                else
                                {
                                    if (locFileDateTime != gdocFileDateTime)
                                    {
                                        downloadDoc = true;
                                    }
                                }


                                if (downloadDoc)
                                {
                                    DoFeedback("Start exporting " + doc.Title + "(Type=" + doc.Type + ") --> " + downloadtype.ToString());
                                    Stream gdocStream = null;
                                    try
                                    {
                                        if (doc.Type == Document.DocumentType.Unknown)
                                        {
                                            String downloadUrl = doc.DocumentEntry.Content.Src.ToString();
                                            Uri    downloadUri = new Uri(downloadUrl);
                                            if (_config.appsMode)
                                            {
                                                // add xoauth_requestor_id to the doc url if not present
                                                if (!downloadUrl.Contains("xoauth_requestor_id="))
                                                {
                                                    downloadUri = new Uri(downloadUrl + "&xoauth_requestor_id=" + this.BuildDomainUserFullName(username));
                                                }
                                            }
                                            gdocStream = request.Service.Query(downloadUri);
                                        }
                                        else if (doc.Type == Document.DocumentType.Document)
                                        {
                                            gdocStream = request.Download(doc, downloadtype.ToString());
                                        }
                                        else if (doc.Type == Document.DocumentType.Spreadsheet)
                                        {
                                            gdocStream = request.Download(doc, downloadtype.ToString());   // WAS: downloadtype.ToString());
                                        }
                                        else if (doc.Type == Document.DocumentType.Presentation)
                                        {
                                            gdocStream = request.Download(doc, downloadtype.ToString());
                                        }
                                        else if (doc.Type == Document.DocumentType.Drawing)
                                        {
                                            gdocStream = request.Download(doc, downloadtype.ToString());
                                        }
                                        else if (doc.Type != Document.DocumentType.PDF)
                                        {
                                            // *** ??? ***
                                            gdocStream = request.Download(doc, downloadtype);
                                        }
                                        else
                                        {
                                            // *** PDF ***
                                            if (_config.appsMode)
                                            {
                                                // add xoauth_requestor_id to the doc url if not present
                                                string url = doc.DocumentEntry.Content.Src.ToString();
                                                if (!url.Contains("xoauth_requestor_id="))
                                                {
                                                    doc.DocumentEntry.Content.Src = new AtomUri(url + "&xoauth_requestor_id=" + this.BuildDomainUserFullName(username));
                                                }
                                            }
                                            gdocStream = request.Download(doc, null);
                                        }

                                        using (FileStream outFile = new FileStream(outFileFP, FileMode.Create, FileAccess.Write))
                                        {
                                            byte[] buffer = new byte[8192];
                                            int    bytesRead;
                                            while ((bytesRead = gdocStream.Read(buffer, 0, buffer.Length)) > 0)
                                            {
                                                outFile.Write(buffer, 0, bytesRead);
                                            }
                                            outFile.Close();
                                        }
                                        gdocStream.Close();
                                    }
                                    finally
                                    {
                                        if (gdocStream != null)
                                        {
                                            gdocStream.Dispose();
                                        }
                                    }

                                    new FileInfo(outFileFP).LastWriteTime = doc.Updated;
                                    DoFeedback("End exporting " + doc.Title + "(Type=" + doc.Type + ") --> " + downloadtype.ToString());

                                    // ------------------------------------------------------------------------------------------------------------------------
                                    // Workaround for Issue 100 - http://code.google.com/p/gdocbackup/issues/detail?id=100
                                    if (doc.Type == Document.DocumentType.Presentation)
                                    {
                                        bool isPPTX = false;

                                        using (FileStream presentationFile = new FileStream(outFileFP, FileMode.Open, FileAccess.Read))
                                        {
                                            int byte1 = presentationFile.ReadByte();
                                            int byte2 = presentationFile.ReadByte();
                                            isPPTX = (byte1 == 80 && byte2 == 75);   // 80 75 = "PK" (pptx is a zip. Every zip starts with "PK"
                                            presentationFile.Close();
                                        }

                                        if (!isPPTX)
                                        {
                                            string newName = outFileFP.Remove(outFileFP.Length - 1);
                                            File.Delete(newName);
                                            File.Move(outFileFP, newName);
                                            DoFeedback("Presentation API bug: renaming output file [" + newName + "]");
                                        }
                                    }
                                    // ------------------------------------------------------------------------------------------------------------------------
                                }
                                else
                                {
                                    DoFeedback("Skipped doc: " + doc.Title);
                                }

                                // Send Feedback
                                DoFeedback(new FeedbackObject(
                                               (_config.appsMode ? username + "#" + doc.Title : doc.Title),
                                               doc.Type.ToString(),
                                               (doc.Type == Document.DocumentType.Unknown) ? "BIN" : downloadtype.ToString(),
                                               downloadDoc ? "BCKUP" : "SKIP",
                                               "", locFileDateTime, gdocFileDateTime));

                                tentativi = maxTentativi;
                            }
                        }
                        catch (Exception ex)
                        {
                            if (tentativi == maxTentativi - 1)
                            {
                                errorCount++;
                                DoFeedback("DOC-ERROR: " + ex.ToString());
                                DoFeedback(new FeedbackObject(
                                               (_config.appsMode ? username + "#" + doc.Title : doc.Title),
                                               doc.Type.ToString(),
                                               "", "ERROR", "", null, null));
                            }
                            else
                            {
                                DoFeedback("DOC-ERROR: (attempt " + tentativi + ") " + ex.ToString());
                            }
                        }
                    }
                }
                else
                {
                    if (doc.Type != Document.DocumentType.Folder)
                    {
                        DoFeedback(new FeedbackObject(doc.Title, doc.Type.ToString(), "", "NONE", "", null, null));
                    }
                }
            }

            return(errorCount);
        }
예제 #21
0
 private void Cancel_Click(object sender, System.EventArgs e)
 {
     this.credentials = null;
     this.Close();
 }