configurable host overrides

This commit is contained in:
Tobias Jacksteit
2020-05-29 23:43:34 +08:00
parent f763553739
commit 6bfd4c2e6f
7 changed files with 158 additions and 34 deletions

View File

@@ -3,18 +3,23 @@ import { observable } from "mobx"
import { observer } from "mobx-react" import { observer } from "mobx-react"
import { isChrome, getSettings, setStorage } from "utils/browser" import { isChrome, getSettings, setStorage } from "utils/browser"
import ApiClient from "api/Client" import ApiClient from "api/Client"
import remoteServices from "../remoteServices";
import { map } from "lodash"
import { getHostOverridesFromSettings } from "../utils/settings"
@observer @observer
class Options extends Component { class Options extends Component {
@observable subdomain = "" @observable subdomain = ""
@observable apiKey = "" @observable apiKey = ""
@observable hostOverrides = {}
@observable errorMessage = null @observable errorMessage = null
@observable isSuccess = false @observable isSuccess = false
componentDidMount() { componentDidMount() {
getSettings(false).then(({ subdomain, apiKey }) => { getSettings(false).then((storeData) => {
this.subdomain = subdomain || "" this.subdomain = storeData.subdomain || ""
this.apiKey = apiKey || "" this.apiKey = storeData.apiKey || ""
this.hostOverrides = getHostOverridesFromSettings(storeData) || {}
}) })
} }
@@ -22,13 +27,19 @@ class Options extends Component {
this[event.target.name] = event.target.value.trim() this[event.target.name] = event.target.value.trim()
} }
onChangeHostOverrides = event => {
this.hostOverrides[event.target.name] = event.target.value.trim()
}
handleSubmit = _event => { handleSubmit = _event => {
this.isSuccess = false this.isSuccess = false
this.errorMessage = null this.errorMessage = null
setStorage({ setStorage({
subdomain: this.subdomain, subdomain: this.subdomain,
apiKey: this.apiKey, apiKey: this.apiKey,
settingTimeTrackingHHMM: false, settingTimeTrackingHHMM: false,
...this.hostOverrides,
}).then(() => { }).then(() => {
const { version } = chrome.runtime.getManifest() const { version } = chrome.runtime.getManifest()
const apiClient = new ApiClient({ const apiClient = new ApiClient({
@@ -93,6 +104,24 @@ class Options extends Component {
Den API-Schlüssel findest du in deinem Profil unter "Integrationen". Den API-Schlüssel findest du in deinem Profil unter "Integrationen".
</p> </p>
</div> </div>
<hr />
{map(
remoteServices,
(remoteService, remoteServiceKey) =>
remoteService.allowHostOverride && (
<div className="form-group" key={remoteServiceKey}>
<label>Override Host: {remoteServiceKey}</label>
<input
type="text"
name={`hostOverrides:${remoteServiceKey}`}
value={this.hostOverrides[`hostOverrides:${remoteServiceKey}`]}
placeholder={remoteService.host}
onKeyDown={this.handleInputKeyDown}
onChange={this.onChangeHostOverrides}
/>
</div>
),
)}
<button className="moco-bx-btn" onClick={this.handleSubmit}> <button className="moco-bx-btn" onClick={this.handleSubmit}>
OK OK
</button> </button>

View File

@@ -7,11 +7,18 @@ import { createServiceFinder } from "utils/urlMatcher"
import remoteServices from "./remoteServices" import remoteServices from "./remoteServices"
import { ContentMessenger } from "utils/messaging" import { ContentMessenger } from "utils/messaging"
import "../css/content.scss" import "../css/content.scss"
import { getSettings } from "./utils/browser"
import { getHostOverridesFromSettings } from "./utils/settings"
const popupRef = createRef() const popupRef = createRef()
const findService = createServiceFinder(remoteServices)(document)
chrome.runtime.onConnect.addListener(function(port) { let findService
getSettings().then((settings) => {
const hostOverrides = getHostOverridesFromSettings(settings, true)
findService = createServiceFinder(remoteServices, hostOverrides)(document)
})
chrome.runtime.onConnect.addListener(function (port) {
const messenger = new ContentMessenger(port) const messenger = new ContentMessenger(port)
function clickHandler(event) { function clickHandler(event) {
@@ -42,10 +49,10 @@ chrome.runtime.onConnect.addListener(function(port) {
leave={{ opacity: "0" }} leave={{ opacity: "0" }}
config={config.stiff} config={config.stiff}
> >
{service => {(service) =>
service && service &&
// eslint-disable-next-line react/display-name // eslint-disable-next-line react/display-name
(props => ( ((props) => (
<animated.div className="moco-bx-bubble" style={{ ...props, ...service.position }}> <animated.div className="moco-bx-bubble" style={{ ...props, ...service.position }}>
<Bubble <Bubble
key={service.url} key={service.url}

View File

@@ -9,9 +9,10 @@ const projectIdentifierBySelector = selector => document =>
export default { export default {
asana: { asana: {
name: "asana", name: "asana",
host: "https://app.asana.com",
urlPatterns: [ urlPatterns: [
[/^https:\/\/app.asana.com\/0\/([^/]+)\/(\d+)/, ["domainUserId", "id"]], [/^__HOST__\/0\/([^/]+)\/(\d+)/, ["domainUserId", "id"]],
[/^https:\/\/app.asana.com\/0\/search\/([^/]+)\/(\d+)/, ["domainUserId", "id"]], [/^__HOST__\/0\/search\/([^/]+)\/(\d+)/, ["domainUserId", "id"]],
], ],
description: document => description: document =>
document.querySelector(".ItemRow--highlighted textarea")?.textContent?.trim() || document.querySelector(".ItemRow--highlighted textarea")?.textContent?.trim() ||
@@ -19,32 +20,38 @@ export default {
document.querySelector(".SingleTaskPane textarea")?.textContent?.trim() || document.querySelector(".SingleTaskPane textarea")?.textContent?.trim() ||
document.querySelector(".SingleTaskTitleInput-taskName textarea")?.textContent?.trim(), document.querySelector(".SingleTaskTitleInput-taskName textarea")?.textContent?.trim(),
projectId: projectIdentifierBySelector(".TopbarPageHeaderStructure-titleRow h1"), projectId: projectIdentifierBySelector(".TopbarPageHeaderStructure-titleRow h1"),
allowHostOverride: false,
}, },
"github-pr": { "github-pr": {
name: "github", name: "github",
urlPatterns: ["https\\://github.com/:org/:repo/pull/:id(/:tab)"], host: "https://github.com",
urlPatterns: ["__HOST__/:org/:repo/pull/:id(/:tab)"],
id: (document, service, { org, repo, id }) => [service.key, org, repo, id].join("."), id: (document, service, { org, repo, id }) => [service.key, org, repo, id].join("."),
description: document => document.querySelector(".js-issue-title")?.textContent?.trim(), description: document => document.querySelector(".js-issue-title")?.textContent?.trim(),
projectId: projectIdentifierBySelector(".js-issue-title"), projectId: projectIdentifierBySelector(".js-issue-title"),
allowHostOverride: true,
}, },
"github-issue": { "github-issue": {
name: "github", name: "github",
urlPatterns: ["https\\://github.com/:org/:repo/issues/:id"], host: "https://github.com",
urlPatterns: ["__HOST__/:org/:repo/issues/:id"],
id: (document, service, { org, repo, id }) => [service.key, org, repo, id].join("."), id: (document, service, { org, repo, id }) => [service.key, org, repo, id].join("."),
description: (document, service, { org, repo, id }) => description: (document, service, { org, repo, id }) =>
document.querySelector(".js-issue-title")?.textContent?.trim(), document.querySelector(".js-issue-title")?.textContent?.trim(),
projectId: projectIdentifierBySelector(".js-issue-title"), projectId: projectIdentifierBySelector(".js-issue-title"),
allowHostOverride: true,
}, },
jira: { jira: {
name: "jira", name: "jira",
host: "https://:org.atlassian.net",
urlPatterns: [ urlPatterns: [
"https\\://:org.atlassian.net/secure/RapidBoard.jspa", "__HOST__/secure/RapidBoard.jspa",
"https\\://:org.atlassian.net/browse/:id", "__HOST__/browse/:id",
"https\\://:org.atlassian.net/jira/software/projects/:projectId/boards/:board", "__HOST__/jira/software/projects/:projectId/boards/:board",
"https\\://:org.atlassian.net/jira/software/projects/:projectId/boards/:board/backlog", "__HOST__/jira/software/projects/:projectId/boards/:board/backlog",
], ],
queryParams: { queryParams: {
id: "selectedIssue", id: "selectedIssue",
@@ -59,11 +66,13 @@ export default {
document.querySelector(".ghx-selected .ghx-summary")?.textContent?.trim() document.querySelector(".ghx-selected .ghx-summary")?.textContent?.trim()
return `#${id} ${title || ""}` return `#${id} ${title || ""}`
}, },
allowHostOverride: true,
}, },
meistertask: { meistertask: {
name: "meistertask", name: "meistertask",
urlPatterns: ["https\\://www.meistertask.com/app/task/:id/:slug"], host: "https://www.meistertask.com",
urlPatterns: ["/app/task/:id/:slug"],
description: document => { description: document => {
const json = document.getElementById("mt-toggl-data")?.dataset?.togglJson || "{}" const json = document.getElementById("mt-toggl-data")?.dataset?.togglJson || "{}"
const data = JSON.parse(json) const data = JSON.parse(json)
@@ -75,30 +84,36 @@ export default {
const match = data.taskName?.match(projectRegex) || data.projectName?.match(projectRegex) const match = data.taskName?.match(projectRegex) || data.projectName?.match(projectRegex)
return match && match[1] return match && match[1]
}, },
allowHostOverride: false,
}, },
trello: { trello: {
name: "trello", name: "trello",
urlPatterns: ["https\\://trello.com/c/:id/:title"], host: "https://trello.com",
urlPatterns: ["__HOST__/c/:id/:title"],
description: (document, service, { title }) => description: (document, service, { title }) =>
document.querySelector(".js-title-helper")?.textContent?.trim() || title, document.querySelector(".js-title-helper")?.textContent?.trim() || title,
projectId: document => projectId: document =>
projectIdentifierBySelector(".js-title-helper")(document) || projectIdentifierBySelector(".js-title-helper")(document) ||
projectIdentifierBySelector(".js-board-editing-target")(document), projectIdentifierBySelector(".js-board-editing-target")(document),
allowHostOverride: false,
}, },
youtrack: { youtrack: {
name: "youtrack", name: "youtrack",
urlPatterns: ["https\\://:org.myjetbrains.com/youtrack/issue/:id"], host: "https://:org.myjetbrains.com",
urlPatterns: ["__HOST__/youtrack/issue/:id"],
description: document => document.querySelector("yt-issue-body h1")?.textContent?.trim(), description: document => document.querySelector("yt-issue-body h1")?.textContent?.trim(),
projectId: projectIdentifierBySelector("yt-issue-body h1"), projectId: projectIdentifierBySelector("yt-issue-body h1"),
allowHostOverride: true,
}, },
wrike: { wrike: {
name: "wrike", name: "wrike",
host: "https://www.wrike.com",
urlPatterns: [ urlPatterns: [
"https\\://www.wrike.com/workspace.htm#path=mywork", "__HOST__/workspace.htm#path=mywork",
"https\\://www.wrike.com/workspace.htm#path=folder", "__HOST__/workspace.htm#path=folder",
"https\\://app-eu.wrike.com/workspace.htm#path=mywork", "https\\://app-eu.wrike.com/workspace.htm#path=mywork",
"https\\://app-eu.wrike.com/workspace.htm#path=folder", "https\\://app-eu.wrike.com/workspace.htm#path=folder",
], ],
@@ -107,39 +122,46 @@ export default {
}, },
description: document => document.querySelector(".title-field-ghost")?.textContent?.trim(), description: document => document.querySelector(".title-field-ghost")?.textContent?.trim(),
projectId: projectIdentifierBySelector(".header-title__main"), projectId: projectIdentifierBySelector(".header-title__main"),
allowHostOverride: false,
}, },
wunderlist: { wunderlist: {
name: "wunderlist", name: "wunderlist",
urlPatterns: ["https\\://www.wunderlist.com/(webapp)#/tasks/:id(/*)"], host: "https://www.wunderlist.com",
urlPatterns: ["__HOST__/(webapp)#/tasks/:id(/*)"],
description: document => description: document =>
document document
.querySelector(".taskItem.selected .taskItem-titleWrapper-title") .querySelector(".taskItem.selected .taskItem-titleWrapper-title")
?.textContent?.trim(), ?.textContent?.trim(),
projectId: projectIdentifierBySelector(".taskItem.selected .taskItem-titleWrapper-title"), projectId: projectIdentifierBySelector(".taskItem.selected .taskItem-titleWrapper-title"),
allowHostOverride: false,
}, },
"gitlab-mr": { "gitlab-mr": {
name: "gitlab", name: "gitlab",
host: "https://gitlab.com",
urlPatterns: [ urlPatterns: [
"https\\://gitlab.com/:org/:group/:projectId/-/merge_requests/:id", "__HOST__/:org/:group/:projectId/-/merge_requests/:id",
"https\\://gitlab.com/:org/:projectId/-/merge_requests/:id", "__HOST__/:org/:projectId/-/merge_requests/:id",
], ],
description: (document, service, { id }) => { description: (document, service, { id }) => {
const title = document.querySelector("h2.title")?.textContent?.trim() const title = document.querySelector("h2.title")?.textContent?.trim()
return `#${id} ${title || ""}`.trim() return `#${id} ${title || ""}`.trim()
}, },
allowHostOverride: true,
}, },
"gitlab-issues": { "gitlab-issues": {
name: "gitlab", name: "gitlab",
host: "https://gitlab.com",
urlPatterns: [ urlPatterns: [
"https\\://gitlab.com/:org/:group/:projectId/-/issues/:id", "__HOST__/:org/:group/:projectId/-/issues/:id",
"https\\://gitlab.com/:org/:projectId/-/issues/:id", "__HOST__/:org/:projectId/-/issues/:id",
], ],
description: (document, service, { id }) => { description: (document, service, { id }) => {
const title = document.querySelector("h2.title")?.textContent?.trim() const title = document.querySelector("h2.title")?.textContent?.trim()
return `#${id} ${title || ""}`.trim() return `#${id} ${title || ""}`.trim()
}, },
allowHostOverride: true,
}, },
} }

View File

@@ -1,11 +1,14 @@
import { head } from "lodash/fp" import { head } from "lodash/fp"
import remoteServices from "../remoteServices"
export const isChrome = () => typeof browser === "undefined" && chrome export const isChrome = () => typeof browser === "undefined" && chrome
export const isFirefox = () => typeof browser !== "undefined" && chrome export const isFirefox = () => typeof browser !== "undefined" && chrome
const DEFAULT_SUBDOMAIN = "unset" const DEFAULT_SUBDOMAIN = "unset"
export const getSettings = (withDefaultSubdomain = true) => { export const getSettings = (withDefaultSubdomain = true) => {
const keys = ["subdomain", "apiKey", "settingTimeTrackingHHMM"] const keys = ["subdomain", "apiKey", "settingTimeTrackingHHMM",
...Object.keys(remoteServices).map(key => `hostOverrides:${key}`)]
const { version } = chrome.runtime.getManifest() const { version } = chrome.runtime.getManifest()
if (isChrome()) { if (isChrome()) {
return new Promise(resolve => { return new Promise(resolve => {

View File

@@ -11,8 +11,13 @@ import { get, forEach, reject, isNil } from "lodash/fp"
import { createMatcher } from "utils/urlMatcher" import { createMatcher } from "utils/urlMatcher"
import remoteServices from "remoteServices" import remoteServices from "remoteServices"
import { queryTabs, isBrowserTab, getSettings, setStorage } from "utils/browser" import { queryTabs, isBrowserTab, getSettings, setStorage } from "utils/browser"
import { getHostOverridesFromSettings } from "./settings"
const matcher = createMatcher(remoteServices) let matcher
getSettings().then((settings) => {
const hostOverrides = getHostOverridesFromSettings(settings, true)
matcher = createMatcher(remoteServices, hostOverrides)
})
export function tabUpdated(tab, { messenger, settings }) { export function tabUpdated(tab, { messenger, settings }) {
messenger.connectTab(tab) messenger.connectTab(tab)

17
src/js/utils/settings.js Normal file
View File

@@ -0,0 +1,17 @@
import { filter, fromPairs, map, toPairs } from "lodash"
export const getHostOverridesFromSettings = (settings, removePrefix) => {
return fromPairs(
map(
filter(toPairs(settings), (item) => {
return item[0].indexOf("hostOverrides") !== -1
}),
(item) => {
if (removePrefix) {
item[0] = item[0].replace("hostOverrides:", "")
}
return item
},
),
)
}

View File

@@ -1,5 +1,5 @@
import UrlPattern from "url-pattern" import UrlPattern from "url-pattern"
import { isFunction, isUndefined, compose, toPairs, map, pipe, isNil } from "lodash/fp" import { isFunction, isUndefined, compose, toPairs, map, pipe, isNil, convert } from "lodash/fp"
import { asArray } from "./index" import { asArray } from "./index"
import queryString from "query-string" import queryString from "query-string"
@@ -39,15 +39,36 @@ const createEvaluator = args => fnOrValue => {
return fnOrValue return fnOrValue
} }
const prepareHostForRegExp = (host) => {
if (isUndefined(host)) {
return
}
return host.replace(":", "\\:")//.replace(/\//g, "\\/")
}
const replaceHostInPattern = (host, pattern) => {
if(typeof pattern === "string") {
return pattern.replace("__HOST__", prepareHostForRegExp(host))
} else if(pattern instanceof RegExp) {
return new RegExp(pattern.source.replace("__HOST__", prepareHostForRegExp(host)))
} else {
console.error("Invalid type for pattern %v, no host replacement performed", pattern)
return pattern
}
}
const parseServices = compose( const parseServices = compose(
map(([key, config]) => ({ map(([key, config]) => ({
...config, ...config,
key, key,
patterns: config.urlPatterns.map(pattern => { patterns: config.urlPatterns.map(pattern => {
if (Array.isArray(pattern)) { if (Array.isArray(pattern)) {
return new UrlPattern(...pattern) return new UrlPattern(
...pattern.map((p, index) => (index === 0 ? replaceHostInPattern(config.host, p) : p)),
)
} }
return new UrlPattern(pattern) return new UrlPattern(replaceHostInPattern(config.host, pattern))
}), }),
})), })),
toPairs, toPairs,
@@ -72,8 +93,28 @@ export const createEnhancer = document => service => {
} }
} }
export const createMatcher = remoteServices => { const applyHostOverrides = (remoteServices, hostOverrides) => {
const services = parseServices(remoteServices) let appliedRemoteServices = Object.assign(remoteServices)
if (isUndefined(hostOverrides)) {
console.error("No overrides found.")
return remoteServices
}
Object.keys(remoteServices).forEach((key) => {
const remoteService = remoteServices[key];
appliedRemoteServices[key] = {
...remoteService,
key,
host: (hostOverrides && hostOverrides[key]) || remoteService.host,
}
})
return appliedRemoteServices
}
export const createMatcher = (remoteServices, hostOverrides) => {
const services = parseServices(applyHostOverrides(remoteServices, hostOverrides))
return tabUrl => { return tabUrl => {
const { origin, pathname, hash, query } = parseUrl(tabUrl) const { origin, pathname, hash, query } = parseUrl(tabUrl)
const url = `${origin}${pathname}${hash}` const url = `${origin}${pathname}${hash}`
@@ -99,8 +140,8 @@ export const createMatcher = remoteServices => {
} }
} }
export const createServiceFinder = remoteServices => document => { export const createServiceFinder = (remoteServices, hostOverrides) => document => {
const matcher = createMatcher(remoteServices) const matcher = createMatcher(remoteServices, hostOverrides)
const enhancer = createEnhancer(document) const enhancer = createEnhancer(document)
return pipe( return pipe(
matcher, matcher,