File size: 2,217 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
import { parse } from 'csv-parse/sync';
import { stringify } from 'csv-stringify/sync';
import fs from 'fs-extra';

const getLocale = ( lang ) => {
	if ( lang === 'en' ) {
		return 'en_US';
	}

	if ( lang.length === 2 ) {
		return `${ lang }_${ lang.toUpperCase() }`;
	}

	return lang.replace( '-', '_' );
};

const productsCountMap = {};
const csvFileContent = await fs.readFile( './top-100-searches.csv', {
	encoding: 'utf-8',
} );
const records = parse( csvFileContent, {
	columns: true,
	skip_empty_lines: true,
} );

for ( const record of records ) {
	const wporgResponse = await fetch(
		'https://api.wordpress.org/plugins/info/1.2?' +
			new URLSearchParams( {
				action: 'query_plugins',
				'request[page]': 1,
				'request[per_page]': 24,
				'request[search]': record.search_term,
				'request[locale]': getLocale( record.language ),
			} )
	);

	const wpcomResponse = await fetch(
		'https://public-api.wordpress.com/wpcom/v2/marketplace/products?' +
			new URLSearchParams( {
				type: 'all',
				_envelope: 1,
				q: record.search_term,
			} )
	);

	const wporgData = await wporgResponse.json();
	const wpcomData = await wpcomResponse.json();

	const wpcomPlugins = Object.values( wpcomData.body.results );
	const wporgPlugins = Object.values( wporgData.plugins );

	const plugins = [ ...wpcomPlugins, ...wporgPlugins ].slice( 0, 6 ); // show top 6 plugins

	console.log(
		`fetched plugins for ${ record.search_term }: locale - ${ getLocale(
			record.language
		) } results - wpcom: ${ wpcomPlugins.length } | wporg: ${ wporgPlugins.length }`
	);

	plugins.forEach( ( plugin ) => {
		productsCountMap[ plugin.slug ] = {
			count: productsCountMap[ plugin.slug ]
				? productsCountMap[ plugin.slug ].count + parseInt( record.count )
				: parseInt( record.count ),
		};
	} );
}

const results = Object.keys( productsCountMap )
	.map( ( slug ) => ( {
		product: slug,
		count: productsCountMap[ slug ].count,
		locales: productsCountMap[ slug ].locales,
	} ) )
	.sort( ( a, b ) => a.count - b.count )
	.reverse()
	.slice( 0, 250 ); // limit to 250 records

await fs.outputFile(
	'results/top-products.csv',
	stringify( results, { columns: [ { key: 'product' }, { key: 'count' } ], header: true } )
);