integrationListDirectory.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. import {Fragment} from 'react';
  2. import {browserHistory, RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import debounce from 'lodash/debounce';
  5. import flatten from 'lodash/flatten';
  6. import groupBy from 'lodash/groupBy';
  7. import startCase from 'lodash/startCase';
  8. import uniq from 'lodash/uniq';
  9. import * as qs from 'query-string';
  10. import DocIntegrationAvatar from 'sentry/components/avatar/docIntegrationAvatar';
  11. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  12. import SelectControl from 'sentry/components/forms/controls/selectControl';
  13. import HookOrDefault from 'sentry/components/hookOrDefault';
  14. import ExternalLink from 'sentry/components/links/externalLink';
  15. import Panel from 'sentry/components/panels/panel';
  16. import PanelBody from 'sentry/components/panels/panelBody';
  17. import SearchBar from 'sentry/components/searchBar';
  18. import SentryAppIcon from 'sentry/components/sentryAppIcon';
  19. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  20. import {t, tct} from 'sentry/locale';
  21. import {space} from 'sentry/styles/space';
  22. import {
  23. AppOrProviderOrPlugin,
  24. DocIntegration,
  25. Integration,
  26. IntegrationProvider,
  27. Organization,
  28. PluginWithProjectList,
  29. SentryApp,
  30. SentryAppInstallation,
  31. } from 'sentry/types';
  32. import {createFuzzySearch, Fuse} from 'sentry/utils/fuzzySearch';
  33. import {
  34. getAlertText,
  35. getCategoriesForIntegration,
  36. getSentryAppInstallStatus,
  37. isDocIntegration,
  38. isPlugin,
  39. isSentryApp,
  40. trackIntegrationAnalytics,
  41. } from 'sentry/utils/integrationUtil';
  42. import withOrganization from 'sentry/utils/withOrganization';
  43. import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
  44. import PermissionAlert from 'sentry/views/settings/organization/permissionAlert';
  45. import CreateIntegrationButton from 'sentry/views/settings/organizationIntegrations/createIntegrationButton';
  46. import {POPULARITY_WEIGHT} from './constants';
  47. import IntegrationRow from './integrationRow';
  48. const FirstPartyIntegrationAlert = HookOrDefault({
  49. hookName: 'component:first-party-integration-alert',
  50. defaultComponent: () => null,
  51. });
  52. const fuseOptions = {
  53. threshold: 0.3,
  54. location: 0,
  55. distance: 100,
  56. includeScore: true as const,
  57. keys: ['slug', 'key', 'name', 'id'],
  58. };
  59. type Props = RouteComponentProps<{}, {}> & {
  60. hideHeader: boolean;
  61. organization: Organization;
  62. };
  63. type State = {
  64. appInstalls: SentryAppInstallation[] | null;
  65. config: {providers: IntegrationProvider[]} | null;
  66. displayedList: AppOrProviderOrPlugin[];
  67. docIntegrations: DocIntegration[] | null;
  68. integrations: Integration[] | null;
  69. list: AppOrProviderOrPlugin[];
  70. orgOwnedApps: SentryApp[] | null;
  71. plugins: PluginWithProjectList[] | null;
  72. publishedApps: SentryApp[] | null;
  73. searchInput: string;
  74. selectedCategory: string;
  75. extraApp?: SentryApp;
  76. fuzzy?: Fuse<AppOrProviderOrPlugin>;
  77. };
  78. const TEXT_SEARCH_ANALYTICS_DEBOUNCE_IN_MS = 1000;
  79. export class IntegrationListDirectory extends DeprecatedAsyncComponent<
  80. Props & DeprecatedAsyncComponent['props'],
  81. State & DeprecatedAsyncComponent['state']
  82. > {
  83. // Some integrations require visiting a different website to add them. When
  84. // we come back to the tab we want to show our integrations as soon as we can.
  85. shouldReload = true;
  86. reloadOnVisible = true;
  87. shouldReloadOnVisible = true;
  88. getDefaultState() {
  89. return {
  90. ...super.getDefaultState(),
  91. list: [],
  92. displayedList: [],
  93. selectedCategory: '',
  94. };
  95. }
  96. onLoadAllEndpointsSuccess() {
  97. const {publishedApps, orgOwnedApps, extraApp, plugins, docIntegrations} = this.state;
  98. const published = publishedApps || [];
  99. // If we have an extra app in state from query parameter, add it as org owned app
  100. if (orgOwnedApps !== null && extraApp) {
  101. orgOwnedApps.push(extraApp);
  102. }
  103. // we don't want the app to render twice if its the org that created
  104. // the published app.
  105. const orgOwned = orgOwnedApps?.filter(
  106. app => !published.find(p => p.slug === app.slug)
  107. );
  108. /**
  109. * We should have three sections:
  110. * 1. Public apps and integrations available to everyone
  111. * 2. Unpublished apps available to that org
  112. * 3. Internal apps available to that org
  113. */
  114. const combined = ([] as AppOrProviderOrPlugin[])
  115. .concat(published)
  116. .concat(orgOwned ?? [])
  117. .concat(this.providers)
  118. .concat(plugins ?? [])
  119. .concat(docIntegrations ?? []);
  120. const list = this.sortIntegrations(combined);
  121. const {searchInput, selectedCategory} = this.getFilterParameters();
  122. this.setState({list, searchInput, selectedCategory}, () => {
  123. this.updateDisplayedList();
  124. this.trackPageViewed();
  125. });
  126. }
  127. trackPageViewed() {
  128. // count the number of installed apps
  129. const {integrations, publishedApps, plugins} = this.state;
  130. const integrationsInstalled = new Set();
  131. // add installed integrations
  132. integrations?.forEach((integration: Integration) => {
  133. integrationsInstalled.add(integration.provider.key);
  134. });
  135. // add sentry apps
  136. publishedApps?.filter(this.getAppInstall).forEach((sentryApp: SentryApp) => {
  137. integrationsInstalled.add(sentryApp.slug);
  138. });
  139. // add plugins
  140. plugins?.forEach((plugin: PluginWithProjectList) => {
  141. if (plugin.projectList.length) {
  142. integrationsInstalled.add(plugin.slug);
  143. }
  144. });
  145. trackIntegrationAnalytics(
  146. 'integrations.index_viewed',
  147. {
  148. integrations_installed: integrationsInstalled.size,
  149. view: 'integrations_directory',
  150. organization: this.props.organization,
  151. },
  152. {startSession: true}
  153. );
  154. }
  155. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  156. const {organization} = this.props;
  157. const baseEndpoints: ([string, string, any] | [string, string])[] = [
  158. ['config', `/organizations/${organization.slug}/config/integrations/`],
  159. [
  160. 'integrations',
  161. `/organizations/${organization.slug}/integrations/`,
  162. {query: {includeConfig: 0}},
  163. ],
  164. ['orgOwnedApps', `/organizations/${organization.slug}/sentry-apps/`],
  165. ['publishedApps', '/sentry-apps/', {query: {status: 'published'}}],
  166. ['appInstalls', `/organizations/${organization.slug}/sentry-app-installations/`],
  167. ['plugins', `/organizations/${organization.slug}/plugins/configs/`],
  168. ['docIntegrations', '/doc-integrations/'],
  169. ];
  170. /**
  171. * optional app to load for super users
  172. * should only be done for unpublished integrations from another org
  173. * but no checks are in place to ensure the above condition
  174. */
  175. const extraAppSlug = new URLSearchParams(this.props.location.search).get('extra_app');
  176. if (extraAppSlug) {
  177. baseEndpoints.push(['extraApp', `/sentry-apps/${extraAppSlug}/`]);
  178. }
  179. return baseEndpoints;
  180. }
  181. // State
  182. get unmigratableReposByOrg() {
  183. // Group by [GitHub|BitBucket|VSTS] Org name
  184. return groupBy(this.state.unmigratableRepos, repo => repo.name.split('/')[0]);
  185. }
  186. get providers(): IntegrationProvider[] {
  187. return this.state.config?.providers ?? [];
  188. }
  189. getAppInstall = (app: SentryApp) =>
  190. this.state.appInstalls?.find(i => i.app.slug === app.slug);
  191. // Returns 0 if uninstalled, 1 if pending, and 2 if installed
  192. getInstallValue(integration: AppOrProviderOrPlugin) {
  193. const {integrations} = this.state;
  194. if (isPlugin(integration)) {
  195. return integration.projectList.length > 0 ? 2 : 0;
  196. }
  197. if (isSentryApp(integration)) {
  198. const install = this.getAppInstall(integration);
  199. if (install) {
  200. return install.status === 'pending' ? 1 : 2;
  201. }
  202. return 0;
  203. }
  204. if (isDocIntegration(integration)) {
  205. return 0;
  206. }
  207. return integrations?.find(i => i.provider.key === integration.key) ? 2 : 0;
  208. }
  209. getPopularityWeight = (integration: AppOrProviderOrPlugin) => {
  210. if (isSentryApp(integration) || isDocIntegration(integration)) {
  211. return integration?.popularity ?? 1;
  212. }
  213. return POPULARITY_WEIGHT[integration.slug] ?? 1;
  214. };
  215. sortByName = (a: AppOrProviderOrPlugin, b: AppOrProviderOrPlugin) =>
  216. a.slug.localeCompare(b.slug);
  217. sortByPopularity = (a: AppOrProviderOrPlugin, b: AppOrProviderOrPlugin) => {
  218. const weightA = this.getPopularityWeight(a);
  219. const weightB = this.getPopularityWeight(b);
  220. return weightB - weightA;
  221. };
  222. sortByInstalled = (a: AppOrProviderOrPlugin, b: AppOrProviderOrPlugin) =>
  223. this.getInstallValue(b) - this.getInstallValue(a);
  224. sortIntegrations(integrations: AppOrProviderOrPlugin[]) {
  225. return integrations.sort((a: AppOrProviderOrPlugin, b: AppOrProviderOrPlugin) => {
  226. // sort by whether installed first
  227. const diffWeight = this.sortByInstalled(a, b);
  228. if (diffWeight !== 0) {
  229. return diffWeight;
  230. }
  231. // then sort by popularity
  232. const diffPop = this.sortByPopularity(a, b);
  233. if (diffPop !== 0) {
  234. return diffPop;
  235. }
  236. // then sort by name
  237. return this.sortByName(a, b);
  238. });
  239. }
  240. async componentDidUpdate(_: Props, prevState: State) {
  241. if (this.state.list.length !== prevState.list.length) {
  242. await this.createSearch();
  243. }
  244. }
  245. async createSearch() {
  246. const {list} = this.state;
  247. this.setState({
  248. fuzzy: await createFuzzySearch(list || [], fuseOptions),
  249. });
  250. }
  251. debouncedTrackIntegrationSearch = debounce((search: string, numResults: number) => {
  252. trackIntegrationAnalytics('integrations.directory_item_searched', {
  253. view: 'integrations_directory',
  254. search_term: search,
  255. num_results: numResults,
  256. organization: this.props.organization,
  257. });
  258. }, TEXT_SEARCH_ANALYTICS_DEBOUNCE_IN_MS);
  259. /**
  260. * Get filter parameters and guard against `qs.parse` returning arrays.
  261. */
  262. getFilterParameters = (): {searchInput: string; selectedCategory: string} => {
  263. const {category, search} = qs.parse(this.props.location.search);
  264. const selectedCategory = Array.isArray(category) ? category[0] : category || '';
  265. const searchInput = Array.isArray(search) ? search[0] : search || '';
  266. return {searchInput, selectedCategory};
  267. };
  268. /**
  269. * Update the query string with the current filter parameter values.
  270. */
  271. updateQueryString = () => {
  272. const {searchInput, selectedCategory} = this.state;
  273. const searchString = qs.stringify({
  274. ...qs.parse(this.props.location.search),
  275. search: searchInput ? searchInput : undefined,
  276. category: selectedCategory ? selectedCategory : undefined,
  277. });
  278. browserHistory.replace({
  279. pathname: this.props.location.pathname,
  280. search: searchString ? `?${searchString}` : undefined,
  281. });
  282. };
  283. /**
  284. * Filter the integrations list by ANDing together the search query and the category select.
  285. */
  286. updateDisplayedList = (): AppOrProviderOrPlugin[] => {
  287. const {fuzzy, list, searchInput, selectedCategory} = this.state;
  288. let displayedList = list;
  289. if (searchInput && fuzzy) {
  290. const searchResults = fuzzy.search(searchInput);
  291. displayedList = this.sortIntegrations(searchResults.map(i => i.item));
  292. }
  293. if (selectedCategory) {
  294. displayedList = displayedList.filter(integration =>
  295. getCategoriesForIntegration(integration).includes(selectedCategory)
  296. );
  297. }
  298. this.setState({displayedList});
  299. return displayedList;
  300. };
  301. handleSearchChange = (value: string) => {
  302. this.setState({searchInput: value}, () => {
  303. this.updateQueryString();
  304. const result = this.updateDisplayedList();
  305. if (value) {
  306. this.debouncedTrackIntegrationSearch(value, result.length);
  307. }
  308. });
  309. };
  310. onCategorySelect = ({value: category}: {value: string}) => {
  311. this.setState({selectedCategory: category}, () => {
  312. this.updateQueryString();
  313. this.updateDisplayedList();
  314. if (category) {
  315. trackIntegrationAnalytics('integrations.directory_category_selected', {
  316. view: 'integrations_directory',
  317. category,
  318. organization: this.props.organization,
  319. });
  320. }
  321. });
  322. };
  323. getCategoryLabel = (value: string) => {
  324. if (value === 'api') {
  325. return 'API';
  326. }
  327. return startCase(value);
  328. };
  329. // Rendering
  330. renderProvider = (provider: IntegrationProvider) => {
  331. const {organization} = this.props;
  332. // find the integration installations for that provider
  333. const integrations =
  334. this.state.integrations?.filter(i => i.provider.key === provider.key) ?? [];
  335. return (
  336. <IntegrationRow
  337. key={`row-${provider.key}`}
  338. data-test-id="integration-row"
  339. organization={organization}
  340. type="firstParty"
  341. slug={provider.slug}
  342. displayName={provider.name}
  343. status={integrations.length ? 'Installed' : 'Not Installed'}
  344. publishStatus="published"
  345. configurations={integrations.length}
  346. categories={getCategoriesForIntegration(provider)}
  347. alertText={getAlertText(integrations)}
  348. resolveText={t('Update Now')}
  349. customAlert={
  350. <FirstPartyIntegrationAlert integrations={integrations} wrapWithContainer />
  351. }
  352. />
  353. );
  354. };
  355. renderPlugin = (plugin: PluginWithProjectList) => {
  356. const {organization} = this.props;
  357. const isLegacy = plugin.isHidden;
  358. const displayName = `${plugin.name} ${isLegacy ? '(Legacy)' : ''}`;
  359. // hide legacy integrations if we don't have any projects with them
  360. if (isLegacy && !plugin.projectList.length) {
  361. return null;
  362. }
  363. return (
  364. <IntegrationRow
  365. key={`row-plugin-${plugin.id}`}
  366. data-test-id="integration-row"
  367. organization={organization}
  368. type="plugin"
  369. slug={plugin.slug}
  370. displayName={displayName}
  371. status={plugin.projectList.length ? 'Installed' : 'Not Installed'}
  372. publishStatus="published"
  373. configurations={plugin.projectList.length}
  374. categories={getCategoriesForIntegration(plugin)}
  375. plugin={plugin}
  376. />
  377. );
  378. };
  379. // render either an internal or non-internal app
  380. renderSentryApp = (app: SentryApp) => {
  381. const {organization} = this.props;
  382. const status = getSentryAppInstallStatus(this.getAppInstall(app));
  383. const categories = getCategoriesForIntegration(app);
  384. return (
  385. <IntegrationRow
  386. key={`sentry-app-row-${app.slug}`}
  387. data-test-id="integration-row"
  388. organization={organization}
  389. type="sentryApp"
  390. slug={app.slug}
  391. displayName={app.name}
  392. status={status}
  393. publishStatus={app.status}
  394. configurations={0}
  395. categories={categories}
  396. customIcon={<SentryAppIcon sentryApp={app} size={36} />}
  397. />
  398. );
  399. };
  400. renderDocIntegration = (doc: DocIntegration) => {
  401. const {organization} = this.props;
  402. return (
  403. <IntegrationRow
  404. key={`doc-int-${doc.slug}`}
  405. data-test-id="integration-row"
  406. organization={organization}
  407. type="docIntegration"
  408. slug={doc.slug}
  409. displayName={doc.name}
  410. publishStatus="published"
  411. configurations={0}
  412. categories={getCategoriesForIntegration(doc)}
  413. customIcon={<DocIntegrationAvatar docIntegration={doc} size={36} />}
  414. />
  415. );
  416. };
  417. renderIntegration = (integration: AppOrProviderOrPlugin) => {
  418. if (isSentryApp(integration)) {
  419. return this.renderSentryApp(integration);
  420. }
  421. if (isPlugin(integration)) {
  422. return this.renderPlugin(integration);
  423. }
  424. if (isDocIntegration(integration)) {
  425. return this.renderDocIntegration(integration);
  426. }
  427. return this.renderProvider(integration);
  428. };
  429. renderBody() {
  430. const {organization} = this.props;
  431. const {displayedList, list, searchInput, selectedCategory} = this.state;
  432. const title = t('Integrations');
  433. const categoryList = uniq(flatten(list.map(getCategoriesForIntegration))).sort();
  434. return (
  435. <Fragment>
  436. <SentryDocumentTitle title={title} orgSlug={organization.slug} />
  437. {!this.props.hideHeader && (
  438. <SettingsPageHeader
  439. title={title}
  440. body={
  441. <ActionContainer>
  442. <SelectControl
  443. name="select-categories"
  444. onChange={this.onCategorySelect}
  445. value={selectedCategory}
  446. options={[
  447. {value: '', label: t('All Categories')},
  448. ...categoryList.map(category => ({
  449. value: category,
  450. label: this.getCategoryLabel(category),
  451. })),
  452. ]}
  453. />
  454. <SearchBar
  455. query={searchInput || ''}
  456. onChange={this.handleSearchChange}
  457. placeholder={t('Filter Integrations...')}
  458. aria-label={t('Filter')}
  459. width="100%"
  460. data-test-id="search-bar"
  461. />
  462. </ActionContainer>
  463. }
  464. action={<CreateIntegrationButton analyticsView="integrations_directory" />}
  465. />
  466. )}
  467. <PermissionAlert access={['org:integrations']} />
  468. <Panel>
  469. <PanelBody data-test-id="integration-panel">
  470. {displayedList.length ? (
  471. displayedList.map(this.renderIntegration)
  472. ) : (
  473. <EmptyResultsContainer>
  474. <EmptyResultsBody>
  475. {tct('No Integrations found for "[searchTerm]".', {
  476. searchTerm: searchInput,
  477. })}
  478. </EmptyResultsBody>
  479. <EmptyResultsBodyBold>
  480. {t("Not seeing what you're looking for?")}
  481. </EmptyResultsBodyBold>
  482. <EmptyResultsBody>
  483. {tct('[link:Build it on the Sentry Integration Platform.]', {
  484. link: (
  485. <ExternalLink href="https://docs.sentry.io/product/integrations/integration-platform/" />
  486. ),
  487. })}
  488. </EmptyResultsBody>
  489. </EmptyResultsContainer>
  490. )}
  491. </PanelBody>
  492. </Panel>
  493. </Fragment>
  494. );
  495. }
  496. }
  497. const ActionContainer = styled('div')`
  498. display: grid;
  499. grid-template-columns: 240px auto;
  500. gap: ${space(2)};
  501. `;
  502. const EmptyResultsContainer = styled('div')`
  503. height: 200px;
  504. display: flex;
  505. flex-direction: column;
  506. align-items: center;
  507. justify-content: center;
  508. `;
  509. const EmptyResultsBody = styled('div')`
  510. font-size: 16px;
  511. line-height: 28px;
  512. color: ${p => p.theme.gray300};
  513. padding-bottom: ${space(2)};
  514. `;
  515. const EmptyResultsBodyBold = styled(EmptyResultsBody)`
  516. font-weight: bold;
  517. `;
  518. export default withOrganization(IntegrationListDirectory);