googleapis#google TypeScript Examples
The following examples show how to use
googleapis#google.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GoogleAuth.ts From Bridge with GNU General Public License v3.0 | 6 votes |
/**
* Use this.token as the credentials for this.oAuth2Client, and make the google library use this authentication.
* Assumes these have already been defined correctly.
*/
private authenticateWithToken() {
this.oAuth2Client.setCredentials(this.token)
google.options({ auth: this.oAuth2Client })
this.hasAuthenticated = true
}
Example #2
Source File: Google.ts From tinyhouse with MIT License | 6 votes |
async function logInHandler(code: string) {
const { tokens } = await auth.getToken(code);
auth.setCredentials(tokens);
const { data } = await google.people({ version: "v1", auth }).people.get({
resourceName: "people/me",
personFields: "emailAddresses,names,photos",
});
return { user: data };
}
Example #3
Source File: drive.ts From metasearch with Apache License 2.0 | 6 votes |
engine: Engine = {
id: "drive",
init: ({ credentials, token }: { credentials: string; token: string }) => {
// https://github.com/googleapis/google-api-nodejs-client/tree/62f8193#oauth2-client
const {
web: { client_id, client_secret },
} = JSON.parse(fs.readFileSync(credentials, "utf8"));
auth = new google.auth.OAuth2(client_id, client_secret);
auth.setCredentials({ refresh_token: token });
},
name: "Google Drive",
search: async q => {
if (!auth) {
throw Error("Engine not initialized");
}
const drive = google.drive({ version: "v3", auth });
const data = await drive.files.list({
// Searches "Visible to anyone in..."
// https://developers.google.com/drive/api/v3/search-files#search_the_corpora
corpora: "domain",
fields: "files(description,id,kind,mimeType,modifiedTime,name,owners)",
q: `fullText contains '${q.replace(/'/, "\\'")}'`,
spaces: "drive",
});
return (
data.data.files?.map(f => {
const { name, urlFragment } = getMimeInfo(f.mimeType);
return {
modified: f.modifiedTime ? getUnixTime(f.modifiedTime) : undefined,
snippet: f.description ?? `${name} by ${f.owners?.[0].displayName}`,
title: f.name ?? "Drive file",
url: `https://docs.google.com/${urlFragment}/d/${f.id}/edit`,
};
}) ?? []
);
},
}
Example #4
Source File: index.ts From backend with MIT License | 6 votes |
async function queryEvents(query: googleCalendar.Params$Resource$Events$List): Promise<googleCalendar.Schema$Event[]> {
const calender: googleCalendar.Calendar = google.calendar({
version: 'v3',
auth: process.env.GOOGLE_KEY
});
const result = await calender.events.list(query);
return result.data.items;
}
Example #5
Source File: youtube.ts From companion-module-youtube-live with MIT License | 6 votes |
/**
* Create new YouTube API wrapper
* @param auth Authorized Google OAuth2 client
* @param maxBroadcasts Limit on how many broadcasts to fetch
*/
constructor(auth: OAuth2Client, maxBroadcasts: number) {
this.ApiClient = google.youtube({
version: 'v3',
auth: auth,
});
this.MaxBroadcasts = maxBroadcasts;
}
Example #6
Source File: auth.service.ts From NextJS-NestJS-GraphQL-Starter with MIT License | 6 votes |
oauth2Client = new google.auth.OAuth2(
GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET,
/*
* This is where Google will redirect the user after they
* give permission to your application
*/
`${CORS_ORIGIN}/auth/google`,
)
Example #7
Source File: analytics.ts From thvu-blog with MIT License | 6 votes |
handlers = async (_: NextApiRequest, res: NextApiResponse<Analytic>) => {
const startDate = "2021-01-01";
const auth = new google.auth.GoogleAuth({
credentials: {
client_email: process.env.GOOGLE_CLIENT_EMAIL,
client_id: process.env.GOOGLE_CLIENT_ID,
private_key: process.env.GOOGLE_PRIVATE_KEY,
},
scopes: ["https://www.googleapis.com/auth/analytics.readonly"],
});
const analytics = google.analytics({
auth,
version: "v3",
});
const response = await analytics.data.ga.get({
"end-date": "today",
ids: "ga:251017969",
metrics: "ga:pageviews",
"start-date": startDate,
});
res.setHeader("Cache-Control", "public, s-maxage=60, stale-while-revalidate=30");
return res.status(200).json({
pageViews: response.data.totalsForAllResults?.["ga:pageviews"],
});
}
Example #8
Source File: server.ts From mui-toolpad with MIT License | 6 votes |
/**
* Create an OAuth2 client based on the configuration
*/
function createOAuthClient(): OAuth2Client {
if (!config.googleSheetsClientId) {
throw new Error('Google Sheets: Missing client ID "TOOLPAD_DATASOURCE_GOOGLESHEETS_CLIENT_ID"');
}
if (!config.googleSheetsClientSecret) {
throw new Error(
'Google Sheets: Missing client secret "TOOLPAD_DATASOURCE_GOOGLESHEETS_CLIENT_SECRET"',
);
}
if (!config.externalUrl) {
throw new Error('Google Sheets: Missing redirect URL "TOOLPAD_EXTERNAL_URL"');
}
return new google.auth.OAuth2(
config.googleSheetsClientId,
config.googleSheetsClientSecret,
new URL('/api/dataSources/googleSheets/auth/callback', config.externalUrl).href,
);
}
Example #9
Source File: gcal.ts From tams-club-cal with MIT License | 6 votes |
/**
* Updates a Google Calendar entry given the event object and the id
*
* @param data Event data to update on the calendar
* @param id Google Calendar event ID to update
*/
export async function updateCalendar(data: EventObject, id: string): Promise<void> {
console.log(id);
const start = data.allDay
? { date: dayjs(data.start).format('YYYY-MM-DD') }
: { dateTime: new Date(data.start).toISOString() };
const end = data.allDay
? { date: dayjs(data.start).format('YYYY-MM-DD') }
: { dateTime: new Date(data.end).toISOString() };
await google.calendar('v3').events.update({
calendarId: process.env.CALENDAR_ID,
eventId: id,
requestBody: {
start,
end,
summary: `${data.name} (${data.club})`,
description: data.description,
},
});
}
Example #10
Source File: GoogleAuth.ts From Bridge with GNU General Public License v3.0 | 6 votes |
/**
* Attempts to get Bridge's client info from the server.
* @returns true if this.clientID and this.clientSecret have been set, and false if that failed.
*/
private async getOAuth2Client() {
if (this.oAuth2Client != null) {
return true
} else {
return new Promise<boolean>(resolve => {
needle.request(
'get',
serverURL + `/api/data/client`, null, (err, response) => {
if (err) {
devLog('Could not authenticate because client info could not be retrieved from the server:', serializeError(err))
resolve(false)
} else {
this.oAuth2Client = new google.auth.OAuth2(response.body.CLIENT_ID, response.body.CLIENT_SECRET, REDIRECT_URI)
resolve(true)
}
})
})
}
}
Example #11
Source File: auth.ts From drive-proxy with Apache License 2.0 | 6 votes |
getAuth = async (): Promise<
InstanceType<typeof google.auth.JWT>
> => {
if (!process.env.GOOGLE_PRIVATE_KEY) {
dotenv.config();
}
if (
!cachedJWTClient.jwtClient ||
Date.now() - cachedJWTClient.created.getTime() > 60000
) {
console.log('[AUTH] Refreshing JWT Client');
const privatekey = JSON.parse(
Buffer.from(process.env.GOOGLE_PRIVATE_KEY, 'base64').toString('ascii'),
);
const jwtClient = new google.auth.JWT(
privatekey.client_email,
null,
privatekey.private_key,
['https://www.googleapis.com/auth/drive'],
);
await jwtClient.authorize();
cachedJWTClient.created = new Date();
cachedJWTClient.jwtClient = jwtClient;
}
google.options({
auth: cachedJWTClient.jwtClient,
});
return cachedJWTClient.jwtClient;
}
Example #12
Source File: .sample.ts From ts-google-drive with MIT License | 6 votes |
async function uploadAndDownload() {
const folderId = "";
const filename = "./icon.png";
const newFile = await tsGoogleDrive.upload(filename, {parent: folderId});
const downloadBuffer = await newFile.download();
// of if you want stream
const drive = google.drive({version: "v3", auth: newFile.client});
const file = await drive.files.get({
fileId: newFile.id,
alt: 'media'
}, {responseType: "stream"});
file.data.on("data", data => {
// stream data
});
file.data.on("end", () => {
// stream end
});
// or use pipe
const writeStream = fs.createWriteStream('./output.png');
file.data.pipe(writeStream);
}
Example #13
Source File: cache.ts From drive-proxy with Apache License 2.0 | 6 votes |
(async (): Promise<void> => {
await getAuth();
let startPageToken = (await google.drive('v3').changes.getStartPageToken())
.data.startPageToken;
setInterval(async () => {
google.drive('v3').files;
await getAuth();
const { data } = await google.drive('v3').changes.list({
pageToken: startPageToken,
});
startPageToken = data.newStartPageToken;
invalidate(
data.changes.reduce((a, c) => {
a[c.fileId] = c.file as any;
return a;
}, {} as any),
);
}, 15000);
})();
Example #14
Source File: google.ts From majsoul-api with MIT License | 6 votes |
constructor(
public readonly spreadsheetId: string,
oAuth2Client: OAuth2Client,
) {
this.sheets = google.sheets({version: 'v4', auth: oAuth2Client});
this.buffer.Chunks$.subscribe((chunk) => {
this.uploadTask = this.uploadTask
.then(async () => {
await this.sheets.spreadsheets.batchUpdate({
spreadsheetId: this.spreadsheetId,
requestBody: {
requests: chunk
}
});
})
.catch();
});
}
Example #15
Source File: sheets.ts From Corsace with MIT License | 6 votes |
async function getPoolData (pool: "openMappool" | "closedMappool", round: string) {
let data;
try {
data = (await sheetsClient.spreadsheets.values.get({
spreadsheetId: config.google.sheets[pool],
range: `'${round}'!A2:P`,
})).data.values as any[][];
} catch (e) {
if (e) data = undefined;
}
return data;
}
Example #16
Source File: YoutubeUploadService.ts From podcast-maker with MIT License | 6 votes |
private async uploadThumbnail(
auth: OAuth2Client,
thumnailPath: string,
videoId: string,
) {
const youtube = google.youtube({ version: 'v3' });
log(`Uploading thumbnail`, 'YoutubeUploadService');
await youtube.thumbnails.set({
auth,
videoId,
media: {
body: fs.createReadStream(thumnailPath),
},
});
}
Example #17
Source File: driveHandler.ts From frames with Mozilla Public License 2.0 | 6 votes |
constructor(token: GoogleToken | null, credentials: GoogleCred | null, deleteAndRename: boolean) {
if (token && credentials) {
const {client_secret, client_id, redirect_uris} = credentials;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
oAuth2Client.setCredentials(token);
const auth = oAuth2Client;
this.drive = google.drive({version: 'v3', auth});
this.drive2 = google.drive({version: 'v2', auth});
this.deleteAndRename = deleteAndRename;
} else
throw new Error('Incorrect google config')
}
Example #18
Source File: MailToJsonService.ts From podcast-maker with MIT License | 6 votes |
private async getAccessToken(): Promise<OAuth2Client> {
log('Getting access token', 'MailToJsonService');
return new Promise(resolve => {
const { OAuth2 } = google.auth;
const oauth2client = new OAuth2(
this.clientId,
this.clientSecret,
this.redirectUrl,
);
oauth2client.setCredentials({
refresh_token: this.refreshToken,
});
oauth2client.refreshAccessToken(async (err, token: any) => {
if (err || !token) {
error(
`Failed at refreshing Google token \n${JSON.stringify(
err,
)}`,
'MailToJsonService',
);
return;
}
oauth2client.setCredentials(token);
resolve(oauth2client);
});
});
}
Example #19
Source File: main.ts From internal-app-sharing-action with Apache License 2.0 | 6 votes |
async function main(): Promise<any> {
getAndValidateInputs();
setGoogleCredentials();
// Acquire an auth client, and bind it to all future calls
const authClient = await auth.getClient();
google.options({
auth: authClient,
});
// TODO: does this block need to be tested?
let res: any; // TODO: add a type to this
if(apkPath) {
res = await androidpublisher.internalappsharingartifacts.uploadapk({
packageName: packageName,
media: {
mimeType: 'application/octet-stream',
body: fs.createReadStream(apkPath)
}
})
} else if (aabPath) {
res = await androidpublisher.internalappsharingartifacts.uploadbundle({
packageName: packageName,
media: {
mimeType: 'application/octet-stream',
body: fs.createReadStream(aabPath)
}
})
}
return res.data;
}
Example #20
Source File: YoutubeFetcher.ts From skychat with MIT License | 5 votes |
constructor() {
// Youtube API object
this.youtube = google.youtube({version: 'v3', auth: Config.YOUTUBE_API_KEY});
}
Example #21
Source File: main.ts From internal-app-sharing-action with Apache License 2.0 | 5 votes |
auth = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/androidpublisher']
})
Example #22
Source File: gcal.ts From tams-club-cal with MIT License | 5 votes |
/**
* Updates the event on the recurring calendar, lengthening or shortening the event if needed
*
* @param data New event data
* @param id ID of the calendar event to update
* @param isLonger True if event repeats for longer; will return list ids
*/
export async function updateRecurringCalendar(
data: EventObject,
id: string,
isLonger: boolean = false
): Promise<calendar_v3.Schema$Event[]> {
// Calculate start time
const start = data.allDay
? { date: dayjs(data.start).format('YYYY-MM-DD'), timeZone: 'Etc/UTC' }
: { dateTime: new Date(data.start).toISOString(), timeZone: 'Etc/UTC' };
// Calculate end time
const end = data.allDay
? { date: dayjs(data.start).format('YYYY-MM-DD'), timeZone: 'Etc/UTC' }
: { dateTime: new Date(data.end).toISOString(), timeZone: 'Etc/UTC' };
// Calculate repeating and end status
const freq = data.repeats === RepeatingStatus.WEEKLY ? 'WEEKLY' : 'MONTHLY';
const until = dayjs(data.repeatsUntil).startOf('day').subtract(1, 'second').format('YYYYMMDD');
await google.calendar('v3').events.update({
calendarId: process.env.CALENDAR_ID,
eventId: id,
requestBody: {
start,
end,
summary: `${data.name} (${data.club})`,
description: data.description,
recurrence: [`RRULE:FREQ=${freq};UNTIL=${until}`],
},
});
if (!isLonger) return null;
// Get the list of all repeating events
const res = await google.calendar('v3').events.instances({
calendarId: process.env.CALENDAR_ID,
eventId: id,
});
// Return those items lol
return res.data.items;
}
Example #23
Source File: Email.ts From expresso with MIT License | 5 votes |
/**
* Set Mail Config
* @returns
*/
private readonly setMailConfig = (): nodemailer.SentMessageInfo => {
const configTransport: nodemailer.SentMessageInfo = {
service: MAIL_DRIVER,
auth: {
user: '',
},
}
// Use Google OAuth
if (MAIL_AUTH_TYPE === 'OAuth2') {
const oauth2Client = new google.auth.OAuth2(
OAUTH_CLIENT_ID,
OAUTH_CLIENT_SECRET,
OAUTH_REDIRECT_URL
)
oauth2Client.setCredentials({
refresh_token: OAUTH_REFRESH_TOKEN,
})
const accessToken = async (): Promise<Headers> => {
const result = await oauth2Client.getRequestHeaders()
return result
}
configTransport.auth.user = MAIL_USERNAME
configTransport.auth.type = MAIL_AUTH_TYPE
configTransport.auth.clientId = OAUTH_CLIENT_ID
configTransport.auth.clientSecret = OAUTH_CLIENT_SECRET
configTransport.auth.refreshToken = OAUTH_REFRESH_TOKEN
configTransport.auth.accessToken = accessToken()
} else if (isMailgunAPI) {
// SMPT with Mailgun API
configTransport.auth.api_key = MAILGUN_API_KEY
configTransport.auth.domain = MAILGUN_DOMAIN
} else {
// SMTP Default
configTransport.host = MAIL_HOST
configTransport.port = MAIL_PORT
configTransport.auth.user = MAIL_USERNAME
configTransport.auth.pass = MAIL_PASSWORD
}
return configTransport
}
Example #24
Source File: Google.ts From tinyhouse with MIT License | 5 votes |
auth = new google.auth.OAuth2(
process.env.G_CLIENT_ID,
process.env.G_CLIENT_SECRET,
`${process.env.PUBLIC_URL}/login`
)
Example #25
Source File: google.authentication.ts From relate with GNU General Public License v3.0 | 5 votes |
protected readonly oAuth2Client = new google.auth.OAuth2({
clientId: this.options.clientId,
clientSecret: this.options.clientSecret,
redirectUri: `${this.env.httpOrigin}${VALIDATION_ENDPOINT}`,
});
Example #26
Source File: gcpMachineTypes.ts From cloud-pricing-api with Apache License 2.0 | 5 votes |
async function scrape(): Promise<void> {
const auth = new google.auth.GoogleAuth({
keyFile: config.gcpKeyFile,
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
const compute = google.compute({
version: 'v1',
auth,
});
const regionResp = await compute.regions.list({
project: config.gcpProject,
});
const zoneResp = await compute.zones.list({
project: config.gcpProject,
});
const zones = (zoneResp.data.items || []).map((i) => i.name || '');
const products: Product[] = [];
for (const region of regionResp.data.items || []) {
const regionName = region.name || '';
const regionZones = zones.filter((z) => z.startsWith(regionName));
const machineTypeResp = await compute.machineTypes.list({
project: config.gcpProject,
zone: regionZones[0],
});
for (const machineType of machineTypeResp.data.items || []) {
const name = machineType.name || '';
config.logger.info(`Adding machine type ${name} for ${regionName}`);
const product: Product = {
productHash: '',
sku: `generated-${name}`,
vendorName: 'gcp',
region: regionName,
service: 'Compute Engine',
productFamily: 'Compute Instance',
attributes: {
machineType: name,
},
prices: [],
};
product.productHash = generateProductHash(product);
const onDemandPrice = await createPrice(
product,
machineType,
'on_demand'
);
if (onDemandPrice) {
product.prices.push(onDemandPrice);
}
const preemptiblePrice = await createPrice(
product,
machineType,
'preemptible'
);
if (preemptiblePrice) {
product.prices.push(preemptiblePrice);
}
products.push(product);
}
}
await upsertProducts(products);
}
Example #27
Source File: oauth.ts From metasearch with Apache License 2.0 | 5 votes |
oauth2Client = new google.auth.OAuth2(
client_id,
client_secret,
"http://localhost:3001/",
)
Example #28
Source File: gcal.ts From tams-club-cal with MIT License | 5 votes |
// All the following functions will operate on REPEATING events
// This is a hellhole, so hold on tight kids!
// Here's the documentation, if you prefer to read through lines and lines of nonsense:
// https://developers.google.com/calendar/api/guides/recurringevents
/**
* Create a calendar event for the repeating event
*/
export async function addRecurringToCalendar(data: EventObject): Promise<string[]> {
try {
// Calculate start time
const start = data.allDay
? { date: dayjs(data.start).format('YYYY-MM-DD'), timeZone: 'Etc/UTC' }
: { dateTime: new Date(data.start).toISOString(), timeZone: 'Etc/UTC' };
// Calculate end time
const end = data.allDay
? { date: dayjs(data.start).format('YYYY-MM-DD'), timeZone: 'Etc/UTC' }
: { dateTime: new Date(data.end).toISOString(), timeZone: 'Etc/UTC' };
// Calculate repeating and end status
const freq = data.repeats === RepeatingStatus.WEEKLY ? 'WEEKLY' : 'MONTHLY';
const until = dayjs(data.repeatsUntil).startOf('day').subtract(1, 'second').format('YYYYMMDD');
// Insert the original repeating event into the calendar
const insertRes = await google.calendar('v3').events.insert({
calendarId: process.env.CALENDAR_ID,
requestBody: {
start,
end,
summary: `${data.name} (${data.club})`,
description: data.description,
recurrence: [`RRULE:FREQ=${freq};UNTIL=${until}`],
},
});
// Get the list of all repeating events
const res = await google.calendar('v3').events.instances({
calendarId: process.env.CALENDAR_ID,
eventId: insertRes.data.id,
});
// Map IDs to string then replace the first ID with the recurringEventId
const ids = res.data.items.map((e) => e.id);
ids[0] = res.data.items[0].recurringEventId;
return ids;
} catch (error) {
throw error;
}
}
Example #29
Source File: FileDownloader.ts From Bridge with GNU General Public License v3.0 | 5 votes |
drive = google.drive('v3')