extensionTipsService.ts 49.1 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6
import { localize } from 'vs/nls';
7
import { join, basename } from 'vs/base/common/path';
8
import { forEach } from 'vs/base/common/collections';
9
import { Disposable } from 'vs/base/common/lifecycle';
J
Johannes Rieken 已提交
10
import { match } from 'vs/base/common/glob';
11
import * as json from 'vs/base/common/json';
12
import { IExtensionManagementService, IExtensionGalleryService, EXTENSION_IDENTIFIER_PATTERN, InstallOperation, ILocalExtension } from 'vs/platform/extensionManagement/common/extensionManagement';
13
import { IExtensionTipsService, ExtensionRecommendationReason, IExtensionsConfigContent, RecommendationChangeNotification, IExtensionRecommendation, ExtensionRecommendationSource, IExtensionEnablementService, EnablementState } from 'vs/workbench/services/extensionManagement/common/extensionManagement';
J
Johannes Rieken 已提交
14
import { IModelService } from 'vs/editor/common/services/modelService';
A
Alex Dima 已提交
15
import { ITextModel } from 'vs/editor/common/model';
J
Johannes Rieken 已提交
16
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
17
import product from 'vs/platform/product/node/product';
18
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
19
import { ShowRecommendedExtensionsAction, InstallWorkspaceRecommendedExtensionsAction, InstallRecommendedExtensionAction } from 'vs/workbench/contrib/extensions/browser/extensionsActions';
20
import Severity from 'vs/base/common/severity';
21
import { IWorkspaceContextService, IWorkspaceFolder, IWorkspace, IWorkspaceFoldersChangeEvent, WorkbenchState } from 'vs/platform/workspace/common/workspace';
22
import { IFileService } from 'vs/platform/files/common/files';
23
import { IExtensionsConfiguration, ConfigurationKey, ShowRecommendationsOnlyOnDemandKey, IExtensionsViewlet, IExtensionsWorkbenchService, EXTENSIONS_CONFIG } from 'vs/workbench/contrib/extensions/common/extensions';
24
import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
25
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
26 27
import * as pfs from 'vs/base/node/pfs';
import * as os from 'os';
S
Sandeep Somavarapu 已提交
28
import { flatten, distinct, shuffle, coalesce } from 'vs/base/common/arrays';
29
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
30
import { guessMimeTypes, MIME_UNKNOWN } from 'vs/base/common/mime';
31
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
32
import { IRequestService, asJson } from 'vs/platform/request/common/request';
33
import { isNumber } from 'vs/base/common/types';
34
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
35
import { INotificationService } from 'vs/platform/notification/common/notification';
36
import { Emitter, Event } from 'vs/base/common/event';
37
import { assign } from 'vs/base/common/objects';
38
import { URI } from 'vs/base/common/uri';
39
import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
40
import { IExperimentService, ExperimentActionType, ExperimentState } from 'vs/workbench/contrib/experiments/common/experimentService';
41
import { CancellationToken } from 'vs/base/common/cancellation';
42
import { ExtensionType } from 'vs/platform/extensions/common/extensions';
B
Benjamin Pasero 已提交
43
import { extname } from 'vs/base/common/resources';
44 45
import { IExeBasedExtensionTip } from 'vs/platform/product/common/product';
import { timeout } from 'vs/base/common/async';
46
import { IWorkspaceStatsService } from 'vs/workbench/contrib/stats/common/workspaceStats';
47

48
const milliSecondsInADay = 1000 * 60 * 60 * 24;
49
const choiceNever = localize('neverShowAgain', "Don't Show Again");
50
const searchMarketplace = localize('searchMarketplace', "Search Marketplace");
51
const processedFileExtensions: string[] = [];
52

53 54 55 56 57
interface IDynamicWorkspaceRecommendations {
	remoteSet: string[];
	recommendations: string[];
}

58
function caseInsensitiveGet<T>(obj: { [key: string]: T }, key: string): T | undefined {
59 60 61
	if (!obj) {
		return undefined;
	}
62
	for (const _key in obj) {
63
		if (Object.hasOwnProperty.call(obj, _key) && _key.toLowerCase() === key.toLowerCase()) {
64 65 66 67 68 69
			return obj[_key];
		}
	}
	return undefined;
}

S
Sandeep Somavarapu 已提交
70
export class ExtensionTipsService extends Disposable implements IExtensionTipsService {
71

72
	_serviceBrand: any;
J
Johannes Rieken 已提交
73

S
Sandeep Somavarapu 已提交
74
	private _fileBasedRecommendations: { [id: string]: { recommendedTime: number, sources: ExtensionRecommendationSource[] }; } = Object.create(null);
75 76
	private _exeBasedRecommendations: { [id: string]: IExeBasedExtensionTip; } = Object.create(null);
	private _importantExeBasedRecommendations: { [id: string]: IExeBasedExtensionTip; } = Object.create(null);
77
	private _availableRecommendations: { [pattern: string]: string[] } = Object.create(null);
S
Sandeep Somavarapu 已提交
78
	private _allWorkspaceRecommendedExtensions: IExtensionRecommendation[] = [];
79
	private _dynamicWorkspaceRecommendations: string[] = [];
R
Ramya Rao 已提交
80
	private _experimentalRecommendations: { [id: string]: string } = Object.create(null);
81 82 83
	private _allIgnoredRecommendations: string[] = [];
	private _globallyIgnoredRecommendations: string[] = [];
	private _workspaceIgnoredRecommendations: string[] = [];
84
	private _extensionsRecommendationsUrl: string;
S
Sandeep Somavarapu 已提交
85
	public loadWorkspaceConfigPromise: Promise<void>;
86
	private proactiveRecommendationsFetched: boolean = false;
S
Sandeep Somavarapu 已提交
87

88
	private readonly _onRecommendationChange = this._register(new Emitter<RecommendationChangeNotification>());
89
	onRecommendationChange: Event<RecommendationChangeNotification> = this._onRecommendationChange.event;
90
	private sessionSeed: number;
91

92
	constructor(
93 94
		@IExtensionGalleryService private readonly _galleryService: IExtensionGalleryService,
		@IModelService private readonly _modelService: IModelService,
95 96
		@IStorageService private readonly storageService: IStorageService,
		@IExtensionManagementService private readonly extensionsService: IExtensionManagementService,
97
		@IExtensionEnablementService private readonly extensionEnablementService: IExtensionEnablementService,
98 99 100 101 102 103 104 105 106 107 108 109 110
		@IInstantiationService private readonly instantiationService: IInstantiationService,
		@IFileService private readonly fileService: IFileService,
		@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
		@IConfigurationService private readonly configurationService: IConfigurationService,
		@ITelemetryService private readonly telemetryService: ITelemetryService,
		@IEnvironmentService private readonly environmentService: IEnvironmentService,
		@IExtensionService private readonly extensionService: IExtensionService,
		@IRequestService private readonly requestService: IRequestService,
		@IViewletService private readonly viewletService: IViewletService,
		@INotificationService private readonly notificationService: INotificationService,
		@IExtensionManagementService private readonly extensionManagementService: IExtensionManagementService,
		@IExtensionsWorkbenchService private readonly extensionWorkbenchService: IExtensionsWorkbenchService,
		@IExperimentService private readonly experimentService: IExperimentService,
111
		@IWorkspaceStatsService private readonly workspaceStatsService: IWorkspaceStatsService
112
	) {
S
Sandeep Somavarapu 已提交
113 114
		super();

115
		if (!this.isEnabled()) {
116 117 118
			return;
		}

119 120 121
		if (product.extensionsGallery && product.extensionsGallery.recommendationsUrl) {
			this._extensionsRecommendationsUrl = product.extensionsGallery.recommendationsUrl;
		}
122

123 124
		this.sessionSeed = +new Date();

125 126 127
		let globallyIgnored = <string[]>JSON.parse(this.storageService.get('extensionsAssistant/ignored_recommendations', StorageScope.GLOBAL, '[]'));
		this._globallyIgnoredRecommendations = globallyIgnored.map(id => id.toLowerCase());

128 129 130
		this.fetchCachedDynamicWorkspaceRecommendations();
		this.fetchFileBasedRecommendations();
		this.fetchExperimentalRecommendations();
131
		if (!this.configurationService.getValue<boolean>(ShowRecommendationsOnlyOnDemandKey)) {
132 133 134
			this.fetchProactiveRecommendations(true);
		}

135 136
		this.loadWorkspaceConfigPromise = this.getWorkspaceRecommendations().then(() => {
			this.promptWorkspaceRecommendations();
137
			this._register(this._modelService.onModelAdded(this.promptFiletypeBasedRecommendations, this));
138 139 140
			this._modelService.getModels().forEach(model => this.promptFiletypeBasedRecommendations(model));
		});

S
Sandeep Somavarapu 已提交
141
		this._register(this.contextService.onDidChangeWorkspaceFolders(e => this.onWorkspaceFoldersChanged(e)));
142
		this._register(this.configurationService.onDidChangeConfiguration(e => {
143
			if (!this.proactiveRecommendationsFetched && !this.configurationService.getValue<boolean>(ShowRecommendationsOnlyOnDemandKey)) {
144 145 146
				this.fetchProactiveRecommendations();
			}
		}));
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
		this._register(this.extensionManagementService.onDidInstallExtension(e => {
			if (e.gallery && e.operation === InstallOperation.Install) {
				const extRecommendations = this.getAllRecommendationsWithReason() || {};
				const recommendationReason = extRecommendations[e.gallery.identifier.id.toLowerCase()];
				if (recommendationReason) {
					/* __GDPR__
						"extensionGallery:install:recommendations" : {
							"recommendationReason": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
							"${include}": [
								"${GalleryExtensionTelemetryData}"
							]
						}
					*/
					this.telemetryService.publicLog('extensionGallery:install:recommendations', assign(e.gallery.telemetryData, { recommendationReason: recommendationReason.reasonId }));
				}
			}
		}));
164 165
	}

166
	private isEnabled(): boolean {
167
		return this._galleryService.isEnabled() && !this.environmentService.extensionDevelopmentLocationURI;
168 169
	}

170 171 172
	getAllRecommendationsWithReason(): { [id: string]: { reasonId: ExtensionRecommendationReason, reasonText: string }; } {
		let output: { [id: string]: { reasonId: ExtensionRecommendationReason, reasonText: string }; } = Object.create(null);

173 174 175 176
		if (!this.proactiveRecommendationsFetched) {
			return output;
		}

R
Ramya Rao 已提交
177 178 179 180 181
		forEach(this._experimentalRecommendations, entry => output[entry.key.toLowerCase()] = {
			reasonId: ExtensionRecommendationReason.Experimental,
			reasonText: entry.value
		});

182 183
		if (this.contextService.getWorkspace().folders && this.contextService.getWorkspace().folders.length === 1) {
			const currentRepo = this.contextService.getWorkspace().folders[0].name;
184 185

			this._dynamicWorkspaceRecommendations.forEach(id => output[id.toLowerCase()] = {
186 187 188
				reasonId: ExtensionRecommendationReason.DynamicWorkspace,
				reasonText: localize('dynamicWorkspaceRecommendation', "This extension may interest you because it's popular among users of the {0} repository.", currentRepo)
			});
189
		}
190 191 192

		forEach(this._exeBasedRecommendations, entry => output[entry.key.toLowerCase()] = {
			reasonId: ExtensionRecommendationReason.Executable,
193
			reasonText: localize('exeBasedRecommendation', "This extension is recommended because you have {0} installed.", entry.value.friendlyName)
194 195
		});

196
		forEach(this._fileBasedRecommendations, entry => output[entry.key.toLowerCase()] = {
197 198 199 200
			reasonId: ExtensionRecommendationReason.File,
			reasonText: localize('fileBasedRecommendation', "This extension is recommended based on the files you recently opened.")
		});

S
Sandeep Somavarapu 已提交
201
		this._allWorkspaceRecommendedExtensions.forEach(({ extensionId }) => output[extensionId.toLowerCase()] = {
202 203 204 205
			reasonId: ExtensionRecommendationReason.Workspace,
			reasonText: localize('workspaceRecommendation', "This extension is recommended by users of the current workspace.")
		});

206 207 208
		for (const id of this._allIgnoredRecommendations) {
			delete output[id];
		}
209

210 211 212
		return output;
	}

213 214 215 216 217 218 219
	getAllIgnoredRecommendations(): { global: string[], workspace: string[] } {
		return {
			global: this._globallyIgnoredRecommendations,
			workspace: this._workspaceIgnoredRecommendations
		};
	}

220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
	toggleIgnoredRecommendation(extensionId: string, shouldIgnore: boolean) {
		const lowerId = extensionId.toLowerCase();
		if (shouldIgnore) {
			const reason = this.getAllRecommendationsWithReason()[lowerId];
			if (reason && reason.reasonId) {
				/* __GDPR__
					"extensionsRecommendations:ignoreRecommendation" : {
						"recommendationReason": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
						"extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }
					}
				*/
				this.telemetryService.publicLog('extensionsRecommendations:ignoreRecommendation', { id: extensionId, recommendationReason: reason.reasonId });
			}
		}

		this._globallyIgnoredRecommendations = shouldIgnore ?
			distinct([...this._globallyIgnoredRecommendations, lowerId].map(id => id.toLowerCase())) :
			this._globallyIgnoredRecommendations.filter(id => id !== lowerId);

		this.storageService.store('extensionsAssistant/ignored_recommendations', JSON.stringify(this._globallyIgnoredRecommendations), StorageScope.GLOBAL);
		this._allIgnoredRecommendations = distinct([...this._globallyIgnoredRecommendations, ...this._workspaceIgnoredRecommendations]);

		this._onRecommendationChange.fire({ extensionId: extensionId, isRecommended: !shouldIgnore });
	}

	getKeymapRecommendations(): IExtensionRecommendation[] {
		return (product.keymapExtensionTips || [])
			.filter(extensionId => this.isExtensionAllowedToBeRecommended(extensionId))
			.map(extensionId => (<IExtensionRecommendation>{ extensionId, sources: ['application'] }));
	}

	//#region workspaceRecommendations

S
Sandeep Somavarapu 已提交
253 254
	getWorkspaceRecommendations(): Promise<IExtensionRecommendation[]> {
		if (!this.isEnabled()) { return Promise.resolve([]); }
255 256
		return this.fetchWorkspaceRecommendations()
			.then(() => this._allWorkspaceRecommendedExtensions.filter(rec => this.isExtensionAllowedToBeRecommended(rec.extensionId)));
S
Merges  
Sandeep Somavarapu 已提交
257 258
	}

259 260 261
	/**
	 * Parse all extensions.json files, fetch workspace recommendations, filter out invalid and unwanted ones
	 */
S
Sandeep Somavarapu 已提交
262
	private fetchWorkspaceRecommendations(): Promise<void> {
S
Sandeep Somavarapu 已提交
263

R
Rob Lourens 已提交
264
		if (!this.isEnabled) { return Promise.resolve(undefined); }
S
Sandeep Somavarapu 已提交
265 266 267 268 269 270 271 272 273 274 275

		return this.fetchExtensionRecommendationContents()
			.then(result => this.validateExtensions(result.map(({ contents }) => contents))
				.then(({ invalidExtensions, message }) => {

					if (invalidExtensions.length > 0 && this.notificationService) {
						this.notificationService.warn(`The below ${invalidExtensions.length} extension(s) in workspace recommendations have issues:\n${message}`);
					}

					const seenUnWantedRecommendations: { [id: string]: boolean } = {};

276 277 278
					this._allWorkspaceRecommendedExtensions = [];
					this._workspaceIgnoredRecommendations = [];

S
Sandeep Somavarapu 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
					for (const contentsBySource of result) {
						if (contentsBySource.contents.unwantedRecommendations) {
							for (const r of contentsBySource.contents.unwantedRecommendations) {
								const unwantedRecommendation = r.toLowerCase();
								if (!seenUnWantedRecommendations[unwantedRecommendation] && invalidExtensions.indexOf(unwantedRecommendation) === -1) {
									this._workspaceIgnoredRecommendations.push(unwantedRecommendation);
									seenUnWantedRecommendations[unwantedRecommendation] = true;
								}
							}
						}

						if (contentsBySource.contents.recommendations) {
							for (const r of contentsBySource.contents.recommendations) {
								const extensionId = r.toLowerCase();
								if (invalidExtensions.indexOf(extensionId) === -1) {
294
									let recommendation = this._allWorkspaceRecommendedExtensions.filter(r => r.extensionId === extensionId)[0];
S
Sandeep Somavarapu 已提交
295 296
									if (!recommendation) {
										recommendation = { extensionId, sources: [] };
297
										this._allWorkspaceRecommendedExtensions.push(recommendation);
S
Sandeep Somavarapu 已提交
298 299 300 301 302 303 304 305 306 307 308 309
									}
									if (recommendation.sources.indexOf(contentsBySource.source) === -1) {
										recommendation.sources.push(contentsBySource.source);
									}
								}
							}
						}
					}
					this._allIgnoredRecommendations = distinct([...this._globallyIgnoredRecommendations, ...this._workspaceIgnoredRecommendations]);
				}));
	}

310 311 312
	/**
	 * Parse all extensions.json files, fetch workspace recommendations
	 */
S
Sandeep Somavarapu 已提交
313
	private fetchExtensionRecommendationContents(): Promise<{ contents: IExtensionsConfigContent, source: ExtensionRecommendationSource }[]> {
314
		const workspace = this.contextService.getWorkspace();
315
		return Promise.all<{ contents: IExtensionsConfigContent, source: ExtensionRecommendationSource } | null>([
S
Sandeep Somavarapu 已提交
316 317 318
			this.resolveWorkspaceExtensionConfig(workspace).then(contents => contents ? { contents, source: workspace } : null),
			...workspace.folders.map(workspaceFolder => this.resolveWorkspaceFolderExtensionConfig(workspaceFolder).then(contents => contents ? { contents, source: workspaceFolder } : null))
		]).then(contents => coalesce(contents));
319 320
	}

321 322 323
	/**
	 * Parse the extensions.json file for given workspace and return the recommendations
	 */
S
Sandeep Somavarapu 已提交
324
	private resolveWorkspaceExtensionConfig(workspace: IWorkspace): Promise<IExtensionsConfigContent | null> {
325
		if (!workspace.configuration) {
S
Sandeep Somavarapu 已提交
326
			return Promise.resolve(null);
327
		}
328

B
Benjamin Pasero 已提交
329 330
		return Promise.resolve(this.fileService.readFile(workspace.configuration)
			.then(content => <IExtensionsConfigContent>(json.parse(content.value.toString())['extensions']), err => null));
331 332
	}

333 334 335
	/**
	 * Parse the extensions.json files for given workspace folder and return the recommendations
	 */
S
Sandeep Somavarapu 已提交
336
	private resolveWorkspaceFolderExtensionConfig(workspaceFolder: IWorkspaceFolder): Promise<IExtensionsConfigContent | null> {
337
		const extensionsJsonUri = workspaceFolder.toResource(EXTENSIONS_CONFIG);
338

B
Benjamin Pasero 已提交
339
		return Promise.resolve(this.fileService.resolve(extensionsJsonUri)
B
Benjamin Pasero 已提交
340 341
			.then(() => this.fileService.readFile(extensionsJsonUri))
			.then(content => <IExtensionsConfigContent>json.parse(content.value.toString()), err => null));
342 343
	}

344 345 346
	/**
	 * Validate the extensions.json file contents using regex and querying the gallery
	 */
S
Sandeep Somavarapu 已提交
347
	private async validateExtensions(contents: IExtensionsConfigContent[]): Promise<{ invalidExtensions: string[], message: string }> {
S
Sandeep Somavarapu 已提交
348 349 350 351
		const extensionsContent: IExtensionsConfigContent = {
			recommendations: distinct(flatten(contents.map(content => content.recommendations || []))),
			unwantedRecommendations: distinct(flatten(contents.map(content => content.unwantedRecommendations || [])))
		};
352

353 354
		const regEx = new RegExp(EXTENSION_IDENTIFIER_PATTERN);

M
Matt Bierner 已提交
355
		const invalidExtensions: string[] = [];
S
Sandeep Somavarapu 已提交
356
		let message = '';
357

S
Sandeep Somavarapu 已提交
358
		const regexFilter = (ids: string[]) => {
359 360
			return ids.filter((element, position) => {
				if (ids.indexOf(element) !== position) {
361 362 363 364
					// This is a duplicate entry, it doesn't hurt anybody
					// but it shouldn't be sent in the gallery query
					return false;
				} else if (!regEx.test(element)) {
S
Sandeep Somavarapu 已提交
365 366
					invalidExtensions.push(element.toLowerCase());
					message += `${element} (bad format) Expected: <provider>.<name>\n`;
367 368 369 370
					return false;
				}
				return true;
			});
371 372
		};

S
Sandeep Somavarapu 已提交
373
		const filteredWanted = regexFilter(extensionsContent.recommendations || []).map(x => x.toLowerCase());
374

375 376
		if (filteredWanted.length) {
			try {
S
Sandeep Somavarapu 已提交
377
				let validRecommendations = (await this._galleryService.query({ names: filteredWanted, pageSize: filteredWanted.length }, CancellationToken.None)).firstPage
378
					.map(extension => extension.identifier.id.toLowerCase());
379

380 381 382 383 384 385 386 387 388 389
				if (validRecommendations.length !== filteredWanted.length) {
					filteredWanted.forEach(element => {
						if (validRecommendations.indexOf(element.toLowerCase()) === -1) {
							invalidExtensions.push(element.toLowerCase());
							message += `${element} (not found in marketplace)\n`;
						}
					});
				}
			} catch (e) {
				console.warn('Error querying extensions gallery', e);
390
			}
391 392
		}
		return { invalidExtensions, message };
393
	}
394

S
Sandeep Somavarapu 已提交
395 396
	private onWorkspaceFoldersChanged(event: IWorkspaceFoldersChangeEvent): void {
		if (event.added.length) {
397
			const oldWorkspaceRecommended = this._allWorkspaceRecommendedExtensions;
S
Sandeep Somavarapu 已提交
398 399 400 401
			this.getWorkspaceRecommendations()
				.then(currentWorkspaceRecommended => {
					// Suggest only if at least one of the newly added recommendations was not suggested before
					if (currentWorkspaceRecommended.some(current => oldWorkspaceRecommended.every(old => current.extensionId !== old.extensionId))) {
402
						this.promptWorkspaceRecommendations();
S
Sandeep Somavarapu 已提交
403 404
					}
				});
S
Sandeep Somavarapu 已提交
405
		}
406
		this._dynamicWorkspaceRecommendations = [];
S
Sandeep Somavarapu 已提交
407 408
	}

409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
	/**
	 * Prompt the user to install workspace recommendations if there are any not already installed
	 */
	private promptWorkspaceRecommendations(): void {
		const storageKey = 'extensionsAssistant/workspaceRecommendationsIgnore';
		const config = this.configurationService.getValue<IExtensionsConfiguration>(ConfigurationKey);
		const filteredRecs = this._allWorkspaceRecommendedExtensions.filter(rec => this.isExtensionAllowedToBeRecommended(rec.extensionId));

		if (filteredRecs.length === 0
			|| config.ignoreRecommendations
			|| config.showRecommendationsOnlyOnDemand
			|| this.storageService.getBoolean(storageKey, StorageScope.WORKSPACE, false)) {
			return;
		}

424
		this.extensionsService.getInstalled(ExtensionType.User).then(local => {
425
			local = local.filter(l => this.extensionEnablementService.getEnablementState(l) !== EnablementState.DisabledByExtensionKind); // Filter extensions disabled by kind
426
			const recommendations = filteredRecs.filter(({ extensionId }) => local.every(local => !areSameExtensions({ id: extensionId }, local.identifier)));
427 428

			if (!recommendations.length) {
R
Rob Lourens 已提交
429
				return Promise.resolve(undefined);
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
			}

			return new Promise<void>(c => {
				this.notificationService.prompt(
					Severity.Info,
					localize('workspaceRecommended', "This workspace has extension recommendations."),
					[{
						label: localize('installAll', "Install All"),
						run: () => {
							/* __GDPR__
							"extensionWorkspaceRecommendations:popup" : {
								"userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
							}
							*/
							this.telemetryService.publicLog('extensionWorkspaceRecommendations:popup', { userReaction: 'install' });

							const installAllAction = this.instantiationService.createInstance(InstallWorkspaceRecommendedExtensionsAction, InstallWorkspaceRecommendedExtensionsAction.ID, localize('installAll', "Install All"), recommendations);
							installAllAction.run();
							installAllAction.dispose();

R
Rob Lourens 已提交
450
							c(undefined);
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
						}
					}, {
						label: localize('showRecommendations', "Show Recommendations"),
						run: () => {
							/* __GDPR__
								"extensionWorkspaceRecommendations:popup" : {
									"userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
								}
							*/
							this.telemetryService.publicLog('extensionWorkspaceRecommendations:popup', { userReaction: 'show' });

							const showAction = this.instantiationService.createInstance(ShowRecommendedExtensionsAction, ShowRecommendedExtensionsAction.ID, localize('showRecommendations', "Show Recommendations"));
							showAction.run();
							showAction.dispose();

R
Rob Lourens 已提交
466
							c(undefined);
467 468 469 470 471 472 473 474 475 476 477 478 479
						}
					}, {
						label: choiceNever,
						isSecondary: true,
						run: () => {
							/* __GDPR__
								"extensionWorkspaceRecommendations:popup" : {
									"userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
								}
							*/
							this.telemetryService.publicLog('extensionWorkspaceRecommendations:popup', { userReaction: 'neverShowAgain' });
							this.storageService.store(storageKey, true, StorageScope.WORKSPACE);

R
Rob Lourens 已提交
480
							c(undefined);
481 482 483 484 485 486 487 488 489 490 491 492
						}
					}],
					{
						sticky: true,
						onCancel: () => {
							/* __GDPR__
								"extensionWorkspaceRecommendations:popup" : {
									"userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
								}
							*/
							this.telemetryService.publicLog('extensionWorkspaceRecommendations:popup', { userReaction: 'cancelled' });

R
Rob Lourens 已提交
493
							c(undefined);
494 495 496 497 498 499 500 501 502
						}
					}
				);
			});
		});
	}

	//#endregion

503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
	//#region important exe based extension

	private async promptForImportantExeBasedExtension(): Promise<boolean> {

		const storageKey = 'extensionsAssistant/workspaceRecommendationsIgnore';
		const config = this.configurationService.getValue<IExtensionsConfiguration>(ConfigurationKey);

		if (config.ignoreRecommendations
			|| config.showRecommendationsOnlyOnDemand
			|| this.storageService.getBoolean(storageKey, StorageScope.WORKSPACE, false)) {
			return false;
		}

		const installed = await this.extensionManagementService.getInstalled(ExtensionType.User);
		let recommendationsToSuggest = Object.keys(this._importantExeBasedRecommendations);
		recommendationsToSuggest = this.filterAllIgnoredInstalledAndNotAllowed(recommendationsToSuggest, installed);
		if (recommendationsToSuggest.length === 0) {
			return false;
		}

		const id = recommendationsToSuggest[0];
		const tip = this._importantExeBasedRecommendations[id];
		const message = localize('exeRecommended', "The '{0}' extension is recommended as you have {1} installed on your system.", tip.friendlyName!, tip.exeFriendlyName || basename(tip.windowsPath!));

		this.notificationService.prompt(Severity.Info, message,
			[{
				label: localize('install', 'Install'),
				run: () => {
					/* __GDPR__
					"exeExtensionRecommendations:popup" : {
						"userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
						"extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }
					}
					*/
					this.telemetryService.publicLog('exeExtensionRecommendations:popup', { userReaction: 'install', extensionId: name });
					this.instantiationService.createInstance(InstallRecommendedExtensionAction, id).run();
				}
			}, {
				label: localize('showRecommendations', "Show Recommendations"),
				run: () => {
					/* __GDPR__
						"exeExtensionRecommendations:popup" : {
							"userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
							"extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }
						}
					*/
					this.telemetryService.publicLog('exeExtensionRecommendations:popup', { userReaction: 'show', extensionId: name });

					const recommendationsAction = this.instantiationService.createInstance(ShowRecommendedExtensionsAction, ShowRecommendedExtensionsAction.ID, localize('showRecommendations', "Show Recommendations"));
					recommendationsAction.run();
					recommendationsAction.dispose();
				}
			}, {
				label: choiceNever,
				isSecondary: true,
				run: () => {
					this.addToImportantRecommendationsIgnore(id);
					/* __GDPR__
						"exeExtensionRecommendations:popup" : {
							"userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
							"extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }
						}
					*/
					this.telemetryService.publicLog('exeExtensionRecommendations:popup', { userReaction: 'neverShowAgain', extensionId: name });
					this.notificationService.prompt(
						Severity.Info,
						localize('ignoreExtensionRecommendations', "Do you want to ignore all extension recommendations?"),
						[{
							label: localize('ignoreAll', "Yes, Ignore All"),
							run: () => this.setIgnoreRecommendationsConfig(true)
						}, {
							label: localize('no', "No"),
							run: () => this.setIgnoreRecommendationsConfig(false)
						}]
					);
				}
			}],
			{
				sticky: true,
				onCancel: () => {
					/* __GDPR__
						"exeExtensionRecommendations:popup" : {
							"userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
							"extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }
						}
					*/
					this.telemetryService.publicLog('exeExtensionRecommendations:popup', { userReaction: 'cancelled', extensionId: name });
				}
			}
		);

		return true;
	}

597 598
	//#region fileBasedRecommendations

S
Sandeep Somavarapu 已提交
599
	getFileBasedRecommendations(): IExtensionRecommendation[] {
600 601 602 603 604 605 606 607 608
		return Object.keys(this._fileBasedRecommendations)
			.sort((a, b) => {
				if (this._fileBasedRecommendations[a].recommendedTime === this._fileBasedRecommendations[b].recommendedTime) {
					if (!product.extensionImportantTips || caseInsensitiveGet(product.extensionImportantTips, a)) {
						return -1;
					}
					if (caseInsensitiveGet(product.extensionImportantTips, b)) {
						return 1;
					}
609
				}
610 611 612 613
				return this._fileBasedRecommendations[a].recommendedTime > this._fileBasedRecommendations[b].recommendedTime ? -1 : 1;
			})
			.filter(extensionId => this.isExtensionAllowedToBeRecommended(extensionId))
			.map(extensionId => (<IExtensionRecommendation>{ extensionId, sources: this._fileBasedRecommendations[extensionId].sources }));
R
Ramya Achutha Rao 已提交
614
	}
615

616 617 618 619
	/**
	 * Parse all file based recommendations from product.extensionTips
	 * Retire existing recommendations if they are older than a week or are not part of product.extensionTips anymore
	 */
620
	private fetchFileBasedRecommendations() {
621
		const extensionTips = product.extensionTips;
622 623 624
		if (!extensionTips) {
			return;
		}
625

626 627 628
		// group ids by pattern, like {**/*.md} -> [ext.foo1, ext.bar2]
		this._availableRecommendations = Object.create(null);
		forEach(extensionTips, entry => {
A
Alex Dima 已提交
629
			let { key: id, value: pattern } = entry;
630 631 632 633 634
			let ids = this._availableRecommendations[pattern];
			if (!ids) {
				this._availableRecommendations[pattern] = [id.toLowerCase()];
			} else {
				ids.push(id.toLowerCase());
635
			}
636 637
		});

J
Joao Moreno 已提交
638
		forEach(product.extensionImportantTips, entry => {
A
Alex Dima 已提交
639
			let { key: id, value } = entry;
640 641 642 643 644 645
			const { pattern } = value;
			let ids = this._availableRecommendations[pattern];
			if (!ids) {
				this._availableRecommendations[pattern] = [id.toLowerCase()];
			} else {
				ids.push(id.toLowerCase());
J
Joao Moreno 已提交
646 647 648
			}
		});

649
		const allRecommendations: string[] = flatten((Object.keys(this._availableRecommendations).map(key => this._availableRecommendations[key])));
650 651 652 653 654 655

		// retrieve ids of previous recommendations
		const storedRecommendationsJson = JSON.parse(this.storageService.get('extensionsAssistant/recommendations', StorageScope.GLOBAL, '[]'));

		if (Array.isArray<string>(storedRecommendationsJson)) {
			for (let id of <string[]>storedRecommendationsJson) {
656
				if (allRecommendations.indexOf(id) > -1) {
S
Sandeep Somavarapu 已提交
657
					this._fileBasedRecommendations[id.toLowerCase()] = { recommendedTime: Date.now(), sources: ['cached'] };
658 659 660 661 662 663 664
				}
			}
		} else {
			const now = Date.now();
			forEach(storedRecommendationsJson, entry => {
				if (typeof entry.value === 'number') {
					const diff = (now - entry.value) / milliSecondsInADay;
665
					if (diff <= 7 && allRecommendations.indexOf(entry.key) > -1) {
S
Sandeep Somavarapu 已提交
666
						this._fileBasedRecommendations[entry.key.toLowerCase()] = { recommendedTime: entry.value, sources: ['cached'] };
667 668 669 670
					}
				}
			});
		}
671 672
	}

673 674 675 676
	/**
	 * Prompt the user to either install the recommended extension for the file type in the current editor model
	 * or prompt to search the marketplace if it has extensions that can support the file type
	 */
677 678
	private promptFiletypeBasedRecommendations(model: ITextModel): void {
		const uri = model.uri;
679
		if (!uri || !this.fileService.canHandleResource(uri)) {
J
Johannes Rieken 已提交
680
			return;
681 682
		}

B
Benjamin Pasero 已提交
683
		let fileExtension = extname(uri);
684 685 686 687 688 689 690
		if (fileExtension) {
			if (processedFileExtensions.indexOf(fileExtension) > -1) {
				return;
			}
			processedFileExtensions.push(fileExtension);
		}

S
Sandeep Somavarapu 已提交
691 692
		// re-schedule this bit of the operation to be off the critical path - in case glob-match is slow
		setImmediate(async () => {
S
Sandeep Somavarapu 已提交
693 694 695 696 697

			let recommendationsToSuggest: string[] = [];
			const now = Date.now();
			forEach(this._availableRecommendations, entry => {
				let { key: pattern, value: ids } = entry;
698
				if (match(pattern, model.uri.toString())) {
S
Sandeep Somavarapu 已提交
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
					for (let id of ids) {
						if (caseInsensitiveGet(product.extensionImportantTips, id)) {
							recommendationsToSuggest.push(id);
						}
						const filedBasedRecommendation = this._fileBasedRecommendations[id.toLowerCase()] || { recommendedTime: now, sources: [] };
						filedBasedRecommendation.recommendedTime = now;
						if (!filedBasedRecommendation.sources.some(s => s instanceof URI && s.toString() === model.uri.toString())) {
							filedBasedRecommendation.sources.push(model.uri);
						}
						this._fileBasedRecommendations[id.toLowerCase()] = filedBasedRecommendation;
					}
				}
			});

			this.storageService.store(
				'extensionsAssistant/recommendations',
715
				JSON.stringify(Object.keys(this._fileBasedRecommendations).reduce((result, key) => { result[key] = this._fileBasedRecommendations[key].recommendedTime; return result; }, {} as { [key: string]: any })),
S
Sandeep Somavarapu 已提交
716 717 718 719 720 721 722 723
				StorageScope.GLOBAL
			);

			const config = this.configurationService.getValue<IExtensionsConfiguration>(ConfigurationKey);
			if (config.ignoreRecommendations || config.showRecommendationsOnlyOnDemand) {
				return;
			}

S
Sandeep Somavarapu 已提交
724
			const installed = await this.extensionManagementService.getInstalled(ExtensionType.User);
S
Sandeep Somavarapu 已提交
725
			if (await this.promptRecommendedExtensionForFileType(recommendationsToSuggest, installed)) {
S
Sandeep Somavarapu 已提交
726 727
				return;
			}
J
Joao Moreno 已提交
728

S
Sandeep Somavarapu 已提交
729 730 731 732 733 734
			if (fileExtension) {
				fileExtension = fileExtension.substr(1); // Strip the dot
			}
			if (!fileExtension) {
				return;
			}
J
cleanup  
Joao Moreno 已提交
735

S
Sandeep Somavarapu 已提交
736
			await this.extensionService.whenInstalledExtensionsRegistered();
B
Benjamin Pasero 已提交
737
			const mimeTypes = guessMimeTypes(uri);
S
Sandeep Somavarapu 已提交
738
			if (mimeTypes.length !== 1 || mimeTypes[0] !== MIME_UNKNOWN) {
739 740 741
				return;
			}

S
Sandeep Somavarapu 已提交
742 743 744
			this.promptRecommendedExtensionForFileExtension(fileExtension, installed);
		});
	}
745

S
Sandeep Somavarapu 已提交
746
	private async promptRecommendedExtensionForFileType(recommendationsToSuggest: string[], installed: ILocalExtension[]): Promise<boolean> {
747

748
		recommendationsToSuggest = this.filterAllIgnoredInstalledAndNotAllowed(recommendationsToSuggest, installed);
S
Sandeep Somavarapu 已提交
749 750 751
		if (recommendationsToSuggest.length === 0) {
			return false;
		}
752

S
Sandeep Somavarapu 已提交
753 754 755 756 757
		const id = recommendationsToSuggest[0];
		const entry = caseInsensitiveGet(product.extensionImportantTips, id);
		if (!entry) {
			return false;
		}
758
		const name = entry.name;
S
Sandeep Somavarapu 已提交
759
		let message = localize('reallyRecommended2', "The '{0}' extension is recommended for this file type.", name);
760
		if (entry.isExtensionPack) {
S
Sandeep Somavarapu 已提交
761 762
			message = localize('reallyRecommendedExtensionPack', "The '{0}' extension pack is recommended for this file type.", name);
		}
763

S
Sandeep Somavarapu 已提交
764 765 766 767 768 769 770 771 772 773 774 775
		this.notificationService.prompt(Severity.Info, message,
			[{
				label: localize('install', 'Install'),
				run: () => {
					/* __GDPR__
					"extensionRecommendations:popup" : {
						"userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
						"extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }
					}
					*/
					this.telemetryService.publicLog('extensionRecommendations:popup', { userReaction: 'install', extensionId: name });
					this.instantiationService.createInstance(InstallRecommendedExtensionAction, id).run();
776
				}
S
Sandeep Somavarapu 已提交
777 778 779 780 781 782 783 784 785 786
			}, {
				label: localize('showRecommendations', "Show Recommendations"),
				run: () => {
					/* __GDPR__
						"extensionRecommendations:popup" : {
							"userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
							"extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }
						}
					*/
					this.telemetryService.publicLog('extensionRecommendations:popup', { userReaction: 'show', extensionId: name });
787

S
Sandeep Somavarapu 已提交
788 789 790
					const recommendationsAction = this.instantiationService.createInstance(ShowRecommendedExtensionsAction, ShowRecommendedExtensionsAction.ID, localize('showRecommendations', "Show Recommendations"));
					recommendationsAction.run();
					recommendationsAction.dispose();
791
				}
S
Sandeep Somavarapu 已提交
792 793 794 795
			}, {
				label: choiceNever,
				isSecondary: true,
				run: () => {
796
					this.addToImportantRecommendationsIgnore(id);
S
Sandeep Somavarapu 已提交
797 798 799 800 801 802 803
					/* __GDPR__
						"extensionRecommendations:popup" : {
							"userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
							"extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }
						}
					*/
					this.telemetryService.publicLog('extensionRecommendations:popup', { userReaction: 'neverShowAgain', extensionId: name });
804 805
					this.notificationService.prompt(
						Severity.Info,
S
Sandeep Somavarapu 已提交
806
						localize('ignoreExtensionRecommendations', "Do you want to ignore all extension recommendations?"),
807
						[{
S
Sandeep Somavarapu 已提交
808
							label: localize('ignoreAll', "Yes, Ignore All"),
809
							run: () => this.setIgnoreRecommendationsConfig(true)
810
						}, {
S
Sandeep Somavarapu 已提交
811
							label: localize('no', "No"),
812
							run: () => this.setIgnoreRecommendationsConfig(false)
S
Sandeep Somavarapu 已提交
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
						}]
					);
				}
			}],
			{
				sticky: true,
				onCancel: () => {
					/* __GDPR__
						"extensionRecommendations:popup" : {
							"userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
							"extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }
						}
					*/
					this.telemetryService.publicLog('extensionRecommendations:popup', { userReaction: 'cancelled', extensionId: name });
				}
			}
		);

		return true;
	}

	private async promptRecommendedExtensionForFileExtension(fileExtension: string, installed: ILocalExtension[]): Promise<void> {
		const fileExtensionSuggestionIgnoreList = <string[]>JSON.parse(this.storageService.get('extensionsAssistant/fileExtensionsSuggestionIgnore', StorageScope.GLOBAL, '[]'));
		if (fileExtensionSuggestionIgnoreList.indexOf(fileExtension) > -1) {
			return;
		}

		const text = `ext:${fileExtension}`;
		const pager = await this.extensionWorkbenchService.queryGallery({ text, pageSize: 100 }, CancellationToken.None);
		if (pager.firstPage.length === 0) {
			return;
		}

		const installedExtensionsIds = installed.reduce((result, i) => { result.add(i.identifier.id.toLowerCase()); return result; }, new Set<string>());
		if (pager.firstPage.some(e => installedExtensionsIds.has(e.identifier.id.toLowerCase()))) {
			return;
		}

		this.notificationService.prompt(
			Severity.Info,
			localize('showLanguageExtensions', "The Marketplace has extensions that can help with '.{0}' files", fileExtension),
			[{
				label: searchMarketplace,
				run: () => {
					/* __GDPR__
						"fileExtensionSuggestion:popup" : {
							"userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
							"fileExtension": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }
861
						}
S
Sandeep Somavarapu 已提交
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
					*/
					this.telemetryService.publicLog('fileExtensionSuggestion:popup', { userReaction: 'ok', fileExtension: fileExtension });
					this.viewletService.openViewlet('workbench.view.extensions', true)
						.then(viewlet => viewlet as IExtensionsViewlet)
						.then(viewlet => {
							viewlet.search(`ext:${fileExtension}`);
							viewlet.focus();
						});
				}
			}, {
				label: localize('dontShowAgainExtension', "Don't Show Again for '.{0}' files", fileExtension),
				run: () => {
					fileExtensionSuggestionIgnoreList.push(fileExtension);
					this.storageService.store(
						'extensionsAssistant/fileExtensionsSuggestionIgnore',
						JSON.stringify(fileExtensionSuggestionIgnoreList),
						StorageScope.GLOBAL
879
					);
S
Sandeep Somavarapu 已提交
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
					/* __GDPR__
						"fileExtensionSuggestion:popup" : {
							"userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
							"fileExtension": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }
						}
					*/
					this.telemetryService.publicLog('fileExtensionSuggestion:popup', { userReaction: 'neverShowAgain', fileExtension: fileExtension });
				}
			}],
			{
				sticky: true,
				onCancel: () => {
					/* __GDPR__
						"fileExtensionSuggestion:popup" : {
							"userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
							"fileExtension": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }
						}
					*/
					this.telemetryService.publicLog('fileExtensionSuggestion:popup', { userReaction: 'cancelled', fileExtension: fileExtension });
				}
			}
		);
902
	}
J
Joao Moreno 已提交
903

904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
	private filterAllIgnoredInstalledAndNotAllowed(recommendationsToSuggest: string[], installed: ILocalExtension[]): string[] {

		const importantRecommendationsIgnoreList = <string[]>JSON.parse(this.storageService.get('extensionsAssistant/importantRecommendationsIgnore', StorageScope.GLOBAL, '[]'));
		const installedExtensionsIds = installed.reduce((result, i) => { result.add(i.identifier.id.toLowerCase()); return result; }, new Set<string>());
		return recommendationsToSuggest.filter(id => {
			if (importantRecommendationsIgnoreList.indexOf(id) !== -1) {
				return false;
			}
			if (!this.isExtensionAllowedToBeRecommended(id)) {
				return false;
			}
			if (installedExtensionsIds.has(id.toLowerCase())) {
				return false;
			}
			return true;
		});
	}

	private addToImportantRecommendationsIgnore(id: string) {
		const importantRecommendationsIgnoreList = <string[]>JSON.parse(this.storageService.get('extensionsAssistant/importantRecommendationsIgnore', StorageScope.GLOBAL, '[]'));
		importantRecommendationsIgnoreList.push(id);
		this.storageService.store(
			'extensionsAssistant/importantRecommendationsIgnore',
			JSON.stringify(importantRecommendationsIgnoreList),
			StorageScope.GLOBAL
		);
	}

	private setIgnoreRecommendationsConfig(configVal: boolean) {
		this.configurationService.updateValue('extensions.ignoreRecommendations', configVal, ConfigurationTarget.USER);
		if (configVal) {
			const ignoreWorkspaceRecommendationsStorageKey = 'extensionsAssistant/workspaceRecommendationsIgnore';
			this.storageService.store(ignoreWorkspaceRecommendationsStorageKey, true, StorageScope.WORKSPACE);
		}
	}

940
	//#endregion
941

942
	//#region otherRecommendations
943

944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
	getOtherRecommendations(): Promise<IExtensionRecommendation[]> {
		return this.fetchProactiveRecommendations().then(() => {
			const others = distinct([
				...Object.keys(this._exeBasedRecommendations),
				...this._dynamicWorkspaceRecommendations,
				...Object.keys(this._experimentalRecommendations),
			]).filter(extensionId => this.isExtensionAllowedToBeRecommended(extensionId));
			shuffle(others, this.sessionSeed);
			return others.map(extensionId => {
				const sources: ExtensionRecommendationSource[] = [];
				if (this._exeBasedRecommendations[extensionId]) {
					sources.push('executable');
				}
				if (this._dynamicWorkspaceRecommendations.indexOf(extensionId) !== -1) {
					sources.push('dynamic');
				}
				return (<IExtensionRecommendation>{ extensionId, sources });
			});
		});
	}
964

965
	private fetchProactiveRecommendations(calledDuringStartup?: boolean): Promise<void> {
966
		let fetchPromise = Promise.resolve<any>(undefined);
967 968
		if (!this.proactiveRecommendationsFetched) {
			this.proactiveRecommendationsFetched = true;
969

970 971 972
			// Executable based recommendations carry out a lot of file stats, delay the resolution so that the startup is not affected
			// 10 sec for regular extensions
			// 3 secs for important
973

974 975 976 977
			const importantExeBasedRecommendations = timeout(calledDuringStartup ? 3000 : 0).then(_ => this.fetchExecutableRecommendations(true));
			importantExeBasedRecommendations.then(_ => this.promptForImportantExeBasedExtension());

			fetchPromise = timeout(calledDuringStartup ? 10000 : 0).then(_ => Promise.all([this.fetchDynamicWorkspaceRecommendations(), this.fetchExecutableRecommendations(false), importantExeBasedRecommendations]));
978

979 980
		}
		return fetchPromise;
981 982
	}

983 984 985
	/**
	 * If user has any of the tools listed in product.exeBasedExtensionTips, fetch corresponding recommendations
	 */
986
	private fetchExecutableRecommendations(important: boolean): Promise<void> {
987
		const homeDir = os.homedir();
988 989
		let foundExecutables: Set<string> = new Set<string>();

990
		let findExecutable = (exeName: string, tip: IExeBasedExtensionTip, path: string) => {
991
			return pfs.fileExists(path).then(exists => {
992
				if (exists && !foundExecutables.has(exeName)) {
993
					foundExecutables.add(exeName);
994 995 996 997
					(tip['recommendations'] || []).forEach(extensionId => {
						if (tip.friendlyName) {
							if (important) {
								this._importantExeBasedRecommendations[extensionId.toLowerCase()] = tip;
998
							}
999 1000 1001
							this._exeBasedRecommendations[extensionId.toLowerCase()] = tip;
						}
					});
1002 1003 1004 1005
				}
			});
		};

S
Sandeep Somavarapu 已提交
1006
		let promises: Promise<void>[] = [];
1007
		// Loop through recommended extensions
1008
		forEach(product.exeBasedExtensionTips, entry => {
1009 1010 1011
			if (typeof entry.value !== 'object' || !Array.isArray(entry.value['recommendations'])) {
				return;
			}
1012 1013 1014 1015
			if (important !== !!entry.value.important) {
				return;
			}
			const exeName = entry.key;
1016 1017 1018 1019
			if (process.platform === 'win32') {
				let windowsPath = entry.value['windowsPath'];
				if (!windowsPath || typeof windowsPath !== 'string') {
					return;
1020
				}
1021 1022 1023
				windowsPath = windowsPath.replace('%USERPROFILE%', process.env['USERPROFILE']!)
					.replace('%ProgramFiles(x86)%', process.env['ProgramFiles(x86)']!)
					.replace('%ProgramFiles%', process.env['ProgramFiles']!)
1024 1025
					.replace('%APPDATA%', process.env['APPDATA']!)
					.replace('%WINDIR%', process.env['WINDIR']!);
1026
				promises.push(findExecutable(exeName, entry.value, windowsPath));
1027
			} else {
1028 1029
				promises.push(findExecutable(exeName, entry.value, join('/usr/local/bin', exeName)));
				promises.push(findExecutable(exeName, entry.value, join(homeDir, exeName)));
1030
			}
1031
		});
1032

S
Sandeep Somavarapu 已提交
1033
		return Promise.all(promises).then(() => undefined);
1034 1035
	}

1036 1037 1038
	/**
	 * Fetch extensions used by others on the same workspace as recommendations from cache
	 */
1039
	private fetchCachedDynamicWorkspaceRecommendations() {
1040
		if (this.contextService.getWorkbenchState() !== WorkbenchState.FOLDER) {
1041
			return;
1042 1043 1044
		}

		const storageKey = 'extensionsAssistant/dynamicWorkspaceRecommendations';
1045
		let storedRecommendationsJson: { [key: string]: any } = {};
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
		try {
			storedRecommendationsJson = JSON.parse(this.storageService.get(storageKey, StorageScope.WORKSPACE, '{}'));
		} catch (e) {
			this.storageService.remove(storageKey, StorageScope.WORKSPACE);
		}

		if (Array.isArray(storedRecommendationsJson['recommendations'])
			&& isNumber(storedRecommendationsJson['timestamp'])
			&& storedRecommendationsJson['timestamp'] > 0
			&& (Date.now() - storedRecommendationsJson['timestamp']) / milliSecondsInADay < 14) {
1056
			this._dynamicWorkspaceRecommendations = storedRecommendationsJson['recommendations'];
1057 1058
			/* __GDPR__
				"dynamicWorkspaceRecommendations" : {
R
Ramya Achutha Rao 已提交
1059 1060
					"count" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
					"cache" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
1061 1062 1063
				}
			*/
			this.telemetryService.publicLog('dynamicWorkspaceRecommendations', { count: this._dynamicWorkspaceRecommendations.length, cache: 1 });
1064
		}
1065
	}
1066

1067 1068 1069
	/**
	 * Fetch extensions used by others on the same workspace as recommendations from recommendation service
	 */
S
Sandeep Somavarapu 已提交
1070
	private fetchDynamicWorkspaceRecommendations(): Promise<void> {
1071
		if (this.contextService.getWorkbenchState() !== WorkbenchState.FOLDER
1072
			|| !this.fileService.canHandleResource(this.contextService.getWorkspace().folders[0].uri)
1073 1074
			|| this._dynamicWorkspaceRecommendations.length
			|| !this._extensionsRecommendationsUrl) {
R
Rob Lourens 已提交
1075
			return Promise.resolve(undefined);
1076 1077
		}

1078
		const storageKey = 'extensionsAssistant/dynamicWorkspaceRecommendations';
1079
		const workspaceUri = this.contextService.getWorkspace().folders[0].uri;
1080
		return Promise.all([this.workspaceStatsService.getHashedRemotesFromUri(workspaceUri, false), this.workspaceStatsService.getHashedRemotesFromUri(workspaceUri, true)]).then(([hashedRemotes1, hashedRemotes2]) => {
1081 1082
			const hashedRemotes = (hashedRemotes1 || []).concat(hashedRemotes2 || []);
			if (!hashedRemotes.length) {
1083
				return undefined;
1084 1085
			}

1086
			return this.requestService.request({ type: 'GET', url: this._extensionsRecommendationsUrl }, CancellationToken.None).then(context => {
1087
				if (context.res.statusCode !== 200) {
1088
					return Promise.resolve(undefined);
1089
				}
1090
				return asJson(context).then((result: { [key: string]: any }) => {
1091 1092 1093
					if (!result) {
						return;
					}
1094 1095 1096 1097
					const allRecommendations: IDynamicWorkspaceRecommendations[] = Array.isArray(result['workspaceRecommendations']) ? result['workspaceRecommendations'] : [];
					if (!allRecommendations.length) {
						return;
					}
1098

1099 1100 1101 1102 1103
					let foundRemote = false;
					for (let i = 0; i < hashedRemotes.length && !foundRemote; i++) {
						for (let j = 0; j < allRecommendations.length && !foundRemote; j++) {
							if (Array.isArray(allRecommendations[j].remoteSet) && allRecommendations[j].remoteSet.indexOf(hashedRemotes[i]) > -1) {
								foundRemote = true;
1104
								this._dynamicWorkspaceRecommendations = allRecommendations[j].recommendations.filter(id => this.isExtensionAllowedToBeRecommended(id)) || [];
1105 1106 1107 1108 1109 1110
								this.storageService.store(storageKey, JSON.stringify({
									recommendations: this._dynamicWorkspaceRecommendations,
									timestamp: Date.now()
								}), StorageScope.WORKSPACE);
								/* __GDPR__
									"dynamicWorkspaceRecommendations" : {
1111 1112
										"count" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
										"cache" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
1113
									}
1114 1115
								*/
								this.telemetryService.publicLog('dynamicWorkspaceRecommendations', { count: this._dynamicWorkspaceRecommendations.length, cache: 0 });
1116
							}
1117 1118 1119
						}
					}
				});
1120 1121 1122 1123
			});
		});
	}

1124 1125 1126
	/**
	 * Fetch extension recommendations from currently running experiments
	 */
1127
	private fetchExperimentalRecommendations() {
R
Ramya Achutha Rao 已提交
1128
		this.experimentService.getExperimentsByType(ExperimentActionType.AddToRecommendations).then(experiments => {
R
Ramya Rao 已提交
1129
			(experiments || []).forEach(experiment => {
1130 1131
				const action = experiment.action;
				if (action && experiment.state === ExperimentState.Run && action.properties && Array.isArray(action.properties.recommendations) && action.properties.recommendationReason) {
M
Matt Bierner 已提交
1132
					action.properties.recommendations.forEach((id: string) => {
1133
						this._experimentalRecommendations[id] = action.properties.recommendationReason;
R
Ramya Rao 已提交
1134 1135 1136 1137 1138 1139
					});
				}
			});
		});
	}

1140
	//#endregion
1141

1142 1143
	private isExtensionAllowedToBeRecommended(id: string): boolean {
		return this._allIgnoredRecommendations.indexOf(id.toLowerCase()) === -1;
1144
	}
1145
}