-
Notifications
You must be signed in to change notification settings - Fork 0
/
photosApi.ts
124 lines (103 loc) · 2.7 KB
/
photosApi.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
import { OAuth2Client } from "google-auth-library";
import axios from "axios";
interface MediaMetadata {
creationTime: string;
width: string;
height: string;
photo?: {
cameraMake: string;
cameraModel: string;
focalLength: number;
apertureFNumber: number;
isoEquivalent: number;
exposureTime: string;
};
video?: {
fps: number;
status: string;
};
}
interface ContributorInfo {
profilePictureBaseUrl: string;
displayName: string;
}
interface MediaItem {
id: string;
productUrl: string;
baseUrl: string;
mimeType: string;
mediaMetadata: MediaMetadata;
contributorInfo: ContributorInfo;
filename: string;
}
interface ListMediaItemsResponse {
mediaItems: MediaItem[];
nextPageToken: string;
}
const DEFAULT_PAGE_SIZE = 50;
export async function searchMediaItemsPage(
oauth2Client: OAuth2Client,
albumId: string,
pageSize: number = DEFAULT_PAGE_SIZE,
pageToken?: string
): Promise<ListMediaItemsResponse> {
const url = "https://photoslibrary.googleapis.com/v1/mediaItems:search";
const response = await axios.post(url, {
albumId,
pageSize,
pageToken,
},
{
headers: {
Authorization: `Bearer ${oauth2Client.credentials.access_token}`,
"Content-Type": "application/json",
},
});
return response.data;
}
export async function* enumerateAlbumMediaItems(
oauth2Client: OAuth2Client,
albumId: string,
pageSize: number = DEFAULT_PAGE_SIZE,
skip?: number
) {
let pageToken;
let resultsCount = 0;
do {
const response = await searchMediaItemsPage(oauth2Client, albumId, pageSize, pageToken);
if (skip && resultsCount < skip) {
resultsCount += response.mediaItems.length;
pageToken = response.nextPageToken;
console.log(`Skipping ${resultsCount}/${skip} media items...`);
continue;
}
if (!response.mediaItems) {
return;
}
for (const mediaItem of response.mediaItems) {
yield mediaItem;
resultsCount++;
}
console.log('Fetched', resultsCount, 'media items');
pageToken = response.nextPageToken;
} while (pageToken);
}
export async function getOrCreateAlbum(oauth2Client: OAuth2Client, name: string) {
const config = {
headers: {
Authorization: `Bearer ${oauth2Client.credentials.access_token}`,
"Content-Type": "application/json",
},
};
const { data: { albums } } = await axios.get('https://photoslibrary.googleapis.com/v1/albums', config);
let album = albums.find((album: any) => album.title === name);
if (!album) {
const { data } = await axios.post(
'https://photoslibrary.googleapis.com/v1/albums',
{ album: { title: name } },
config
);
album = data;
}
return album.id;
}