-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Program.cs
247 lines (224 loc) · 9.23 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.ComponentModel;
namespace BulkEditGoogleDrive
{
/// <typeparam name="Scopes">Array of string containing the scopes the program should use.</typeparam>
/// <typeparam name="ApplicationName">The name of the program.</typeparam>
/// <typeparam name="Service">The Google Service instance to connect to reference Google.</typeparam>
class Program
{
static string[] Scopes = {
DriveService.Scope.Drive,
DriveService.Scope.DriveAppdata,
DriveService.Scope.DriveFile,
};
static DriveService Service;
static Dictionary<string, string> Extensions = new Dictionary<string, string>()
{
{"gdo", "application/vnd.google-apps.document"}, {"gsh", "application/vnd.google-apps.spreadsheet"},
{"gsl", "application/vnd.google-apps.presentation"}, {"gfo", "application/vnd.google-apps.form"}
};
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("╔═════════════════════╗");
Console.WriteLine("║ BulkEditGoogleDrive ║");
Console.WriteLine("╚═════════════════════╝");
Console.ResetColor();
Console.WriteLine(
"To know how to format the file, read the description in "
+ "https://github.com/JoseDeFreitas/BulkEditGoogleDrive."
);
Console.Write("Do you want to update the information of the file? (y/n): ");
char decision = 'n';
try
{
decision = Convert.ToChar(Console.ReadLine());
}
catch (Exception e)
{
if (e is ArgumentNullException || e is FormatException)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("The answer should be \"y\" or \"n\".");
Console.ResetColor();
Environment.Exit(1);
}
}
if (decision == 'y')
{
try
{
Process.Start("notepad.exe", "files.txt");
}
catch (Win32Exception)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("The notepad application could not be found.");
Console.ResetColor();
Environment.Exit(1);
}
Environment.Exit(0);
}
// Read data from the "files.txt" file
string[] fileNames = {};
try
{
fileNames = System.IO.File.ReadAllLines("files.txt");
}
catch (FileNotFoundException)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("The file \"files.txt\" was not found.");
Console.ResetColor();
Environment.Exit(1);
}
catch (IOException)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("An IO error ocurred when opening the file.");
Console.ResetColor();
Environment.Exit(1);
}
// Connect to Google Drive
try
{
UserCredential credential;
using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.FromStream(stream).Secrets,
Scopes,
"admin",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
Service = new DriveService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "BulkEditGoogleDrive"
});
}
catch (FileNotFoundException)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"The \"credentials.json\" file was not found.");
Console.ResetColor();
Environment.Exit(1);
}
// Define names and options
string folderName = "";
char numberedNames = 'n';
try
{
folderName = fileNames[0].Split('|')[0];
numberedNames = Convert.ToChar(fileNames[0].Split('|')[1]);
}
catch (Exception e)
{
if (e is ArgumentNullException || e is FormatException || e is ArgumentOutOfRangeException)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("The answer should be \"y\" or \"n\".");
Console.ResetColor();
Environment.Exit(1);
}
}
// Create files in Google Drive
int createdFilesCount = 0;
int skippedFilesCount = 0;
try
{
// Check if folder already exists
string folderId = "";
var folderRequest = Service.Files.List();
folderRequest.Q = $"name='{folderName}' and mimeType='application/vnd.google-apps.folder'";
var folderResult = folderRequest.Execute();
if (folderResult.Files.Count == 0)
{
var folderMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = folderName,
MimeType = "application/vnd.google-apps.folder"
};
var request = Service.Files.Create(folderMetadata).Execute();
folderId = request.Id;
}
else
folderId = folderResult.Files[0].Id;
// Create files inside folder
for (int i = 1; i < fileNames.Length; i++)
{
string fileName = "";
try
{
fileName = fileNames[i].Split('.')[0];
}
catch (ArgumentOutOfRangeException)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("The format of the \"files.txt\" file is wrong.");
Console.ResetColor();
Environment.Exit(1);
}
if (numberedNames == 'y')
fileName = $"{i}- {fileName}";
string fileType = "";
try
{
fileType = Extensions[fileNames[i].Split('.')[1]];
}
catch (ArgumentOutOfRangeException)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("The format of the \"files.txt\" file is wrong.");
Console.ResetColor();
Environment.Exit(1);
}
// Check if file already exists
var fileRequest = Service.Files.List();
fileRequest.Q = $"name='{fileName}' and mimeType='{fileType}'";
var fileResult = fileRequest.Execute();
if (fileResult.Files.Count == 0)
{
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = fileName,
Parents = new List<string>
{
folderId
},
MimeType = fileType
};
Service.Files.Create(fileMetadata).Execute();
createdFilesCount++;
}
else
skippedFilesCount++;
}
}
catch (Exception)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("The folder or the files couldn't be created.");
Console.ResetColor();
Environment.Exit(1);
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(
$"{createdFilesCount} files were created successfully.\n"
+ $"{skippedFilesCount} files were skipped because they already existed."
);
Console.ResetColor();
}
}
}