Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions docs/OPENING_LINKS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Opening links in services

Ferdium can act as the desktop app of the services it runs. When another program asks Ferdium to open a link, Ferdium finds the service the link belongs to, shows it and loads the link in it. That covers two kinds of links:

- **http(s) links**, for example a Slack permalink handed to Ferdium by a link router that is set up as the default browser.
- **App links** of a service, for example the `slack://` link that the "Open in app" button on a Slack web page opens.

The work is split in two. Ferdium does the generic part: getting the link to the right window, asking the recipes who owns it, and loading it. Each recipe does the part that only it knows: which links belong to it and what url its web app needs for them.

## How a link travels

1. **The operating system starts Ferdium with the link as an argument.** For app links that only happens when Ferdium is registered as their handler, see [Registering app link protocols](#registering-app-link-protocols). When Ferdium is already running, the new process passes its arguments to the running one and quits without opening a window.
2. **The main process picks the link out of the arguments** (`getExternalUrlFromArgs` in `src/electron/deepLinking.ts`): the first argument that has a scheme, except Ferdium's own `ferdium://` deep links, which are handled as before. It sends the link to the window as `openUrlInService`.
3. **The renderer waits until the services are loaded**, because a link can be what started Ferdium (`ServicesStore._openUrl`).
4. **Ferdium asks the recipe of each displayed service**, in sidebar order, whether the link is its own (`resolveServiceLink` in `src/helpers/open-url-helpers.ts`). The first recipe that returns a url wins. When no recipe claims the link, an http(s) link opens in the first service whose own address has the same host.
5. **Ferdium shows that service and loads the url in its webview.** A hibernated service is woken up first.
6. **When no service matches**, Ferdium tells the user in a dialog and does nothing else. It does not hand the link to the default browser, because a link router may send it straight back to Ferdium.

## What a recipe can do

All of this is optional. A recipe that does nothing keeps working as before, and links to its own host still open in it.

- **`resolveLink(link, context)`** in the recipe's `index.js` decides whether a link belongs to this service. It returns the url the service should load, or `null` when the link isn't its own. `context` holds what Ferdium knows about the service: its `url`, its `team` and its `linkContext`. The base class returns `null`.
- **`Ferdium.setLinkContext({ ... })`** in the recipe's `webview.js` stores details the page knows and Ferdium doesn't, so `resolveLink` can use them later. Ferdium saves them with the service's settings and only when they change.
- **`protocols`** in the recipe's `package.json` lists the app link protocols the recipe handles, for example `["slack"]`. Only list a protocol when `resolveLink` handles its links.

Every service has its own quirks, and they belong in its recipe, not in Ferdium. Slack is an example of all three:

- A `slack://channel?team=T…&id=C…&message=…` link only names the workspace id, while the service only knows its subdomain. The recipe's `webview.js` reads the workspace id from the web client's url (`app.slack.com/client/T…`) and stores it with `setLinkContext`, so `resolveLink` can tell whether an app link is meant for this workspace.
- A permalink to `/archives/…` first shows an "open in the Slack app" page, while the same link to `/messages/…` opens the message in the web client. `resolveLink` rewrites the one into the other.
- `"protocols": ["slack"]` lets Ferdium register for `slack://` links.

## Registering app link protocols

The setting **Open app links in Ferdium** (off by default) registers Ferdium as the handler for the protocols of the recipes of the user's services. It's off by default so Ferdium never takes over links from a native app the user still uses.

Electron can only unregister a protocol handler on Windows and macOS. On Linux the registration stays until the user removes it, for example with `xdg-mime`.

Ferdium registers itself for `ferdium://` regardless of this setting, as before.
1 change: 1 addition & 0 deletions src/@types/stores.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ export interface AppStore extends TypedStore {
isSystemMuteOverridden: () => void;
locale: string;
lockedPassword: string;
openAppLinksInFerdium: boolean;
reloadAfterResume: boolean;
reloadAfterResumeTime: number;
searchEngine: string;
Expand Down
4 changes: 4 additions & 0 deletions src/actions/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,10 @@ export default <ActionDefinitions>{
openWindow: {
event: PropTypes.object.isRequired,
},
openUrl: {
url: PropTypes.string.isRequired,
},
clearUnmatchedUrl: {},
reload: {
serviceId: PropTypes.string.isRequired,
},
Expand Down
50 changes: 50 additions & 0 deletions src/components/services/UnmatchedUrlDialog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { dialog, getCurrentWindow } from '@electron/remote';
import { useEffect } from 'react';
import {
type WrappedComponentProps,
defineMessages,
injectIntl,
} from 'react-intl';

import globalMessages from '../../i18n/globalMessages';

const messages = defineMessages({
title: {
id: 'service.unmatchedUrl.title',
defaultMessage: 'No service for this link',
},
detail: {
id: 'service.unmatchedUrl.detail',
defaultMessage: "{url} doesn't match any of your services.",
},
});

interface IProps extends WrappedComponentProps {
url: string | null;
onClose: () => void;
}

/**
* Tells the user that a link Ferdium was asked to open matches none of the
* services.
*/
function UnmatchedUrlDialog({ url, onClose, intl }: IProps) {
useEffect(() => {
if (!url) {
return;
}

dialog
.showMessageBox(getCurrentWindow(), {
type: 'info',
message: intl.formatMessage(messages.title),
detail: intl.formatMessage(messages.detail, { url }),
buttons: [intl.formatMessage(globalMessages.ok)],
})
.then(() => onClose());
}, [url, intl, onClose]);

return null;
}

export default injectIntl(UnmatchedUrlDialog);
16 changes: 16 additions & 0 deletions src/components/settings/settings/EditSettingsForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ const debug = require('../../../preload-safe-debug')(
);

const messages = defineMessages({
openAppLinksInFerdiumInfo: {
id: 'settings.app.openAppLinksInFerdiumInfo',
defaultMessage:
'Ferdium becomes the handler for the app links of your services, like the "Open in app" button on a Slack web page. Turning this off again is not possible on Linux; remove the handler there with xdg-mime.',
},
headlineGeneral: {
id: 'settings.app.headlineGeneral',
defaultMessage: 'General',
Expand Down Expand Up @@ -695,6 +700,17 @@ class EditSettingsForm extends Component<IProps, IState> {
</>
)}

{/* macOS only allows protocols declared when the app is built */}
{!isMac && (
<>
<Toggle {...form.$('openAppLinksInFerdium').bind()} />
<p className="settings__help indented__help">
{intl.formatMessage(messages.openAppLinksInFerdiumInfo)}
</p>
<Hr />
</>
)}

<Toggle {...form.$('keepAllWorkspacesLoaded').bind()} />

{isTodosActivated && <Hr />}
Expand Down
1 change: 1 addition & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,7 @@ export const DEFAULT_APP_SETTINGS = {
reloadAfterResumeTime: 10,
enableSystemTray: true,
startMinimized: false,
openAppLinksInFerdium: false,
confirmOnQuit: false,
minimizeToSystemTray: false,
closeToSystemTray: false,
Expand Down
10 changes: 10 additions & 0 deletions src/containers/layout/AppLayoutContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { ThemeProvider as MUIThemeProvider } from '@mui/material/styles';
import type { StoresProps } from '../../@types/ferdium-components.types';
import AppLayout from '../../components/layout/AppLayout';
import Sidebar from '../../components/layout/Sidebar';
import UnmatchedUrlDialog from '../../components/services/UnmatchedUrlDialog';
import Services from '../../components/services/content/Services';
import AppLoader from '../../components/ui/AppLoader';
import { workspaceStore } from '../../features/workspaces';
Expand All @@ -17,6 +18,11 @@ interface IProps extends StoresProps {}
@inject('stores', 'actions')
@observer
class AppLayoutContainer extends Component<IProps> {
// A stable reference, so the unmatched url dialog doesn't reopen on every render
clearUnmatchedUrl = (): void => {
this.props.actions.service.clearUnmatchedUrl();
};

render(): ReactElement {
const { app, features, services, ui, settings, requests, user, router } =
this.props.stores;
Expand Down Expand Up @@ -165,6 +171,10 @@ class AppLayoutContainer extends Component<IProps> {
>
<Outlet />
</AppLayout>
<UnmatchedUrlDialog
url={services.unmatchedUrl}
onClose={this.clearUnmatchedUrl}
/>
</ThemeProvider>
</MUIThemeProvider>
);
Expand Down
14 changes: 14 additions & 0 deletions src/containers/settings/EditSettingsScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,10 @@ const messages = defineMessages({
id: 'settings.app.form.enableMenuBar',
defaultMessage: 'Always show Ferdium in Menu Bar',
},
openAppLinksInFerdium: {
id: 'settings.app.form.openAppLinksInFerdium',
defaultMessage: 'Open app links (like slack://) in Ferdium',
},
reloadAfterResume: {
id: 'settings.app.form.reloadAfterResume',
defaultMessage: 'Reload Ferdium after system resume',
Expand Down Expand Up @@ -435,6 +439,7 @@ class EditSettingsScreen extends Component<
trayDependencySatisfied && Boolean(settingsData.runInBackground),
enableSystemTray,
reloadAfterResume: Boolean(settingsData.reloadAfterResume),
openAppLinksInFerdium: Boolean(settingsData.openAppLinksInFerdium),
reloadAfterResumeTime: Number(settingsData.reloadAfterResumeTime),
startMinimized:
trayDependencySatisfied && Boolean(settingsData.startMinimized),
Expand Down Expand Up @@ -772,6 +777,15 @@ class EditSettingsScreen extends Component<
default: DEFAULT_APP_SETTINGS.enableSystemTray,
type: 'checkbox',
},
openAppLinksInFerdium: {
label: intl.formatMessage(messages.openAppLinksInFerdium),
value: ifUndefined<boolean>(
settings.all.app.openAppLinksInFerdium,
DEFAULT_APP_SETTINGS.openAppLinksInFerdium,
),
default: DEFAULT_APP_SETTINGS.openAppLinksInFerdium,
type: 'checkbox',
},
reloadAfterResume: {
label: intl.formatMessage(messages.reloadAfterResume),
value: ifUndefined<boolean>(
Expand Down
36 changes: 36 additions & 0 deletions src/electron/deepLinking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,21 @@ export function getDeepLinkFromArgs(args: string[]): string | undefined {
return args.find(arg => arg.startsWith(protocolPrefix));
}

/**
* Finds a link Ferdium was asked to open: an http(s) url, or the app link of a
* service such as slack://. Ferdium's own deep links are handled separately.
*/
export function getExternalUrlFromArgs(args: string[]): string | undefined {
return args.find(
arg =>
/^[a-z][\d+.a-z-]*:\/\//i.test(arg) && !arg.startsWith(protocolPrefix),
);
}

export function handleExternalUrl(window: BrowserWindow, url: string): void {
window.webContents.send('openUrlInService', { url });
}

export default function handleDeepLink(
window: BrowserWindow,
rawUrl: string,
Expand All @@ -24,3 +39,24 @@ export default function handleDeepLink(

window.webContents.send('navigateFromDeepLink', { url });
}

/**
* Handles the command-line arguments Ferdium was launched with, or that a second
* instance passed on: a Ferdium deep link navigates, and otherwise an http(s) url
* is opened in the service it belongs to.
*/
export function handleLaunchArgs(window: BrowserWindow, args: string[]): void {
const deepLink = getDeepLinkFromArgs(args);

if (deepLink) {
handleDeepLink(window, deepLink);

return;
}

const externalUrl = getExternalUrlFromArgs(args);

if (externalUrl) {
handleExternalUrl(window, externalUrl);
}
}
101 changes: 101 additions & 0 deletions src/helpers/open-url-helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
interface ServiceWithUrl {
url: string;
}

/**
* What Ferdium knows about a service that a recipe can use to decide whether a
* link belongs to it.
*/
export interface LinkContext {
url: string;
team: string;
linkContext: Record<string, string>;
}

interface ServiceWithRecipe extends ServiceWithUrl {
team: string;
linkContext: Record<string, string>;
recipe: {
resolveLink?: (link: string, context: LinkContext) => string | null;
};
}

function parseHttpUrl(value: string): URL | undefined {
try {
const url = new URL(value);

if (url.protocol !== 'http:' && url.protocol !== 'https:') {
return undefined;
}

return url;
} catch {
return undefined;
}
}

/**
* Finds the service that should open the given http(s) url: the first service
* whose own address has the same host.
*/
export function findServiceForUrl<Service extends ServiceWithUrl>(
services: Service[],
url: string,
): Service | undefined {
const host = parseHttpUrl(url)?.hostname;

if (!host) {
return undefined;
}

return services.find(service => parseHttpUrl(service.url)?.hostname === host);
}

/**
* Finds the service that should open the given link and the url it should load.
* The recipe of a service decides first, so it can claim app links like slack://
* or rewrite a url; otherwise the service with the same host opens the url as is.
*/
export function resolveServiceLink<Service extends ServiceWithRecipe>(
services: Service[],
link: string,
): { service: Service; url: string } | undefined {
for (const service of services) {
const url = service.recipe.resolveLink?.(link, {
url: service.url,
team: service.team,
linkContext: service.linkContext,
});

if (url) {
return { service, url };
}
}

const service = findServiceForUrl(services, link);

return service ? { service, url: link } : undefined;
}

// Protocols Ferdium must never take over: the web itself and its own deep links
const RESERVED_PROTOCOLS = new Set([
'http',
'https',
'file',
'ferdium',
'ferdium-dev',
]);

/**
* The app link protocols (e.g. slack) the recipes of the given services can open,
* each listed once.
*/
export function getAppLinkProtocols(
services: { recipe: { protocols: string[] } }[],
): string[] {
const protocols = services.flatMap(service => service.recipe.protocols);

return [...new Set(protocols)].filter(
protocol => !RESERVED_PROTOCOLS.has(protocol),
);
}
4 changes: 4 additions & 0 deletions src/i18n/locales/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,8 @@
"service.hibernating.message": "This service is currently hibernating.",
"service.screenshare.cancel": "Cancel",
"service.screenshare.loading": "Loading screens and windows",
"service.unmatchedUrl.detail": "{url} doesn't match any of your services.",
"service.unmatchedUrl.title": "No service for this link",
"service.webviewLoader.loading": "Loading {service}",
"services.getStarted": "Get started",
"services.login": "Please login to use Ferdium.",
Expand Down Expand Up @@ -316,6 +318,7 @@
"settings.app.form.minimizeToSystemTray": "Minimize Ferdium to system tray",
"settings.app.form.navigationBarBehaviour": "Navigation bar behaviour",
"settings.app.form.notifyTaskBarOnMessage": "Notify TaskBar/Dock on new message",
"settings.app.form.openAppLinksInFerdium": "Open app links (like slack://) in Ferdium",
"settings.app.form.passwordToggle": "Password toggle",
"settings.app.form.predefinedTodoServer": "Todo Server",
"settings.app.form.privateNotifications": "Don't show message content in notifications",
Expand Down Expand Up @@ -367,6 +370,7 @@
"settings.app.lockInfo": "Password Lock allows you to keep your messages protected.\nUsing Password Lock, you will be prompted to enter your password every time you start Ferdium or lock Ferdium yourself using the lock symbol in the bottom left corner or the shortcut {lockShortcut}.",
"settings.app.lockedPassword": "Password",
"settings.app.lockedPasswordInfo": "Please make sure to set a password you'll remember.\nIf you lose this password, you will have to reinstall Ferdium.",
"settings.app.openAppLinksInFerdiumInfo": "Ferdium becomes the handler for the app links of your services, like the \"Open in app\" button on a Slack web page. Turning this off again is not possible on Linux; remove the handler there with xdg-mime.",
"settings.app.overallTheme": "Overall Theme",
"settings.app.progressbarTheme": "Progressbar Theme",
"settings.app.restart.restartDialogDetail": "You made a change that requires a restart. This will close Ferdium and restart it.",
Expand Down
Loading
Loading