/
GoogleExcelService.cs
222 lines (187 loc) · 7.79 KB
/
GoogleExcelService.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
using Google.Apis.Services;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using GoogleExcel.Models;
using HttpHelper;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GoogleExcel
{
public class GoogleExcelService
{
private struct AuthorizeResponseModel
{
[JsonProperty("access_token")]
public string AccessToken;
[JsonProperty("token_type")]
public string TokenType;
[JsonProperty("expires_in")]
public int ExpiresIn;
}
private static async Task<string> authorizePost(string assertion)
{
Dictionary<string, string> form = new Dictionary<string, string>();
form.Add("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
form.Add("assertion", assertion);
HttpHelper.Model.ResponseModel resp = await HttpRequest.New()
.SetForm(form)
.To(TOKEN_URL)
.Post();
return resp.Content;
}
private const string JWT_HEADER = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9";
private const string TOKEN_URL = "https://www.googleapis.com/oauth2/v4/token";
private SheetsService _service;
private string _accessToken;
private string _privateKey;
private ClaimsModel _claims;
public GoogleExcelService(string applicationName, string email, Scope scope, string privateKey, int expires = 3600)
: this(applicationName, privateKey, new ClaimsModel(email, scope, expires))
{ }
public GoogleExcelService(string applicationName, string privateKey, ClaimsModel claims)
{
Init(applicationName, privateKey, claims);
}
/// <summary>
/// use google json file to init
/// </summary>
/// <param name="applicationName"></param>
/// <param name="fileName"></param>
/// <param name="scope"></param>
/// <param name="expires"></param>
public GoogleExcelService(string applicationName, string fileName, Scope scope, int expires = 3600)
{
GoogleJsonSecret fileData = FileUtil.JsonFile<GoogleJsonSecret>(fileName);
string email = fileData.ClientEmail;
Init(applicationName, fileData.PrivateKey, new ClaimsModel(email, scope, expires));
}
public void Init(string applicationName, string privateKey, ClaimsModel claims)
{
_privateKey = privateKey;
SetClaims(claims);
// Create Google Sheets API service.
_service = new SheetsService(
new BaseClientService.Initializer()
{
ApplicationName = applicationName
}
);
}
public void SetClaims(ClaimsModel claims)
{
_claims = claims;
}
public async Task FormatUpdate(string spreadsheetId, RangePosition range, CellFormat userEnteredFormat)
{
//get sheet id by sheet name
int sheetId = await getSheetID(spreadsheetId, range.TableName);
//define cell color
BatchUpdateSpreadsheetRequest bussr = new BatchUpdateSpreadsheetRequest();
//create the update request for cells from the first row
Request updateCellsRequest = new Request()
{
RepeatCell = new RepeatCellRequest()
{
Range = range.GetGridRange(sheetId),
Cell = new CellData()
{
UserEnteredFormat = userEnteredFormat
},
Fields = "UserEnteredFormat(BackgroundColor,TextFormat)"
}
};
bussr.Requests = new List<Request>();
bussr.Requests.Add(updateCellsRequest);
SpreadsheetsResource.BatchUpdateRequest bur = _service.Spreadsheets.BatchUpdate(bussr, spreadsheetId);
await autoAuthorize(bur);
}
public async Task Update(string spreadsheetId, UpdateRange updateRange)
{
string rangeStr = updateRange.Range.GetStr();
ValueRange targetRange = new ValueRange();
targetRange.Values = updateRange.Data;
targetRange.MajorDimension = "ROWS";
SpreadsheetsResource.ValuesResource.UpdateRequest request =
_service.Spreadsheets.Values.Update(targetRange, spreadsheetId, rangeStr);
request.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
await autoAuthorize(request);
}
public async Task BatchUpdate(string spreadsheetId, IEnumerable<UpdateRange> updateDatas)
{
BatchUpdateValuesRequest body = new BatchUpdateValuesRequest();
body.Data = updateDatas.Select(d => new ValueRange
{
Range = d.Range.GetStr(),
Values = d.Data,
MajorDimension = "ROWS"
}).ToList();
body.ValueInputOption = "USER_ENTERED";
SpreadsheetsResource.ValuesResource.BatchUpdateRequest request =
_service.Spreadsheets.Values.BatchUpdate(body, spreadsheetId);
await autoAuthorize(request);
}
public async Task<IList<IList<object>>> Get(string spreadsheetId, RangePosition range)
{
string rangeStr = range.GetStr();
SpreadsheetsResource.ValuesResource.GetRequest request =
_service.Spreadsheets.Values.Get(spreadsheetId, rangeStr);
ValueRange response = await autoAuthorize(request);
return response.Values;
}
private async Task authorize()
{
string jsonStr = JsonConvert.SerializeObject(_claims);
string jwtClaimSet = jsonStr.Base64();
string assertion = $"{JWT_HEADER}.{jwtClaimSet}";
byte[] shaSignature = ConvertUtil.Sha256WithRSA(assertion, _privateKey);
string jwtSignature = shaSignature.Base64();
assertion += "." + jwtSignature;
string responseStr = await authorizePost(assertion);
AuthorizeResponseModel response = JsonConvert.DeserializeObject<AuthorizeResponseModel>(responseStr);
_accessToken = response.AccessToken;
}
private async Task<int> getSheetID(string spreadsheetId, string tableName)
{
//get sheet id by sheet name
SpreadsheetsResource.GetRequest requs = _service.Spreadsheets.Get(spreadsheetId);
Spreadsheet spr = await autoAuthorize(requs);
if (spr == null)
{
throw new Exception("找不到此ID的表");
}
Sheet sh = spr.Sheets.Where(s => s.Properties.Title == tableName).FirstOrDefault();
return (int)sh.Properties.SheetId;
}
private bool isUnauthorize(Exception e)
{
return e.Message.Contains("[403]");
}
private async Task<responseModel> autoAuthorize<responseModel>(SheetsBaseServiceRequest<responseModel> reqes)
{
bool hasRetried = false;
while (true)
{
try
{
reqes.AccessToken = _accessToken;
return await reqes.ExecuteAsync();
}
catch (Exception e)
{
if (!hasRetried && isUnauthorize(e))
{
await authorize();
hasRetried = true;
}
else
{
throw e;
}
}
}
}
}
}