File size: 1,890 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
const fetch = require( 'electron-fetch' ).default;
const log = require( '../../lib/logger' )( 'desktop:analytics' );

function buildQuerystring( group, name ) {
	let uriComponent = '';

	if ( 'object' === typeof group ) {
		for ( const key in group ) {
			checkLength( key, group[ key ] );
			uriComponent += '&x_' + encodeURIComponent( key ) + '=' + encodeURIComponent( group[ key ] );
		}
	} else {
		checkLength( group, name );
		uriComponent = '&x_' + encodeURIComponent( group ) + '=' + encodeURIComponent( name );
	}

	return uriComponent;
}

async function bumpStat( group, name ) {
	if ( 'object' === typeof group ) {
		log.info( 'Bumping stats ', group );
	} else {
		log.info(
			'Bumping stat,' + `${ group ? ' group: ' + group : '' }` + `${ name ? ' name: ' + name : '' }`
		);
	}

	const uriComponent = buildQuerystring( group, name );
	const url = `https://pixel.wp.com/g.gif?v=wpcom-no-pv${ uriComponent }&t=${ Math.random() }`;

	const resp = await fetch( url );
	if ( resp.status !== 200 ) {
		log.warn( `Analytics ping failed (${ resp.status }): `, resp.statusText );
	}
}

// Get analytics conform version string
// version string needs to be formatted without `.`
// Replaces `beta` with `b` as stats key and value is limited to 32 chars
function sanitizeVersion( version ) {
	return version.replace( /\./g, '-' ).replace( 'beta', 'b' );
}

const PLATFORMS = {
	darwin: 'osx',
	win32: 'windows',
	linux: 'linux',
};

// Get analytics conform platform string
function getPlatform( platform ) {
	return PLATFORMS[ platform ];
}

// Stats key and value is limited to 32 chars
function checkLength( key, val ) {
	if ( key.length > 32 ) {
		log.warn( `bumpStat() key '${ key }' is longer than 32 chars` );
	}
	if ( val.length > 32 ) {
		log.warn( `bumpStat() value '${ val }' is longer than 32 chars` );
	}
}

module.exports = {
	bumpStat,
	sanitizeVersion,
	getPlatform,
};