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

wip: ga #15451

Draft
wants to merge 12 commits into
base: develop
Choose a base branch
from
Draft

wip: ga #15451

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
16 changes: 16 additions & 0 deletions packages/backend/migration/1739006797620-GoogleAnalytics.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/

export class GoogleAnalytics1739006797620 {
name = 'GoogleAnalytics1739006797620'

async up(queryRunner) {
await queryRunner.query(`ALTER TABLE "meta" ADD "googleAnalyticsMeasurementId" character varying(64)`);
}

async down(queryRunner) {
await queryRunner.query(`ALTER TABLE "meta" DROP COLUMN "googleAnalyticsMeasurementId"`);
}
}
1 change: 1 addition & 0 deletions packages/backend/src/core/entities/MetaEntityService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ export class MetaEntityService {
enableTurnstile: instance.enableTurnstile,
turnstileSiteKey: instance.turnstileSiteKey,
enableTestcaptcha: instance.enableTestcaptcha,
googleAnalyticsMeasurementId: instance.googleAnalyticsMeasurementId,
swPublickey: instance.swPublicKey,
themeColor: instance.themeColor,
mascotImageUrl: instance.mascotImageUrl ?? '/assets/ai.png',
Expand Down
6 changes: 6 additions & 0 deletions packages/backend/src/models/Meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -658,4 +658,10 @@ export class MiMeta {
default: '{}',
})
public federationHosts: string[];

@Column('varchar', {
length: 64,
nullable: true,
})
public googleAnalyticsMeasurementId: string | null;
}
4 changes: 4 additions & 0 deletions packages/backend/src/models/json-schema/meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,10 @@ export const packedMetaLiteSchema = {
type: 'boolean',
optional: false, nullable: false,
},
googleAnalyticsMeasurementId: {
type: 'string',
optional: false, nullable: true,
},
swPublickey: {
type: 'string',
optional: false, nullable: true,
Expand Down
5 changes: 5 additions & 0 deletions packages/backend/src/server/api/endpoints/admin/meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ export const meta = {
type: 'boolean',
optional: false, nullable: false,
},
googleAnalyticsMeasurementId: {
type: 'string',
optional: false, nullable: true,
},
swPublickey: {
type: 'string',
optional: false, nullable: true,
Expand Down Expand Up @@ -572,6 +576,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
enableTurnstile: instance.enableTurnstile,
turnstileSiteKey: instance.turnstileSiteKey,
enableTestcaptcha: instance.enableTestcaptcha,
googleAnalyticsMeasurementId: instance.googleAnalyticsMeasurementId,
swPublickey: instance.swPublicKey,
themeColor: instance.themeColor,
mascotImageUrl: instance.mascotImageUrl,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ export const paramDef = {
turnstileSiteKey: { type: 'string', nullable: true },
turnstileSecretKey: { type: 'string', nullable: true },
enableTestcaptcha: { type: 'boolean' },
googleAnalyticsMeasurementId: { type: 'string', nullable: true },
sensitiveMediaDetection: { type: 'string', enum: ['none', 'all', 'local', 'remote'] },
sensitiveMediaDetectionSensitivity: { type: 'string', enum: ['medium', 'low', 'high', 'veryLow', 'veryHigh'] },
setSensitiveFlagAutomatically: { type: 'boolean' },
Expand Down Expand Up @@ -371,6 +372,12 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
set.enableTestcaptcha = ps.enableTestcaptcha;
}

if (ps.googleAnalyticsMeasurementId !== undefined) {
// 空文字列をnullにしたいので??は使わない
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
set.googleAnalyticsMeasurementId = ps.googleAnalyticsMeasurementId || null;
}

if (ps.sensitiveMediaDetection !== undefined) {
set.sensitiveMediaDetection = ps.sensitiveMediaDetection;
}
Expand Down
2 changes: 2 additions & 0 deletions packages/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"lint": "pnpm typecheck && pnpm eslint"
},
"dependencies": {
"@analytics/google-analytics": "^1.1.0",
"@discordapp/twemoji": "15.1.0",
"@github/webauthn-json": "2.1.1",
"@mcaptcha/vanilla-glue": "0.1.0-alpha-3",
Expand All @@ -29,6 +30,7 @@
"@vitejs/plugin-vue": "5.2.1",
"@vue/compiler-sfc": "3.5.13",
"aiscript-vscode": "github:aiscript-dev/aiscript-vscode#v0.1.15",
"analytics": "^0.8.16",
"astring": "1.9.0",
"broadcast-channel": "7.0.0",
"buraha": "0.0.1",
Expand Down
107 changes: 107 additions & 0 deletions packages/frontend/src/analytics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/

import * as Misskey from 'misskey-js';
import type { AnalyticsInstance, AnalyticsPlugin } from 'analytics';

/**
* analytics moduleを読み込まなくても動作するようにするためのラッパー
*/
class AnalyticsProxy implements AnalyticsInstance {
private analytics?: AnalyticsInstance;

constructor(analytics?: AnalyticsInstance) {
if (analytics) {
this.analytics = analytics;
}
}

public setAnalytics(analytics: AnalyticsInstance) {
if (this.analytics) {
throw new Error('Analytics instance already exists.');
}
this.analytics = analytics;
}

public identify(...args: Parameters<AnalyticsInstance['identify']>) {
return this.analytics?.identify(...args) ?? Promise.resolve();
}

public track(...args: Parameters<AnalyticsInstance['track']>) {
return this.analytics?.track(...args) ?? Promise.resolve();
}

public page(...args: Parameters<AnalyticsInstance['page']>) {
return this.analytics?.page(...args) ?? Promise.resolve();
}

public user(...args: Parameters<AnalyticsInstance['user']>) {
return this.analytics?.user(...args) ?? Promise.resolve();
}

public reset(...args: Parameters<AnalyticsInstance['reset']>) {
return this.analytics?.reset(...args) ?? Promise.resolve();
}

public ready(...args: Parameters<AnalyticsInstance['ready']>) {
return this.analytics?.ready(...args) ?? function () { void 0; };
}

public on(...args: Parameters<AnalyticsInstance['on']>) {
return this.analytics?.on(...args) ?? function () { void 0; };
}

public once(...args: Parameters<AnalyticsInstance['once']>) {
return this.analytics?.once(...args) ?? function () { void 0; };
}

public getState(...args: Parameters<AnalyticsInstance['getState']>) {
return this.analytics?.getState(...args) ?? Promise.resolve();
}

public get storage() {
return this.analytics?.storage ?? {
getItem: () => null,
setItem: () => void 0,
removeItem: () => void 0,
};
}

public get plugins() {
return this.analytics?.plugins ?? {
enable: (p, c) => Promise.resolve(c ? c() : void 0),
disable: (p, c) => Promise.resolve(c ? c() : void 0),
};
}
}

export const analytics = new AnalyticsProxy();

export async function initAnalytics(instance: Misskey.entities.MetaDetailed) {
// アナリティクスプロバイダに関する設定がひとつもない場合は、アナリティクスモジュールを読み込まない
if (!instance.googleAnalyticsMeasurementId) {
return;
}

const { default: Analytics } = await import('analytics');
const plugins: AnalyticsPlugin[] = [];

// Google Analytics
if (instance.googleAnalyticsMeasurementId) {
const { default: googleAnalytics } = await import('@analytics/google-analytics');

plugins.push(googleAnalytics({
measurementIds: [instance.googleAnalyticsMeasurementId],
debug: _DEV_,
}));
}

analytics.setAnalytics(Analytics({
app: 'misskey',
version: _VERSION_,
debug: _DEV_,
plugins,
}));
}
12 changes: 11 additions & 1 deletion packages/frontend/src/boot/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
*/

import { computed, watch, version as vueVersion } from 'vue';
import type { App } from 'vue';
import { compareVersions } from 'compare-versions';
import { version, lang, updateLocale, locale } from '@@/js/config.js';
import type { App } from 'vue';
import widgets from '@/widgets/index.js';
import directives from '@/directives/index.js';
import components from '@/components/index.js';
Expand All @@ -21,6 +21,7 @@ import { reloadChannel } from '@/scripts/unison-reload.js';
import { getUrlWithoutLoginId } from '@/scripts/login-id.js';
import { getAccountFromId } from '@/scripts/get-account-from-id.js';
import { deckStore } from '@/ui/deck/deck-store.js';
import { analytics, initAnalytics } from '@/analytics.js';
import { miLocalStorage } from '@/local-storage.js';
import { fetchCustomEmojis } from '@/custom-emojis.js';
import { setupRouter } from '@/router/main.js';
Expand Down Expand Up @@ -241,6 +242,15 @@ export async function common(createVue: () => App<Element>) {
await fetchCustomEmojis();
} catch (err) { /* empty */ }

// analytics
fetchInstanceMetaPromise.then(async () => {
await initAnalytics(instance);

if ($i) {
analytics.identify($i.id);
}
});

const app = createVue();

setupRouter(app, createMainRouter);
Expand Down
4 changes: 3 additions & 1 deletion packages/frontend/src/components/MkPageWindow.vue
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,14 @@ SPDX-License-Identifier: AGPL-3.0-only
import { computed, onMounted, onUnmounted, provide, ref, shallowRef } from 'vue';
import { url } from '@@/js/config.js';
import { getScrollContainer } from '@@/js/scroll.js';
import type { PageMetadata } from '@/scripts/page-metadata.js';
import RouterView from '@/components/global/RouterView.vue';
import MkWindow from '@/components/MkWindow.vue';
import { popout as _popout } from '@/scripts/popout.js';
import { copyToClipboard } from '@/scripts/copy-to-clipboard.js';
import { useScrollPositionManager } from '@/nirax.js';
import { i18n } from '@/i18n.js';
import { provideMetadataReceiver, provideReactiveMetadata } from '@/scripts/page-metadata.js';
import type { PageMetadata } from '@/scripts/page-metadata.js';
import { openingWindowsCount } from '@/os.js';
import { claimAchievement } from '@/scripts/achievements.js';
import { useRouterFactory } from '@/router/supplier.js';
Expand Down Expand Up @@ -92,6 +92,8 @@ const reloadCount = ref(0);

windowRouter.addListener('push', ctx => {
history.value.push({ path: ctx.path, key: ctx.key });

// ga
});

windowRouter.addListener('replace', ctx => {
Expand Down
53 changes: 39 additions & 14 deletions packages/frontend/src/pages/admin/external-services.vue
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,34 @@ SPDX-License-Identifier: AGPL-3.0-only
<template #header><XHeader :actions="headerActions" :tabs="headerTabs"/></template>
<MkSpacer :contentMax="700" :marginMin="16" :marginMax="32">
<FormSuspense :p="init">
<MkFolder>
<template #label>DeepL Translation</template>
<div class="_gaps_m">
<MkFolder>
<template #label>Google Analytics</template>

<div class="_gaps_m">
<MkInput v-model="deeplAuthKey">
<template #prefix><i class="ti ti-key"></i></template>
<template #label>DeepL Auth Key</template>
</MkInput>
<MkSwitch v-model="deeplIsPro">
<template #label>Pro account</template>
</MkSwitch>
<MkButton primary @click="save_deepl">Save</MkButton>
</div>
</MkFolder>
<div class="_gaps_m">
<MkInput v-model="googleAnalyticsMeasurementId">
<template #prefix><i class="ti ti-key"></i></template>
<template #label>Measurement ID</template>
</MkInput>
<MkButton primary @click="save_googleAnalytics">Save</MkButton>
</div>
</MkFolder>

<MkFolder>
<template #label>DeepL Translation</template>

<div class="_gaps_m">
<MkInput v-model="deeplAuthKey">
<template #prefix><i class="ti ti-key"></i></template>
<template #label>DeepL Auth Key</template>
</MkInput>
<MkSwitch v-model="deeplIsPro">
<template #label>Pro account</template>
</MkSwitch>
<MkButton primary @click="save_deepl">Save</MkButton>
</div>
</MkFolder>
</div>
</FormSuspense>
</MkSpacer>
</MkStickyContainer>
Expand All @@ -44,10 +58,13 @@ import MkFolder from '@/components/MkFolder.vue';
const deeplAuthKey = ref<string>('');
const deeplIsPro = ref<boolean>(false);

const googleAnalyticsMeasurementId = ref<string>('');

async function init() {
const meta = await misskeyApi('admin/meta');
deeplAuthKey.value = meta.deeplAuthKey;
deeplAuthKey.value = meta.deeplAuthKey ?? '';
deeplIsPro.value = meta.deeplIsPro;
googleAnalyticsMeasurementId.value = meta.googleAnalyticsMeasurementId ?? '';
}

function save_deepl() {
Expand All @@ -59,6 +76,14 @@ function save_deepl() {
});
}

function save_googleAnalytics() {
os.apiWithDialog('admin/update-meta', {
googleAnalyticsMeasurementId: googleAnalyticsMeasurementId.value,
}).then(() => {
fetchInstance(true);
});
}

const headerActions = computed(() => []);

const headerTabs = computed(() => []);
Expand Down
5 changes: 5 additions & 0 deletions packages/frontend/src/router/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { EventEmitter } from 'eventemitter3';
import type { IRouter, Resolved, RouteDef, RouterEvent, RouterFlag } from '@/nirax.js';

import type { App, ShallowRef } from 'vue';
import { analytics } from '@/analytics.js';

/**
* {@link Router}による画面遷移を可能とするために{@link mainRouter}をセットアップする。
Expand All @@ -23,6 +24,10 @@ export function setupRouter(app: App, routerFactory: ((path: string) => IRouter)

mainRouter.addListener('push', ctx => {
window.history.pushState({ key: ctx.key }, '', ctx.path);

analytics.page({
path: ctx.path,
});
Comment on lines +27 to +30
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

replaceに反応しないのでchangeイベントで取ったほうがいいかも

});

mainRouter.addListener('replace', ctx => {
Expand Down
3 changes: 3 additions & 0 deletions packages/misskey-js/src/autogen/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5042,6 +5042,7 @@ export type components = {
enableTurnstile: boolean;
turnstileSiteKey: string | null;
enableTestcaptcha: boolean;
googleAnalyticsMeasurementId: string | null;
swPublickey: string | null;
/** @default /assets/ai.png */
mascotImageUrl: string;
Expand Down Expand Up @@ -8251,6 +8252,7 @@ export type operations = {
enableTurnstile: boolean;
turnstileSiteKey: string | null;
enableTestcaptcha: boolean;
googleAnalyticsMeasurementId: string | null;
swPublickey: string | null;
/** @default /assets/ai.png */
mascotImageUrl: string | null;
Expand Down Expand Up @@ -10617,6 +10619,7 @@ export type operations = {
turnstileSiteKey?: string | null;
turnstileSecretKey?: string | null;
enableTestcaptcha?: boolean;
googleAnalyticsMeasurementId?: string | null;
/** @enum {string} */
sensitiveMediaDetection?: 'none' | 'all' | 'local' | 'remote';
/** @enum {string} */
Expand Down
Loading
Loading