Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support switch plugin on or off #3667

Merged
merged 5 commits into from
Jul 20, 2021
Merged
Show file tree
Hide file tree
Changes from 3 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
9 changes: 2 additions & 7 deletions packages/dashboard/src/initialization/Dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,20 @@ import {
MaskDarkTheme,
useSystemPreferencePalatte,
} from '@masknet/theme'
import { Emitter } from '@servie/events'
import { ErrorBoundary } from '@masknet/shared'

import i18n from 'i18next'
import { I18nextProvider } from 'react-i18next'

import './plugins'
import { startPluginDashboard, createInjectHooksRenderer, useActivatedPluginsDashboard } from '@masknet/plugin-infra'
import './PluginHost'
import { createInjectHooksRenderer, useActivatedPluginsDashboard } from '@masknet/plugin-infra'
import { Pages } from '../pages/routes'
import { useAppearance } from '../pages/Personas/api'
import { Web3Provider } from '@masknet/web3-shared'
import { Web3Context } from '../web3/context'

const PluginRender = createInjectHooksRenderer(useActivatedPluginsDashboard, (x) => x.GlobalInjection)

// TODO: implement
startPluginDashboard({
enabled: { events: new Emitter(), isEnabled: () => true },
})
export default function DashboardRoot() {
const settings = useAppearance()
const mode = useSystemPreferencePalatte()
Expand Down
19 changes: 19 additions & 0 deletions packages/dashboard/src/initialization/PluginHost.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import './plugins'

import { Emitter } from '@servie/events'
import { startPluginDashboard, Plugin } from '@masknet/plugin-infra'
import { Services, Messages } from '../API'

const PluginHost: Plugin.__Host.Host = {
enabled: {
events: new Emitter(),
isEnabled: (id) => {
return Services.Settings.isPluginEnabled(id)
},
},
}
setTimeout(() => {
Messages.events.pluginEnabled.on((id) => PluginHost.enabled.events.emit('enabled', id))
Messages.events.pluginDisabled.on((id) => PluginHost.enabled.events.emit('disabled', id))
startPluginDashboard(PluginHost)
})
2 changes: 1 addition & 1 deletion packages/maskbook/src/_locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@
"error_gas_feed_exceeds": "Error occurred when invoking the smart contract.",
"error_insufficient_balance": "Your allowance in this wallet is not sufficient to do that.",
"error_unknown": "Unknown Error.",
"eanble_or_disable_plugin": "enable/disable plugin",
"enable_or_disable_plugin": "enable/disable plugin",
"feedback": "Feedback",
"fingerprint": "Fingerprint",
"buy": "Buy",
Expand Down
2 changes: 1 addition & 1 deletion packages/maskbook/src/_locales/ja/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@
"error_gas_feed_exceeds": "スマートコントラクト呼び出し時にエラーが起こったため、取引を実行できませんでした。",
"error_insufficient_balance": "ウォレットの残高が不足しています。",
"error_unknown": "不明のエラー",
"eanble_or_disable_plugin": "プラグインを有効/無効化する",
"enable_or_disable_plugin": "プラグインを有効/無効化する",
"feedback": "フィードバック",
"fingerprint": "指紋(フィンガープリント)",
"buy": "購入する",
Expand Down
2 changes: 1 addition & 1 deletion packages/maskbook/src/_locales/ko/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@
"error_gas_feed_exceeds": "스마트 컨트랙트를 활성화할 때 오류가 생겼습니다.",
"error_insufficient_balance": "이 월렛의 잔액이 부족합니다.",
"error_unknown": "미지의 오류",
"eanble_or_disable_plugin": "플러그인 사용/사용 안 함",
"enable_or_disable_plugin": "플러그인 사용/사용 안 함",
"feedback": "피드백",
"fingerprint": "지문",
"buy": "매수하기",
Expand Down
2 changes: 1 addition & 1 deletion packages/maskbook/src/_locales/zh/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@
"error_gas_feed_exceeds": "呼叫智慧合約時出錯。",
"error_insufficient_balance": "你錢包裡的餘額不足以完成這個操作。",
"error_unknown": "未知的錯誤。",
"eanble_or_disable_plugin": "開啟/關閉插件",
"enable_or_disable_plugin": "開啟/關閉插件",
"feedback": "提供建議",
"fingerprint": "指紋",
"buy": "購買",
Expand Down
2 changes: 0 additions & 2 deletions packages/maskbook/src/database/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import './migrate/index'
import './tasks/index'
export * from './helpers/avatar'
export * from './helpers/group'
export * from './Persona/helpers'
Expand Down
7 changes: 0 additions & 7 deletions packages/maskbook/src/database/tasks/index.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { createAvatarDBAccess, queryAvatarOutdatedDB, deleteAvatarsDB } from '../avatar'
import { createTransaction } from '../helpers/openDB'
import { consistentPersonaDBWriteAccess } from '../Persona/Persona.db'
import { Identifier, ProfileIdentifier, GroupIdentifier } from '../type'
import { IdentifierMap } from '../IdentifierMap'
import { createAvatarDBAccess, queryAvatarOutdatedDB, deleteAvatarsDB } from '../../../../database/avatar'
import { createTransaction } from '../../../../database/helpers/openDB'
import { consistentPersonaDBWriteAccess } from '../../../../database/Persona/Persona.db'
import { Identifier, ProfileIdentifier, GroupIdentifier } from '../../../../database/type'
import { IdentifierMap } from '../../../../database/IdentifierMap'
import { untilDocumentReady } from '../../../../utils'

async function cleanAvatarDB(anotherList: IdentifierMap<ProfileIdentifier | GroupIdentifier, undefined>) {
const t = createTransaction(await createAvatarDBAccess(), 'readwrite')('avatars', 'metadata')
Expand All @@ -13,8 +14,10 @@ async function cleanAvatarDB(anotherList: IdentifierMap<ProfileIdentifier | Grou
await deleteAvatarsDB(Array.from(anotherList.keys()), t)
}

export async function cleanProfileWithNoLinkedPersona() {
setTimeout(cleanProfileWithNoLinkedPersona, 1000 * 60 * 60 * 24 * 7 /** days */)
export default async function cleanProfileWithNoLinkedPersona(signal: AbortSignal) {
await untilDocumentReady()
const timeout = setTimeout(cleanProfileWithNoLinkedPersona, 1000 * 60 * 60 * 24 /** 1 day */)
signal.addEventListener('abort', () => clearTimeout(timeout))

const cleanedList = new IdentifierMap<ProfileIdentifier | GroupIdentifier, undefined>(
new Map(),
Expand All @@ -23,6 +26,7 @@ export async function cleanProfileWithNoLinkedPersona() {
)
const expired = new Date(Date.now() - 1000 * 60 * 60 * 24 * 14 /** days */)
await consistentPersonaDBWriteAccess(async (t) => {
if (signal.aborted) throw new Error('')
Jack-Works marked this conversation as resolved.
Show resolved Hide resolved
for await (const x of t.objectStore('profiles')) {
if (x.value.linkedPersona) continue
if (expired < x.value.updatedAt) continue
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
/* eslint-disable import/no-deprecated */
/// <reference path="../global.d.ts" />
/**
* @deprecated
* This database is deprecated since Mask 1.8.10
Expand All @@ -24,12 +23,12 @@
* @type {Record<string, AESJsonWebKey>} Record of <userId, CryptoKey>
* @keys outline, string, which means network.
*/
import { GroupIdentifier, Identifier, ProfileIdentifier } from '../type'
import { GroupIdentifier, Identifier, ProfileIdentifier } from '../../../../database/type'
import { DBSchema, openDB } from 'idb/with-async-ittr-cjs'
import { JsonWebKeyToCryptoKey, getKeyParameter } from '../../utils/type-transform/CryptoKey-JsonWebKey'
import { JsonWebKeyToCryptoKey, getKeyParameter } from '../../../../utils/type-transform/CryptoKey-JsonWebKey'
import { assertEnvironment, Environment } from '@dimensiondev/holoflows-kit'
import { createDBAccess } from '../helpers/openDB'
import type { AESJsonWebKey } from '../../modules/CryptoAlgorithm/interfaces/utils'
import { createDBAccess } from '../../../../database/helpers/openDB'
import type { AESJsonWebKey } from '../../../../modules/CryptoAlgorithm/interfaces/utils'

assertEnvironment(Environment.ManifestBackground)
//#region Type and utils
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { queryUserGroupDatabase } from '../group'
import { GroupIdentifier } from '../type'
import { createDefaultFriendsGroup } from '../helpers/group'
import { queryMyProfiles } from '../../extension/background-script/IdentityService'
import { queryUserGroupDatabase } from '../../../../database/group'
import { GroupIdentifier } from '@masknet/shared'
import { createDefaultFriendsGroup } from '../../UserGroupService'
import { queryMyProfiles } from '../../IdentityService'

/**
* If an identity has no default user group, create one
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { setStorage } from '../../utils/browser.storage'
import { queryPersonasWithPrivateKey } from '../Persona/Persona.db'
import { deletePersona } from '../Persona/helpers'
import { setStorage } from '../../../../utils/browser.storage'
import { queryPersonasWithPrivateKey } from '../../../../database/Persona/Persona.db'
import { deletePersona } from '../../../../database/Persona/helpers'

/**
* There is a bug that when use QR to import key, the private ket lost its secret.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import createUserGroupForOldUsers from './create.user.group.for.old.users'
import fixQrPrivateKeyBug from './fix.qr.private.key.bug'
import migratePeopleToPersona from './people.to.persona'
import { untilDocumentReady } from '../../utils/dom'
import { sideEffect } from '../../utils/side-effects'
import { sideEffect, untilDocumentReady } from '../../../../utils'

sideEffect.then(untilDocumentReady).then(run)
function run() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,10 @@ import {
PersonRecordPublic,
PersonRecordPublicPrivate,
} from './_deprecated_people_db'
import * as persona from '../Persona/Persona.db'
import { ECKeyIdentifier, ECKeyIdentifierFromCryptoKey, ProfileIdentifier } from '../type'
import { IdentifierMap } from '../IdentifierMap'
import { CryptoKeyToJsonWebKey } from '../../utils/type-transform/CryptoKey-JsonWebKey'
import type { AESJsonWebKey } from '../../modules/CryptoAlgorithm/interfaces/utils'
import * as persona from '../../../../database/Persona/Persona.db'
import { ECKeyIdentifier, ProfileIdentifier, IdentifierMap, AESJsonWebKey } from '@masknet/shared'
import { ECKeyIdentifierFromCryptoKey } from '../../../../database/type'
import { CryptoKeyToJsonWebKey } from '../../../../utils/type-transform/CryptoKey-JsonWebKey'

export default async function migratePeopleToPersona() {
const myIDs = await getMyIdentitiesDB()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import './index_hmr'
// Add and execute your non-cancelable jobs here. It won't compatible to HMR.
import './PrintBuildFlags'
import './MigrateDatabase'
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as InjectContentScripts from './InjectContentScripts'
import * as NewInstalled from './NewInstalled'
import * as PluginWorker from './StartPluginWorker'
import * as SettingListeners from './SettingListeners'
import * as CleanupProfileDatabase from './DatabaseCleanup/CleanProfileAndAvatar'

type CancelableJob = { default: (signal: AbortSignal) => void }
const CancelableJobs: CancelableJob[] = [
Expand All @@ -13,6 +14,7 @@ const CancelableJobs: CancelableJob[] = [
IsolatedDashboardBridge,
PluginWorker,
SettingListeners,
CleanupProfileDatabase,
]

const abort = new AbortController()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
currentPersonaIdentifier,
languageSettings,
disableOpenNewTabInBackgroundSettings,
currentPluginEnabledStatus,
} from '../../settings/settings'
import { currentDataProviderSettings } from '../../plugins/Trader/settings'
import { queryMyPersonas } from './IdentityService'
Expand Down Expand Up @@ -79,3 +80,6 @@ export async function setCurrentPersonaIdentifier(x: PersonaIdentifier) {
await currentPersonaIdentifier.readyPromise
currentPersonaIdentifier.value = x.toText()
}
export async function isPluginEnabled(id: string) {
return currentPluginEnabledStatus['plugin:' + id].value
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@ import { Flags, useI18N } from '../../../utils'
import { useModal } from '../DashboardDialogs/Base'
import { DashboardPluginDetailDialog } from '../DashboardDialogs/Plugin'

interface Props {
export interface PluginCardProps {
id: string
name: string
icon: React.ReactNode
description?: string
enabled: boolean
onSwitch(): void
canDisable: boolean
}

const useStyles = makeStyles((theme) => ({
Expand Down Expand Up @@ -77,7 +80,7 @@ const useStyles = makeStyles((theme) => ({
},
}))

export default function PluginCard({ id, name, icon, description }: Props) {
export default function PluginCard({ id, name, icon, description, enabled, onSwitch, canDisable }: PluginCardProps) {
const { t } = useI18N()
const classes = useStyles()
const [pluginDetail, openPluginDetail] = useModal(DashboardPluginDetailDialog, {
Expand Down Expand Up @@ -115,12 +118,14 @@ export default function PluginCard({ id, name, icon, description }: Props) {
<Button variant="outlined" size="small" onClick={openPluginDetail}>
{t('details')}
</Button>
{Flags.plugin_switch_enabled ? (
{Flags.plugin_switch_enabled && canDisable ? (
<Switch
className={classes.switch}
color="primary"
size="small"
inputProps={{ 'aria-label': t('eanble_or_disable_plugin') }}
inputProps={{ 'aria-label': t('enable_or_disable_plugin') }}
checked={enabled}
onChange={() => onSwitch()}
/>
) : null}
</div>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { makeStyles } from '@material-ui/core/styles'
import { useI18N } from '../../../utils'
import PluginCard from '../DashboardComponents/PluginCard'
import { useI18N, useValueRef } from '../../../utils'
import PluginCard, { PluginCardProps } from '../DashboardComponents/PluginCard'

import DashboardRouterContainer from './Container'
import { useActivatedPluginsSNSAdaptor } from '@masknet/plugin-infra'
import { useRegisteredPlugins } from '@masknet/plugin-infra'
import { currentPluginEnabledStatus } from '../../../settings/settings'

const useStyles = makeStyles((theme) => ({
root: {
Expand All @@ -29,23 +30,32 @@ const useStyles = makeStyles((theme) => ({
export default function DashboardSettingsRouter() {
const { t } = useI18N()
const classes = useStyles()
const plugins = useActivatedPluginsSNSAdaptor()
const plugins = useRegisteredPlugins()

return (
<DashboardRouterContainer title={t('plugins')}>
<ul className={classes.pluginList}>
{plugins.map((plugin) => (
<li className={classes.pluginItem} key={plugin.ID}>
<PluginCard
key={plugin.ID}
name={plugin.name.fallback}
id={plugin.ID}
icon={plugin.icon}
description={plugin.description?.fallback}
/>
</li>
))}
{plugins
.filter((x) => !x.management?.internal)
.map((plugin) => (
<li className={classes.pluginItem} key={plugin.ID}>
<PluginCardContainer
key={plugin.ID}
name={plugin.name.fallback}
id={plugin.ID}
icon={plugin.icon}
description={plugin.description?.fallback}
canDisable={!plugin.management?.alwaysOn}
/>
</li>
))}
</ul>
</DashboardRouterContainer>
)
}

function PluginCardContainer(props: Omit<PluginCardProps, 'enabled' | 'onSwitch'>) {
const ref = currentPluginEnabledStatus['plugin:' + props.id]
const status = useValueRef(ref)
return <PluginCard {...props} enabled={status} onSwitch={() => (ref.value = !status)} />
}
30 changes: 23 additions & 7 deletions packages/maskbook/src/plugin-infra/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,30 @@ import './register'

import type { Plugin } from '@masknet/plugin-infra'
import { Emitter } from '@servie/events'

import { currentPluginEnabledStatus } from '../settings/settings'
import { isEnvironment, Environment } from '@dimensiondev/holoflows-kit'
import { MaskMessage } from '../utils'
export function createPluginHost(signal?: AbortSignal): Plugin.__Host.Host {
return {
signal,
// TODO: need a place to store enabled/disabled status of a plugin id
enabled: {
isEnabled: (id) => true,
events: new Emitter(),
const listening = new Set<string>()
const enabled: Plugin.__Host.EnabledStatusReporter = {
isEnabled: (id) => {
const status = currentPluginEnabledStatus['plugin:' + id]
if (!listening.has(id)) {
listening.add(id)
const undo = status.addListener((newVal) => enabled.events.emit(newVal ? 'enabled' : 'disabled', id))
signal?.addEventListener('abort', undo)

// TODO: move it elsewhere.
if (isEnvironment(Environment.ManifestBackground)) {
status.addListener((newVal) => {
if (newVal) MaskMessage.events.pluginEnabled.sendToAll(id)
else MaskMessage.events.pluginDisabled.sendToAll(id)
})
}
}
return status.value
},
events: new Emitter(),
}
return { signal, enabled }
}
Loading