extensionTipsService.ts 44.0 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 } 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 {
13
	IExtensionManagementService, IExtensionGalleryService, IExtensionTipsService, ExtensionRecommendationReason, EXTENSION_IDENTIFIER_PATTERN,
S
Sandeep Somavarapu 已提交
14
	IExtensionsConfigContent, RecommendationChangeNotification, IExtensionRecommendation, ExtensionRecommendationSource, InstallOperation, ILocalExtension
15
} from 'vs/platform/extensionManagement/common/extensionManagement';
J
Johannes Rieken 已提交
16
import { IModelService } from 'vs/editor/common/services/modelService';
A
Alex Dima 已提交
17
import { ITextModel } from 'vs/editor/common/model';
J
Johannes Rieken 已提交
18
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
19
import product from 'vs/platform/product/node/product';
20
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
21
import { ShowRecommendedExtensionsAction, InstallWorkspaceRecommendedExtensionsAction, InstallRecommendedExtensionAction } from 'vs/workbench/contrib/extensions/browser/extensionsActions';
22
import Severity from 'vs/base/common/severity';
23
import { IWorkspaceContextService, IWorkspaceFolder, IWorkspace, IWorkspaceFoldersChangeEvent, WorkbenchState } from 'vs/platform/workspace/common/workspace';
24
import { IFileService } from 'vs/platform/files/common/files';
25
import { IExtensionsConfiguration, ConfigurationKey, ShowRecommendationsOnlyOnDemandKey, IExtensionsViewlet, IExtensionsWorkbenchService, EXTENSIONS_CONFIG } from 'vs/workbench/contrib/extensions/common/extensions';
26
import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
27
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
28 29
import * as pfs from 'vs/base/node/pfs';
import * as os from 'os';
S
Sandeep Somavarapu 已提交
30
import { flatten, distinct, shuffle, coalesce } from 'vs/base/common/arrays';
31
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
32
import { guessMimeTypes, MIME_UNKNOWN } from 'vs/base/common/mime';
33
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
34
import { getHashedRemotesFromUri } from 'vs/workbench/contrib/stats/electron-browser/workspaceStats';
35
import { IRequestService, asJson } from 'vs/platform/request/common/request';
36
import { isNumber } from 'vs/base/common/types';
37
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
38
import { INotificationService } from 'vs/platform/notification/common/notification';
39
import { Emitter, Event } from 'vs/base/common/event';
40
import { assign } from 'vs/base/common/objects';
41
import { URI } from 'vs/base/common/uri';
42
import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
43
import { IExperimentService, ExperimentActionType, ExperimentState } from 'vs/workbench/contrib/experiments/common/experimentService';
44
import { CancellationToken } from 'vs/base/common/cancellation';
45
import { ExtensionType } from 'vs/platform/extensions/common/extensions';
B
Benjamin Pasero 已提交
46
import { extname } from 'vs/base/common/resources';
B
Benjamin Pasero 已提交
47
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
48

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

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

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

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

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

S
Sandeep Somavarapu 已提交
75
	private _fileBasedRecommendations: { [id: string]: { recommendedTime: number, sources: ExtensionRecommendationSource[] }; } = Object.create(null);
76
	private _exeBasedRecommendations: { [id: string]: string; } = 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 97 98 99 100 101 102 103 104 105 106 107 108 109
		@IStorageService private readonly storageService: IStorageService,
		@IExtensionManagementService private readonly extensionsService: IExtensionManagementService,
		@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,
B
Benjamin Pasero 已提交
110
		@ITextFileService private readonly textFileService: ITextFileService
111
	) {
S
Sandeep Somavarapu 已提交
112 113
		super();

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

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

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

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

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

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

S
Sandeep Somavarapu 已提交
140
		this._register(this.contextService.onDidChangeWorkspaceFolders(e => this.onWorkspaceFoldersChanged(e)));
141
		this._register(this.configurationService.onDidChangeConfiguration(e => {
142
			if (!this.proactiveRecommendationsFetched && !this.configurationService.getValue<boolean>(ShowRecommendationsOnlyOnDemandKey)) {
143 144 145
				this.fetchProactiveRecommendations();
			}
		}));
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
		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 }));
				}
			}
		}));
163 164
	}

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

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

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

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

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

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

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

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

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

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

209 210 211
		return output;
	}

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

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

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

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

		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 } = {};

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

S
Sandeep Somavarapu 已提交
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
					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) {
293
									let recommendation = this._allWorkspaceRecommendedExtensions.filter(r => r.extensionId === extensionId)[0];
S
Sandeep Somavarapu 已提交
294 295
									if (!recommendation) {
										recommendation = { extensionId, sources: [] };
296
										this._allWorkspaceRecommendedExtensions.push(recommendation);
S
Sandeep Somavarapu 已提交
297 298 299 300 301 302 303 304 305 306 307 308
									}
									if (recommendation.sources.indexOf(contentsBySource.source) === -1) {
										recommendation.sources.push(contentsBySource.source);
									}
								}
							}
						}
					}
					this._allIgnoredRecommendations = distinct([...this._globallyIgnoredRecommendations, ...this._workspaceIgnoredRecommendations]);
				}));
	}

309 310 311
	/**
	 * Parse all extensions.json files, fetch workspace recommendations
	 */
S
Sandeep Somavarapu 已提交
312
	private fetchExtensionRecommendationContents(): Promise<{ contents: IExtensionsConfigContent, source: ExtensionRecommendationSource }[]> {
313
		const workspace = this.contextService.getWorkspace();
314
		return Promise.all<{ contents: IExtensionsConfigContent, source: ExtensionRecommendationSource } | null>([
S
Sandeep Somavarapu 已提交
315 316 317
			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));
318 319
	}

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

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

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

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

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

352 353
		const regEx = new RegExp(EXTENSION_IDENTIFIER_PATTERN);

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

S
Sandeep Somavarapu 已提交
357
		const regexFilter = (ids: string[]) => {
358 359
			return ids.filter((element, position) => {
				if (ids.indexOf(element) !== position) {
360 361 362 363
					// 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 已提交
364 365
					invalidExtensions.push(element.toLowerCase());
					message += `${element} (bad format) Expected: <provider>.<name>\n`;
366 367 368 369
					return false;
				}
				return true;
			});
370 371
		};

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

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

379 380 381 382 383 384 385 386 387 388
				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);
389
			}
390 391
		}
		return { invalidExtensions, message };
392
	}
393

S
Sandeep Somavarapu 已提交
394 395
	private onWorkspaceFoldersChanged(event: IWorkspaceFoldersChangeEvent): void {
		if (event.added.length) {
396
			const oldWorkspaceRecommended = this._allWorkspaceRecommendedExtensions;
S
Sandeep Somavarapu 已提交
397 398 399 400
			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))) {
401
						this.promptWorkspaceRecommendations();
S
Sandeep Somavarapu 已提交
402 403
					}
				});
S
Sandeep Somavarapu 已提交
404
		}
405
		this._dynamicWorkspaceRecommendations = [];
S
Sandeep Somavarapu 已提交
406 407
	}

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
	/**
	 * 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;
		}

423
		this.extensionsService.getInstalled(ExtensionType.User).then(local => {
424
			const recommendations = filteredRecs.filter(({ extensionId }) => local.every(local => !areSameExtensions({ id: extensionId }, local.identifier)));
425 426

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

			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 已提交
448
							c(undefined);
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
						}
					}, {
						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 已提交
464
							c(undefined);
465 466 467 468 469 470 471 472 473 474 475 476 477
						}
					}, {
						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 已提交
478
							c(undefined);
479 480 481 482 483 484 485 486 487 488 489 490
						}
					}],
					{
						sticky: true,
						onCancel: () => {
							/* __GDPR__
								"extensionWorkspaceRecommendations:popup" : {
									"userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
								}
							*/
							this.telemetryService.publicLog('extensionWorkspaceRecommendations:popup', { userReaction: 'cancelled' });

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

	//#endregion

	//#region fileBasedRecommendations

S
Sandeep Somavarapu 已提交
503
	getFileBasedRecommendations(): IExtensionRecommendation[] {
504 505 506 507 508 509 510 511 512
		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;
					}
513
				}
514 515 516 517
				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 已提交
518
	}
519

520 521 522 523
	/**
	 * 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
	 */
524
	private fetchFileBasedRecommendations() {
525
		const extensionTips = product.extensionTips;
526 527 528
		if (!extensionTips) {
			return;
		}
529

530 531 532
		// group ids by pattern, like {**/*.md} -> [ext.foo1, ext.bar2]
		this._availableRecommendations = Object.create(null);
		forEach(extensionTips, entry => {
A
Alex Dima 已提交
533
			let { key: id, value: pattern } = entry;
534 535 536 537 538
			let ids = this._availableRecommendations[pattern];
			if (!ids) {
				this._availableRecommendations[pattern] = [id.toLowerCase()];
			} else {
				ids.push(id.toLowerCase());
539
			}
540 541
		});

J
Joao Moreno 已提交
542
		forEach(product.extensionImportantTips, entry => {
A
Alex Dima 已提交
543
			let { key: id, value } = entry;
544 545 546 547 548 549
			const { pattern } = value;
			let ids = this._availableRecommendations[pattern];
			if (!ids) {
				this._availableRecommendations[pattern] = [id.toLowerCase()];
			} else {
				ids.push(id.toLowerCase());
J
Joao Moreno 已提交
550 551 552
			}
		});

553
		const allRecommendations: string[] = flatten((Object.keys(this._availableRecommendations).map(key => this._availableRecommendations[key])));
554 555 556 557 558 559

		// 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) {
560
				if (allRecommendations.indexOf(id) > -1) {
S
Sandeep Somavarapu 已提交
561
					this._fileBasedRecommendations[id.toLowerCase()] = { recommendedTime: Date.now(), sources: ['cached'] };
562 563 564 565 566 567 568
				}
			}
		} else {
			const now = Date.now();
			forEach(storedRecommendationsJson, entry => {
				if (typeof entry.value === 'number') {
					const diff = (now - entry.value) / milliSecondsInADay;
569
					if (diff <= 7 && allRecommendations.indexOf(entry.key) > -1) {
S
Sandeep Somavarapu 已提交
570
						this._fileBasedRecommendations[entry.key.toLowerCase()] = { recommendedTime: entry.value, sources: ['cached'] };
571 572 573 574
					}
				}
			});
		}
575 576
	}

577 578 579 580
	/**
	 * 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
	 */
581 582
	private promptFiletypeBasedRecommendations(model: ITextModel): void {
		const uri = model.uri;
583
		if (!uri || !this.fileService.canHandleResource(uri)) {
J
Johannes Rieken 已提交
584
			return;
585 586
		}

B
Benjamin Pasero 已提交
587
		let fileExtension = extname(uri);
588 589 590 591 592 593 594
		if (fileExtension) {
			if (processedFileExtensions.indexOf(fileExtension) > -1) {
				return;
			}
			processedFileExtensions.push(fileExtension);
		}

S
Sandeep Somavarapu 已提交
595 596
		// re-schedule this bit of the operation to be off the critical path - in case glob-match is slow
		setImmediate(async () => {
S
Sandeep Somavarapu 已提交
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618

			let recommendationsToSuggest: string[] = [];
			const now = Date.now();
			forEach(this._availableRecommendations, entry => {
				let { key: pattern, value: ids } = entry;
				if (match(pattern, model.uri.path)) {
					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',
619
				JSON.stringify(Object.keys(this._fileBasedRecommendations).reduce((result, key) => { result[key] = this._fileBasedRecommendations[key].recommendedTime; return result; }, {} as { [key: string]: any })),
S
Sandeep Somavarapu 已提交
620 621 622 623 624 625 626 627
				StorageScope.GLOBAL
			);

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

S
Sandeep Somavarapu 已提交
628
			const installed = await this.extensionManagementService.getInstalled(ExtensionType.User);
S
Sandeep Somavarapu 已提交
629
			if (await this.promptRecommendedExtensionForFileType(recommendationsToSuggest, installed)) {
S
Sandeep Somavarapu 已提交
630 631
				return;
			}
J
Joao Moreno 已提交
632

S
Sandeep Somavarapu 已提交
633 634 635 636 637 638
			if (fileExtension) {
				fileExtension = fileExtension.substr(1); // Strip the dot
			}
			if (!fileExtension) {
				return;
			}
J
cleanup  
Joao Moreno 已提交
639

S
Sandeep Somavarapu 已提交
640
			await this.extensionService.whenInstalledExtensionsRegistered();
B
Benjamin Pasero 已提交
641
			const mimeTypes = guessMimeTypes(uri);
S
Sandeep Somavarapu 已提交
642
			if (mimeTypes.length !== 1 || mimeTypes[0] !== MIME_UNKNOWN) {
643 644 645
				return;
			}

S
Sandeep Somavarapu 已提交
646 647 648
			this.promptRecommendedExtensionForFileExtension(fileExtension, installed);
		});
	}
649

S
Sandeep Somavarapu 已提交
650
	private async promptRecommendedExtensionForFileType(recommendationsToSuggest: string[], installed: ILocalExtension[]): Promise<boolean> {
S
Sandeep Somavarapu 已提交
651 652 653 654 655 656 657 658 659 660 661 662 663 664
		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>());
		recommendationsToSuggest = 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;
		});
665

S
Sandeep Somavarapu 已提交
666 667 668
		if (recommendationsToSuggest.length === 0) {
			return false;
		}
669

S
Sandeep Somavarapu 已提交
670 671 672 673 674 675
		const id = recommendationsToSuggest[0];
		const entry = caseInsensitiveGet(product.extensionImportantTips, id);
		if (!entry) {
			return false;
		}
		const name = entry['name'];
676

S
Sandeep Somavarapu 已提交
677 678 679 680 681
		let message = localize('reallyRecommended2', "The '{0}' extension is recommended for this file type.", name);
		// Temporary fix for the only extension pack we recommend. See https://github.com/Microsoft/vscode/issues/35364
		if (id === 'vscjava.vscode-java-pack') {
			message = localize('reallyRecommendedExtensionPack', "The '{0}' extension pack is recommended for this file type.", name);
		}
682

S
Sandeep Somavarapu 已提交
683 684 685 686 687 688 689
		const setIgnoreRecommendationsConfig = (configVal: boolean) => {
			this.configurationService.updateValue('extensions.ignoreRecommendations', configVal, ConfigurationTarget.USER);
			if (configVal) {
				const ignoreWorkspaceRecommendationsStorageKey = 'extensionsAssistant/workspaceRecommendationsIgnore';
				this.storageService.store(ignoreWorkspaceRecommendationsStorageKey, true, StorageScope.WORKSPACE);
			}
		};
690

S
Sandeep Somavarapu 已提交
691 692 693 694 695 696 697 698 699 700 701 702
		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();
703
				}
S
Sandeep Somavarapu 已提交
704 705 706 707 708 709 710 711 712 713
			}, {
				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 });
714

S
Sandeep Somavarapu 已提交
715 716 717
					const recommendationsAction = this.instantiationService.createInstance(ShowRecommendedExtensionsAction, ShowRecommendedExtensionsAction.ID, localize('showRecommendations', "Show Recommendations"));
					recommendationsAction.run();
					recommendationsAction.dispose();
718
				}
S
Sandeep Somavarapu 已提交
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
			}, {
				label: choiceNever,
				isSecondary: true,
				run: () => {
					importantRecommendationsIgnoreList.push(id);
					this.storageService.store(
						'extensionsAssistant/importantRecommendationsIgnore',
						JSON.stringify(importantRecommendationsIgnoreList),
						StorageScope.GLOBAL
					);
					/* __GDPR__
						"extensionRecommendations:popup" : {
							"userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
							"extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }
						}
					*/
					this.telemetryService.publicLog('extensionRecommendations:popup', { userReaction: 'neverShowAgain', extensionId: name });
736 737
					this.notificationService.prompt(
						Severity.Info,
S
Sandeep Somavarapu 已提交
738
						localize('ignoreExtensionRecommendations', "Do you want to ignore all extension recommendations?"),
739
						[{
S
Sandeep Somavarapu 已提交
740 741
							label: localize('ignoreAll', "Yes, Ignore All"),
							run: () => setIgnoreRecommendationsConfig(true)
742
						}, {
S
Sandeep Somavarapu 已提交
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
							label: localize('no', "No"),
							run: () => setIgnoreRecommendationsConfig(false)
						}]
					);
				}
			}],
			{
				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" }
793
						}
S
Sandeep Somavarapu 已提交
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
					*/
					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
811
					);
S
Sandeep Somavarapu 已提交
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
					/* __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 });
				}
			}
		);
834
	}
J
Joao Moreno 已提交
835

836
	//#endregion
837

838
	//#region otherRecommendations
839

840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
	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 });
			});
		});
	}
860

861
	private fetchProactiveRecommendations(calledDuringStartup?: boolean): Promise<void> {
862
		let fetchPromise = Promise.resolve(undefined);
863 864
		if (!this.proactiveRecommendationsFetched) {
			this.proactiveRecommendationsFetched = true;
865

866 867
			// Executable based recommendations carry out a lot of file stats, so run them after 10 secs
			// So that the startup is not affected
868

869 870
			fetchPromise = new Promise((c, e) => {
				setTimeout(() => {
R
Rob Lourens 已提交
871
					Promise.all([this.fetchExecutableRecommendations(), this.fetchDynamicWorkspaceRecommendations()]).then(() => c(undefined));
872
				}, calledDuringStartup ? 10000 : 0);
J
Joao Moreno 已提交
873
			});
874

875 876
		}
		return fetchPromise;
877 878
	}

879 880 881
	/**
	 * If user has any of the tools listed in product.exeBasedExtensionTips, fetch corresponding recommendations
	 */
S
Sandeep Somavarapu 已提交
882
	private fetchExecutableRecommendations(): Promise<void> {
883
		const homeDir = os.homedir();
884 885
		let foundExecutables: Set<string> = new Set<string>();

886
		let findExecutable = (exeName: string, path: string) => {
887
			return pfs.fileExists(path).then(exists => {
888
				if (exists && !foundExecutables.has(exeName)) {
889
					foundExecutables.add(exeName);
890
					(product.exeBasedExtensionTips[exeName]['recommendations'] || [])
891
						.forEach(extensionId => {
892
							if (product.exeBasedExtensionTips[exeName]['friendlyName']) {
893
								this._exeBasedRecommendations[extensionId.toLowerCase()] = product.exeBasedExtensionTips[exeName]['friendlyName'];
894 895
							}
						});
896 897 898 899
				}
			});
		};

S
Sandeep Somavarapu 已提交
900
		let promises: Promise<void>[] = [];
901
		// Loop through recommended extensions
902
		forEach(product.exeBasedExtensionTips, entry => {
903 904 905
			if (typeof entry.value !== 'object' || !Array.isArray(entry.value['recommendations'])) {
				return;
			}
906

907 908 909 910 911
			let exeName = entry.key;
			if (process.platform === 'win32') {
				let windowsPath = entry.value['windowsPath'];
				if (!windowsPath || typeof windowsPath !== 'string') {
					return;
912
				}
913 914 915
				windowsPath = windowsPath.replace('%USERPROFILE%', process.env['USERPROFILE']!)
					.replace('%ProgramFiles(x86)%', process.env['ProgramFiles(x86)']!)
					.replace('%ProgramFiles%', process.env['ProgramFiles']!)
916 917
					.replace('%APPDATA%', process.env['APPDATA']!)
					.replace('%WINDIR%', process.env['WINDIR']!);
918
				promises.push(findExecutable(exeName, windowsPath));
919
			} else {
920 921
				promises.push(findExecutable(exeName, join('/usr/local/bin', exeName)));
				promises.push(findExecutable(exeName, join(homeDir, exeName)));
922
			}
923
		});
924

S
Sandeep Somavarapu 已提交
925
		return Promise.all(promises).then(() => undefined);
926 927
	}

928 929 930
	/**
	 * Fetch extensions used by others on the same workspace as recommendations from cache
	 */
931
	private fetchCachedDynamicWorkspaceRecommendations() {
932
		if (this.contextService.getWorkbenchState() !== WorkbenchState.FOLDER) {
933
			return;
934 935 936
		}

		const storageKey = 'extensionsAssistant/dynamicWorkspaceRecommendations';
937
		let storedRecommendationsJson: { [key: string]: any } = {};
938 939 940 941 942 943 944 945 946 947
		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) {
948
			this._dynamicWorkspaceRecommendations = storedRecommendationsJson['recommendations'];
949 950
			/* __GDPR__
				"dynamicWorkspaceRecommendations" : {
R
Ramya Achutha Rao 已提交
951 952
					"count" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
					"cache" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
953 954 955
				}
			*/
			this.telemetryService.publicLog('dynamicWorkspaceRecommendations', { count: this._dynamicWorkspaceRecommendations.length, cache: 1 });
956
		}
957
	}
958

959 960 961
	/**
	 * Fetch extensions used by others on the same workspace as recommendations from recommendation service
	 */
S
Sandeep Somavarapu 已提交
962
	private fetchDynamicWorkspaceRecommendations(): Promise<void> {
963
		if (this.contextService.getWorkbenchState() !== WorkbenchState.FOLDER
964
			|| !this.fileService.canHandleResource(this.contextService.getWorkspace().folders[0].uri)
965 966
			|| this._dynamicWorkspaceRecommendations.length
			|| !this._extensionsRecommendationsUrl) {
R
Rob Lourens 已提交
967
			return Promise.resolve(undefined);
968 969
		}

970
		const storageKey = 'extensionsAssistant/dynamicWorkspaceRecommendations';
971
		const workspaceUri = this.contextService.getWorkspace().folders[0].uri;
B
Benjamin Pasero 已提交
972
		return Promise.all([getHashedRemotesFromUri(workspaceUri, this.fileService, this.textFileService, false), getHashedRemotesFromUri(workspaceUri, this.fileService, this.textFileService, true)]).then(([hashedRemotes1, hashedRemotes2]) => {
973 974
			const hashedRemotes = (hashedRemotes1 || []).concat(hashedRemotes2 || []);
			if (!hashedRemotes.length) {
975
				return undefined;
976 977
			}

978
			return this.requestService.request({ type: 'GET', url: this._extensionsRecommendationsUrl }, CancellationToken.None).then(context => {
979
				if (context.res.statusCode !== 200) {
980
					return Promise.resolve(undefined);
981
				}
982
				return asJson(context).then((result: { [key: string]: any }) => {
983 984 985
					if (!result) {
						return;
					}
986 987 988 989
					const allRecommendations: IDynamicWorkspaceRecommendations[] = Array.isArray(result['workspaceRecommendations']) ? result['workspaceRecommendations'] : [];
					if (!allRecommendations.length) {
						return;
					}
990

991 992 993 994 995
					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;
996
								this._dynamicWorkspaceRecommendations = allRecommendations[j].recommendations.filter(id => this.isExtensionAllowedToBeRecommended(id)) || [];
997 998 999 1000 1001 1002
								this.storageService.store(storageKey, JSON.stringify({
									recommendations: this._dynamicWorkspaceRecommendations,
									timestamp: Date.now()
								}), StorageScope.WORKSPACE);
								/* __GDPR__
									"dynamicWorkspaceRecommendations" : {
1003 1004
										"count" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
										"cache" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
1005
									}
1006 1007
								*/
								this.telemetryService.publicLog('dynamicWorkspaceRecommendations', { count: this._dynamicWorkspaceRecommendations.length, cache: 0 });
1008
							}
1009 1010 1011
						}
					}
				});
1012 1013 1014 1015
			});
		});
	}

1016 1017 1018
	/**
	 * Fetch extension recommendations from currently running experiments
	 */
1019
	private fetchExperimentalRecommendations() {
R
Ramya Achutha Rao 已提交
1020
		this.experimentService.getExperimentsByType(ExperimentActionType.AddToRecommendations).then(experiments => {
R
Ramya Rao 已提交
1021
			(experiments || []).forEach(experiment => {
1022 1023
				const action = experiment.action;
				if (action && experiment.state === ExperimentState.Run && action.properties && Array.isArray(action.properties.recommendations) && action.properties.recommendationReason) {
M
Matt Bierner 已提交
1024
					action.properties.recommendations.forEach((id: string) => {
1025
						this._experimentalRecommendations[id] = action.properties.recommendationReason;
R
Ramya Rao 已提交
1026 1027 1028 1029 1030 1031
					});
				}
			});
		});
	}

1032
	//#endregion
1033

1034 1035
	private isExtensionAllowedToBeRecommended(id: string): boolean {
		return this._allIgnoredRecommendations.indexOf(id.toLowerCase()) === -1;
1036
	}
1037
}