Как добавить событие календаря Google с триггером базы данных Firebase - PullRequest
0 голосов
/ 11 мая 2018

Я хочу добавить событие календаря пользователя с телефона Android с триггером Firebase, но у меня проблема с Google Oauth2.

На стороне Android я использую Firebase + Google Auth с областью календаря: "https://www.googleapis.com/auth/calendar"

На пожарной базе у меня есть этот код:

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import * as google from 'googleapis';

admin.initializeApp();
export const addEvent = functions.database
    .ref('users/{user}/calendarEvents/{eventId}')
    .onCreate((snapshot, context) => {
        const data = snapshot.val()
        const calendar = google.google.calendar('v3');
        const authClient = getOauthClient(data.token);
        return new Promise((resolve, reject) => {
            calendar.events.insert({
                auth: authClient,
                calendarId: 'primary',
                resource: getCalendarEvent(data),
            }, function (err, event) {
                if (err) {
                    console.error(err);
                    reject.apply(err);
                }
                else {
                    resolve.apply(event.data);
                }
            });
        }).then(() => snapshot.ref.remove());
    });

function getCalendarEvent(data) {
    const start = new Date()
    start.setTime(data.date)
    const end = new Date()
    end.setTime(data.date + (1000 * 60 * 60))
    return {
        'id': String(data.id),
        'summary': data.summary,
        'description': data.description,
        'start': {
            'dateTime': start.toISOString()
        },
        'end': {
            'dateTime': end.toISOString()
        },
        'attendees': [
            { 'email': data.email }
        ],
        'reminders': {
            'useDefault': false,
            'overrides': [
                { 'method': 'email', 'minutes': 24 * 60 },
                { 'method': 'popup', 'minutes': 10 }
            ]
        }
    }
}

function getOauthClient(accessToken) {
    const oauth = new google.google.auth.OAuth2();
    oauth.setCredentials({ access_token: accessToken });
    return oauth;
}

В журналах Firebase я получил эту ошибку:

No access, refresh token or API key is set.
at OAuth2Client.<anonymous> (/user_code/node_modules/googleapis/node_modules/google-auth-library/build/src/auth/oauth2client.js:336:35)
at step (/user_code/node_modules/googleapis/node_modules/google-auth-library/build/src/auth/oauth2client.js:57:23)
at Object.next (/user_code/node_modules/googleapis/node_modules/google-auth-library/build/src/auth/oauth2client.js:38:53)
at /user_code/node_modules/googleapis/node_modules/google-auth-library/build/src/auth/oauth2client.js:32:71
at __awaiter (/user_code/node_modules/googleapis/node_modules/google-auth-library/build/src/auth/oauth2client.js:28:12)
at OAuth2Client.getRequestMetadataAsync (/user_code/node_modules/googleapis/node_modules/google-auth-library/build/src/auth/oauth2client.js:329:16)
at OAuth2Client.<anonymous> (/user_code/node_modules/googleapis/node_modules/google-auth-library/build/src/auth/oauth2client.js:441:51)
at step (/user_code/node_modules/googleapis/node_modules/google-auth-library/build/src/auth/oauth2client.js:57:23)
at Object.next (/user_code/node_modules/googleapis/node_modules/google-auth-library/build/src/auth/oauth2client.js:38:53)
at /user_code/node_modules/googleapis/node_modules/google-auth-library/build/src/auth/oauth2client.js:32:71

Какой токен я должен отправить от клиента? Как я должен использовать его с Google Calendar API?

На андроиде я использовал это для получения токена:

token = GoogleSignIn.getLastSignedInAccount(application).serverAuthCode

И

token = GoogleSignIn.getLastSignedInAccount(application).idToken

А

 token = Tasks.await(FirebaseAuth.currentUser.getIdToken(true)) }.token

Я также пробовал запрос функции из Можно ли добавить события в календарь Google пользователя (через мой сервер) после какого-либо события в моем приложении?

Но я получил

The API returned an error: Error: No refresh token is set.
...