File size: 2,057 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
import { includes } from 'lodash';
import { JETPACK_REMOTE_INSTALL } from 'calypso/state/action-types';
import { recordTracksEvent, withAnalytics } from 'calypso/state/analytics/actions';
import { registerHandlers } from 'calypso/state/data-layer/handler-registry';
import { http } from 'calypso/state/data-layer/wpcom-http/actions';
import { dispatchRequest } from 'calypso/state/data-layer/wpcom-http/utils';
import {
	jetpackRemoteInstallComplete,
	jetpackRemoteInstallUpdateError,
} from 'calypso/state/jetpack-remote-install/actions';

export const JETPACK_REMOTE_INSTALL_RETRIES = 3;

export const installJetpackPlugin = ( action ) =>
	http(
		{
			method: 'POST',
			path: '/jetpack-install/' + encodeURIComponent( action.url ),
			query: {
				user: action.user,
				password: action.password,
			},
		},
		action
	);

export const handleSuccess = ( { url } ) => {
	const logToTracks = withAnalytics(
		recordTracksEvent( 'calypso_jpc_remoteinstall_api_success', {
			url,
		} )
	);

	return logToTracks( jetpackRemoteInstallComplete( url ) );
};

export const handleError = ( action, error ) => {
	const {
		url,
		user,
		password,
		meta: { dataLayer },
	} = action;
	const { retryCount = 0 } = dataLayer;

	const logToTracks = withAnalytics(
		recordTracksEvent( 'calypso_jpc_remoteinstall_api_fail', {
			url,
			error: error.error,
			error_message: error.message,
			status: error.status,
		} )
	);

	if ( includes( error.message, 'timed out' ) ) {
		if ( retryCount < JETPACK_REMOTE_INSTALL_RETRIES ) {
			return {
				type: JETPACK_REMOTE_INSTALL,
				url,
				user,
				password,
				meta: {
					dataLayer: {
						retryCount: retryCount + 1,
						trackRequest: true,
					},
				},
			};
		}
	}

	return logToTracks( jetpackRemoteInstallUpdateError( url, error.error, error.message ) );
};

registerHandlers( 'state/data-layer/wpcom/jetpack-install/index.js', {
	[ JETPACK_REMOTE_INSTALL ]: [
		dispatchRequest( {
			fetch: installJetpackPlugin,
			onSuccess: handleSuccess,
			onError: handleError,
		} ),
	],
} );

export default {};