Beispiel #1
0
 internal void Add(DatabaseRow databaseRow)
 {
     databaseRows.Add(databaseRow);
 }
Beispiel #2
0
    private async Task Run(Boolean refresh)
    {
      UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        new ClientSecrets
        {
          ClientId = CLIENT_ID,
          ClientSecret = CLIENT_SECRET
        },
        new[] { SCOPE },
        "user",
        CancellationToken.None, new FileDataStore("Spreadsheet.aboveTradera"));

      if (refresh)
      {
        refresh = credential.RefreshTokenAsync(CancellationToken.None).Result;
      }
      var requestFactory = new GDataRequestFactory("My App User Agent");
      requestFactory.CustomHeaders.Add(string.Format("Authorization: Bearer {0}", credential.Token.AccessToken));

      var service = new SpreadsheetsService("MySpreadsheetIntegration-v1");
      service.RequestFactory = requestFactory;

      // Create Drive API service.
      drive = new DriveService(new BaseClientService.Initializer()
      {
        HttpClientInitializer = credential,
        ApplicationName = "aboveTradera",
      });

      main.UseWaitCursor = false;
      
      var query = new SpreadsheetQuery();
      query.Title = "Samling";
      query.Exact = true;

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

      var spreadsheet = (SpreadsheetEntry)feed.Entries[0];
      // Console.WriteLine(spreadsheet.Title.Text);

      // Make a request to the API to fetch information about all
      // worksheets in the spreadsheet.
      var wsFeed = spreadsheet.Worksheets;

      // Iterate through each worksheet in the spreadsheet.
      foreach (WorksheetEntry entry in wsFeed.Entries)
      {
        // Get the worksheet's title, row count, and column count.
        string title = entry.Title.Text;
        uint rowCount = entry.Rows;
        uint colCount = entry.Cols;

        // Print the fetched information to the screen for this worksheet.
        // Console.WriteLine(title + "- rows:" + rowCount + " cols: " + colCount);
      }

      var worksheet = (WorksheetEntry)wsFeed.Entries[0];
      var listFeedLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null);

      // Fetch the list feed of the worksheet.
      var listQuery = new ListQuery(listFeedLink.HRef.ToString());
      var listFeed = service.Query(listQuery);

      database = Database.Load();

      if (database == null)
      {
        database = new Database();
      }

      // Download all stamps there is in Östergötland.
      Database newDatabase = new Database();
      DatabaseRow databaseRow = new DatabaseRow();
      newDatabase.Add(databaseRow);
      foreach (ListEntry row in listFeed.Entries)
      {
        if (row.Title.Text.StartsWith("Row:"))
        {
          databaseRow.Add(row);
        }
        else
        {
          databaseRow = new DatabaseRow(row);
          newDatabase.Add(databaseRow);
        }
      }

      var request = drive.Children.List("root");
      ChildList children = request.Execute();
      Google.Apis.Drive.v2.Data.File frimärken = null;
      foreach (var folder in children.Items)
      {
        frimärken = drive.Files.Get(folder.Id).Execute();
        if (frimärken.Title == "Frimärken")
        {
          break;
        }
      }

      // Download a File descriptor for all stamps in my collection.
      List<aboveTradera.DatabaseRowEntry.KeyValuePair<String, List<Google.Apis.Drive.v2.Data.File>>> images = new List<aboveTradera.DatabaseRowEntry.KeyValuePair<string, List<Google.Apis.Drive.v2.Data.File>>>();

      ChildrenResource.ListRequest folderCommand = drive.Children.List(frimärken.Id);
      folderCommand.MaxResults = 1000;
      // main.ToolStripProgressBar.Maximum = orter.Items.Count;
      int counter = 0;
      List<Google.Apis.Drive.v2.Data.File> folders = new List<Google.Apis.Drive.v2.Data.File>();
      const string collectingHeading = "Found images for ";
      do
      {
        try
        {
          ChildList orter = folderCommand.Execute();
          foreach (var ort in orter.Items)
          {
            Google.Apis.Drive.v2.Data.File folder = drive.Files.Get(ort.Id).Execute();
            if (backgroundGoogleDrive.CancellationPending) return;
            if (folder.Kind != "drive#file") continue;
            if (folder.Title.StartsWith("New")) continue;
            backgroundGoogleDrive.ReportProgress(++counter, collectingHeading + folder.Title);
            folders.Add(folder);
          }
          folderCommand.PageToken = orter.NextPageToken;
        }
        catch (Exception e)
        {
          Console.WriteLine("An error occurred: " + e.Message);
          folderCommand.PageToken = null;
        }
      } while (!String.IsNullOrEmpty(folderCommand.PageToken)); 

      counter = 0;
      const string heading = "Downloading images for ";
      Thread.CurrentThread.CurrentCulture = new CultureInfo("sv-SE");
      foreach (var stampFolder in folders.OrderBy(p => p.Title))
      {
        var list = new List<Google.Apis.Drive.v2.Data.File>();
        if (backgroundGoogleDrive.CancellationPending) return;
        backgroundGoogleDrive.ReportProgress(++counter, heading + stampFolder.Title);
        var stampImageRequest = drive.Children.List(stampFolder.Id).Execute();
        foreach (var image in stampImageRequest.Items)
        {
          Google.Apis.Drive.v2.Data.File imageFile = drive.Files.Get(image.Id).Execute();
          list.Add(imageFile);
          //DownloadImage(drive, imageFile);
        }
        var keyvaluePair = new aboveTradera.DatabaseRowEntry.KeyValuePair<string, List<Google.Apis.Drive.v2.Data.File>>(stampFolder.Title.ToUpper(), list);
        images.Add(keyvaluePair);
      }
      if (backgroundGoogleDrive.CancellationPending) return;
      backgroundGoogleDrive.ReportProgress(100, "Analyzing...");

      // Let's do a check that I've correctly mark a stamp as my and that I've scanned the stamp.
      // I have all stamps marks with a "z" - link'em with the scanned image File descriptor.
      // Print a report of those images that's missing and those that's extra.

      // First we check that we have a image 4 all stamps we have logged as ours i.e. all "z"'d should have an image.
      string fileName = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

      using (TextWriter writer = System.IO.File.CreateText(fileName))
      {
        bool anything2report = false;
        foreach (var row in newDatabase.Rows)
        {
          if (row.Town == null) continue;
          foreach (DatabaseRowEntry entry in row.Entries)
          {
            if (entry.IsOwned)
            {
              String cancelletion = DatabaseRow.Cancellation(entry.Start);
              try
              {
                foreach(var image in images.Find(s => s.Key == row.Town).Value.FindAll(t => t.Title.StartsWith(cancelletion))){
                  entry.Images.Add(new aboveTradera.DatabaseRowEntry.KeyValuePair<string, string>(image.Id, image.DownloadUrl));
                }
              }
              catch (Exception)
              {
                anything2report = true;
                writer.WriteLine("Missing image {0} ({1})", row.Town, cancelletion);
              }
            }
          }
        }
        // Then we check that we don't have an image that is not checked with a "z"
        foreach (var image in images)
        {
          foreach (var file in image.Value)
          {
            foreach (var row in newDatabase.Rows.FindAll(s => s.Town == image.Key))
            {
              try
              {
                var entry = row.Entries.Find(s => DatabaseRow.Cancellation(file.Title).StartsWith(DatabaseRow.Cancellation(s.Start)));
                if (entry == null) throw new Exception();
                if (!entry.IsOwned)
                {
                  entry.ExtraImages.Add(new aboveTradera.DatabaseRowEntry.KeyValuePair<string, string>(file.Id, file.DownloadUrl));
                  throw new Exception();
                }
              }
              catch (Exception)
              {
                anything2report = true;
                writer.WriteLine("Stamp not marked as owned {0} ({1})", row.Town, file.Title);
              }
            }
          }
        }
        if (anything2report)
        {
          Process.Start("notepad.exe", fileName);
        }
      }
      newDatabase.Save();
      if (backgroundGoogleDrive.CancellationPending) return;
      backgroundGoogleDrive.ReportProgress(0, "");
      database = newDatabase;
    }