This repository has been archived by the owner on May 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.ts
330 lines (291 loc) · 8.54 KB
/
index.ts
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/**
* This file is part of the node-appstore-connect distribution.
* Copyright (c) e.GO Digital GmbH, Aachen, Germany (https://www.e-go-digital.com/)
*
* node-appstore-connect is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, version 3.
*
* node-appstore-connect is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import got from 'got';
import * as jwt from 'jsonwebtoken';
import * as moment from 'moment';
import { gunzip, isNil, readCSV } from './utils';
/**
* Options for a 'Client' instance.
*/
export interface ClientOptions {
/**
* The API key.
*/
'apiKey': string;
/**
* The number in sec, the token will expire. Default: 1200
*/
'expriresIn'?: number;
/**
* The ID of the issuer.
*/
'issuerId': string;
/**
* The private key.
*/
'privateKey': PrivateKey;
}
/**
* The frequence of a report.
*/
export enum DownloadSalesReportFrequency {
/**
* Daily
*/
Daily = 'DAILY',
/**
* Monthly
*/
Monthly = 'MONTHLY',
/**
* Weekly
*/
Weekly = 'WEEKLY',
/**
* Yearly
*/
Yearly = 'YEARLY',
}
/**
* A filter for a 'SalesReportRow' item.
*
* @param {SalesReportRow} row The current item / row.
*
* @return {boolean|PromiseLike<boolean>} The result, that indicates if filter criteria matches or not.
*/
export type SalesReportRowFilter = (row: SalesReportRow) => boolean | PromiseLike<boolean>;
/**
* Options for 'Client.downloadSalesReportSummary()' method.
*/
export interface DownloadSalesReportSummaryOptions {
/**
* The custom report date.
*/
'date'?: moment.MomentInput;
/**
* A filter for a sales report row.
*/
'filter'?: SalesReportRowFilter;
/**
* The frequency. Default: Weekly.
*/
'frequency'?: DownloadSalesReportFrequency;
/**
* The ID of the vendor.
*/
'vendorId': string;
}
/**
* Options for 'Client.getAppDownloads()' method.
*/
export interface GetAppDownloadsOptions extends DownloadSalesReportSummaryOptions {
}
/**
* Result of a 'Client.getAppDownloads()' method call.
*/
export interface GetAppDownloadsResult {
/**
* The list of apps.
*/
'apps': { [appId: string]: GetAppDownloadsAppItem };
}
/**
* An app item of 'GetAppDownloadsResult.apps'.
*/
export interface GetAppDownloadsAppItem {
/**
* The number of downloads.
*/
'downloads': number;
}
/**
* A value for an App Store Connect private key.
*/
export type PrivateKey = string | Buffer;
/**
* A row of a sales report CSV.
*/
export interface SalesReportRow {
'Apple Identifier': string;
'Begin Date': string;
'CMB': string;
'Category': string;
'Client': string;
'Country Code': string;
'Currency of Proceeds': string;
'Customer Currency': string;
'Customer Price': string;
'Developer Proceeds': string;
'Developer': string;
'Device': string;
'End Date': string;
'Order Type': string;
'Parent Identifier': string;
'Period': string;
'Preserved Pricing': string;
'Proceeds Reason': string;
'Product Type Identifier': string;
'Promo Code': string;
'Provider Country': string;
'Provider': string;
'SKU': string;
'Subscription': string;
'Supported Platforms': string;
'Title': string;
'Units': string;
'Version': string;
}
/**
* A client for the App Store Connect API.
*/
export class Client {
private _bearerToken: string | undefined;
/**
* Initializes a new instance of that class.
*
* @param {ClientOptions} options The options.
*/
public constructor(
public readonly options: ClientOptions
) { }
private _getBearerToken(): string {
if (isNil(this._bearerToken)) {
const NOW = Math.round((new Date()).getTime() / 1000);
let expriresIn = this.options.expriresIn;
if (isNaN(expriresIn)) {
expriresIn = 1200;
}
const PAYLOAD = {
'iss': this.options.issuerId,
'exp': NOW + expriresIn,
'aud': 'appstoreconnect-v1'
};
const SIGN_OPTS: jwt.SignOptions = {
'algorithm': 'ES256',
'header': {
'alg': 'ES256',
'kid': this.options.apiKey,
'typ': 'JWT'
}
};
this._bearerToken = jwt.sign(
PAYLOAD,
this.options.privateKey,
SIGN_OPTS
);
}
return this._bearerToken;
}
/**
* Downloads a summary of a sales report.
*
* @param {DownloadSalesReportSummaryOptions} opts The options.
*
* @return {Promise<SalesReportRow[]>} The promise with the rows.
*/
public async downloadSalesReportSummary(opts: DownloadSalesReportSummaryOptions): Promise<SalesReportRow[]> {
let reportDate = opts.date;
if (isNil(reportDate)) {
reportDate = moment();
}
if (!moment.isMoment(reportDate)) {
reportDate = moment(reportDate);
}
let frequency = opts.frequency;
if (isNil(frequency)) {
frequency = DownloadSalesReportFrequency.Weekly;
}
let filterReportDate: string;
switch (frequency) {
case DownloadSalesReportFrequency.Weekly:
reportDate = moment(reportDate.toDate()).endOf('isoWeek');
filterReportDate = reportDate.format('YYYY-MM-DD');
break;
case DownloadSalesReportFrequency.Monthly:
filterReportDate = reportDate.format('YYYY-MM');
break;
case DownloadSalesReportFrequency.Yearly:
filterReportDate = reportDate.format('YYYY');
break;
default:
filterReportDate = reportDate.format('YYYY-MM-DD');
break;
}
const TOKEN = this._getBearerToken();
const RESPONSE = await got.get(`https://api.appstoreconnect.apple.com/v1/salesReports`, {
'headers': {
'Authorization': 'Bearer ' + TOKEN,
'Accept': 'application/a-gzip'
},
'responseType': 'buffer',
'searchParams': {
'filter[frequency]': frequency,
'filter[reportDate]': filterReportDate,
'filter[reportType]': 'SALES',
'filter[reportSubType]': 'SUMMARY',
'filter[vendorNumber]': opts.vendorId,
},
'throwHttpErrors': false,
});
if (200 !== RESPONSE.statusCode) {
if (404 === RESPONSE.statusCode) {
return [];
}
throw new Error(`Unexpected Response: [${
RESPONSE.statusCode
}] '${RESPONSE.body}'`);
}
const ZIPPED_CSV = RESPONSE.body;
const ALL_ROWS = await readCSV<SalesReportRow>(
await gunzip(ZIPPED_CSV, 'utf8')
);
const ROWS: SalesReportRow[] = [];
const FILTER: SalesReportRowFilter = isNil(opts.filter) ?
() => true : opts.filter;
for (const R of ALL_ROWS) {
if (await Promise.resolve(FILTER(R))) {
ROWS.push(R);
}
}
return ROWS;
}
/**
* Returns a summary of app downloads.
*
* @param {GetAppDownloadsOptions} opts The options.
*
* @return {Promise<GetAppDownloadsResult>} The promise with the result.
*/
public async getAppDownloads(opts: GetAppDownloadsOptions): Promise<GetAppDownloadsResult> {
const CSV = await this.downloadSalesReportSummary(opts);
const RESULT: GetAppDownloadsResult = {
apps: {},
};
for (const R of CSV) {
let item = RESULT.apps[R.SKU];
if (isNil(item)) {
RESULT.apps[R.SKU] = item = {
downloads: 0,
};
}
let units = parseInt(R.Units);
item.downloads += isNaN(units) ?
0 : units;
}
return RESULT;
}
}