// SPDX-License-Identifier: AGPL-3.0-or-later package main import ( "errors" "log/slog" "net/url" "regexp" "slices" "strings" "sync" ) // deepLinkScheme is registered with the OS by the installers (build/config.yml). const deepLinkScheme = "docwell" // openRouteEvent carries an app route (e.g. "/p/abc123") to the frontend. const openRouteEvent = "docwell:open-route" // deepLinkRoutes are the app routes a link may open: a page or a space. var deepLinkRoutes = []string{"p", "s"} var recordID = regexp.MustCompile(`^[A-Za-z0-9]{1,32}$`) // routeFromDeepLink turns docwell://p/ into the app route /p/. // Anything else is refused: links come from other apps and web pages, so // they may only navigate, never change settings such as the server address. func routeFromDeepLink(raw string) (string, error) { u, err := url.Parse(strings.TrimSpace(raw)) if err != nil || !strings.EqualFold(u.Scheme, deepLinkScheme) { return "", errors.New("not a docwell:// link") } if u.Host == "" && strings.Trim(u.Path, "/") == "" { return "/", nil } parts := strings.Split(strings.Trim(u.Host+u.Path, "/"), "/") if len(parts) != 2 || !slices.Contains(deepLinkRoutes, parts[0]) || !recordID.MatchString(parts[1]) { return "", errors.New("unsupported docwell:// link") } return "/" + parts[0] + "/" + parts[1], nil } // deepLinkFromArgs finds a docwell:// link among command-line arguments, // which is how Windows and Linux pass it to the app. func deepLinkFromArgs(args []string) (string, bool) { for _, a := range args { if strings.HasPrefix(strings.ToLower(a), deepLinkScheme+"://") { return a, true } } return "", false } // LinkService routes docwell:// links into the app. It is bound to the // frontend, which asks for a link that arrived before it was listening (the // one the app was launched with) and then follows openRouteEvent. type LinkService struct { mu sync.Mutex pending string // emit sends a route to the frontend; set once the app exists. emit func(route string) // listening turns true when the frontend first calls TakePending. listening bool } // open handles a link from the OS. Bad links are logged and ignored. func (s *LinkService) open(raw string) { route, err := routeFromDeepLink(raw) if err != nil { slog.Warn("ignoring link", "link", raw, "err", err) return } slog.Info("opening link", "route", route) s.mu.Lock() var emit func(string) if s.listening { emit = s.emit } else { s.pending = route } s.mu.Unlock() if emit != nil { emit(route) } } // TakePending returns the route the app was opened with, once. The frontend // calls it after subscribing to openRouteEvent, so later links are emitted. func (s *LinkService) TakePending() string { s.mu.Lock() defer s.mu.Unlock() s.listening = s.emit != nil route := s.pending s.pending = "" return route } func (s *LinkService) setEmitter(emit func(route string)) { s.mu.Lock() defer s.mu.Unlock() s.emit = emit }