File size: 4,459 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import config from '@automattic/calypso-config';
import { useI18n } from '@wordpress/react-i18n';
import { useLayoutEffect, useState } from 'react';
import { useDispatch } from 'calypso/state';
import { recordTracksEvent } from 'calypso/state/analytics/actions';
import { postLoginRequest } from 'calypso/state/login/utils';
import { infoNotice, errorNotice } from 'calypso/state/notices/actions';
import {
	GitHubInstallationData,
	useGithubInstallationsQuery,
} from '../../use-github-installations-query';
import { openPopup } from '../../utils/open-popup';
import { useSaveGitHubCredentialsMutation } from './use-save-github-credentials-mutation';

interface UseLiveInstallationsParameters {
	initialInstallationId?: number;
}

const NOTICE_ID = 'github-app-install-notice';

const AUTHORIZATION_URL =
	'https://public-api.wordpress.com/wpcom/v2/hosting/github/app-authorize?ux_mode=popup';

const INSTALLATION_URL = 'https://public-api.wordpress.com/wpcom/v2/hosting/github/app-install';

export const useLiveInstallations = ( {
	initialInstallationId,
}: UseLiveInstallationsParameters = {} ) => {
	const {
		data: installations,
		error: installationsError,
		refetch,
		isLoading: isLoadingInstallations,
	} = useGithubInstallationsQuery();
	const dispatch = useDispatch();
	const { __ } = useI18n();
	const { saveGitHubCredentials } = useSaveGitHubCredentialsMutation();
	const [ installation, setInstallation ] = useState< GitHubInstallationData >();

	useLayoutEffect( () => {
		if ( installation || ! installations || installations.length === 0 ) {
			return;
		}

		if ( initialInstallationId ) {
			const preselectedInstallation = installations.find(
				( installation ) => installation.external_id === initialInstallationId
			);

			if ( preselectedInstallation ) {
				setInstallation( preselectedInstallation );
				return;
			}
		}

		setInstallation( installations[ 0 ] );
	}, [ installations, installation, initialInstallationId ] );

	const authorizeApp = async ( { code }: { code: string } ) => {
		const response = await postLoginRequest( 'exchange-social-auth-code', {
			service: 'github',
			auth_code: code,
			client_id: config( 'wpcom_signup_id' ),
			client_secret: config( 'wpcom_signup_key' ),
		} );

		if ( response.body.data.access_token ) {
			await saveGitHubCredentials( { accessToken: response.body.data.access_token } );
		}
	};

	const onNewInstallationRequest = () => {
		dispatch( recordTracksEvent( 'calypso_hosting_github_app_open_auth_popup_requested' ) );

		const openedPopup = openPopup( {
			url: installationsError?.name === 'UnauthorizedError' ? AUTHORIZATION_URL : INSTALLATION_URL,
			onMessage: async ( data, popup ) => {
				if ( 'github-app-authorized' === data.type ) {
					dispatch( recordTracksEvent( 'calypso_hosting_github_app_authorised_success' ) );

					try {
						await authorizeApp( { code: data.code } );
						refetch();
						popup.location = INSTALLATION_URL;
					} catch {
						popup.close();

						dispatch( recordTracksEvent( 'calypso_hosting_github_app_install_failed' ) );

						dispatch(
							errorNotice( __( 'Failed to authorize GitHub. Please try again.' ), {
								duration: 5000,
							} )
						);
					}
				}

				if ( 'github-app-installed' === data.type ) {
					popup.close();

					const { installationId } = data as { installationId?: number };

					dispatch(
						recordTracksEvent( 'calypso_hosting_github_app_install_success', {
							is_org_request: ! installationId,
						} )
					);

					if ( ! installationId ) {
						dispatch(
							infoNotice(
								__(
									'Installation requested. You will be able to see it once approved by the organization owner.'
								),
								{
									id: NOTICE_ID,
									showDismiss: true,
								}
							)
						);
					}

					const { data: newInstallations } = await refetch();

					const newInstallation = newInstallations?.find(
						( installation ) => installation.external_id === installationId
					);

					if ( newInstallation ) {
						setInstallation( newInstallation );
					}
				}
			},
		} );

		if ( ! openedPopup ) {
			dispatch( recordTracksEvent( 'calypso_hosting_github_app_install_failed' ) );

			dispatch(
				errorNotice( __( 'Failed to authorize GitHub. Please try again.' ), {
					duration: 5000,
				} )
			);
		}
	};

	return {
		installation,
		onNewInstallationRequest,
		setInstallation,
		installations: installations ?? [],
		isLoadingInstallations,
	};
};