integrationListDirectory.tsx 19 KB

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