Skip to content

Commit

Permalink
V1.3.6 analytics (#131)
Browse files Browse the repository at this point in the history
* Update Freesound keys and GA
* Increase API response page size
* 1.3.6
  • Loading branch information
jamland authored Dec 27, 2020
1 parent e496308 commit d13e374
Show file tree
Hide file tree
Showing 16 changed files with 275 additions and 96 deletions.
13 changes: 12 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,15 @@ NUCLEUS_API_KEY= set correct credentials
GA_API_KEY= set correct credentials
APPLE_ID= set correct credentials
APPLE_ID_PASSWORD= set correct credentials
GITHUB_TOKEN= set correct credentials
GITHUB_TOKEN= set correct credentials
GA4_MEASUREMENT_ID= set correct credentials
GA4_API_SECRET= set correct credentials
SAMPLESCOPE_FREESOUND_CLIENT_ID_01= set correct credentials
SAMPLESCOPE_FREESOUND_API_KEY_01= set correct credentials
SAMPLESCOPE_FREESOUND_CLIENT_ID_02= set correct credentials
SAMPLESCOPE_FREESOUND_API_KEY_02= set correct credentials
SAMPLESCOPE_FREESOUND_CLIENT_ID_03= set correct credentials
SAMPLESCOPE_FREESOUND_API_KEY_03= set correct credentials
SAMPLESCOPE_FREESOUND_CLIENT_ID_04= set correct credentials
SAMPLESCOPE_FREESOUND_API_KEY_04= set correct credentials

Binary file modified design/Samplescope v2.sketch
Binary file not shown.
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "samplescope",
"productName": "Samplescope",
"version": "1.3.5",
"version": "1.3.6",
"description": "Search samples over internet sources",
"main": ".webpack/main",
"repository": "github:jamland/samplescope",
Expand Down
8 changes: 5 additions & 3 deletions src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@
<meta charset="UTF-8" />
<title>Samplescope</title>

<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300;0,400;0,600;0,700;1,300;1,400&display=swap" rel="stylesheet">

<link rel="preconnect" href="https://fonts.gstatic.com" />
<link
href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300;0,400;0,600;0,700;1,300;1,400&display=swap"
rel="stylesheet"
/>
</head>

<body>
Expand Down
9 changes: 1 addition & 8 deletions src/main/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { app, BrowserWindow, ipcMain } from 'electron';
import { download } from 'electron-dl';
import windowStateKeeper from 'electron-window-state';
import analyticsGoogle from '../modules/analytics/google';
import logger from 'electron-log';
import appMenu from './menu';
import '../modules/analytics/bugsnag.main';
Expand All @@ -21,9 +20,7 @@ if (require('electron-squirrel-startup')) {
app.quit();
}

global.analyticsGoogle = analyticsGoogle ?? {};

const defaultWidth = 950;
const defaultWidth = 920;
const defaultHeight = 800;

// for tracking user session time
Expand Down Expand Up @@ -86,10 +83,6 @@ const createWindow = () => {

// Emitted when the window is closed.
mainWindow.on('closed', () => {
const endTime = new Date().getMilliseconds();
const interactionTime = startTime - endTime;
analyticsGoogle.trackSessionTiming(interactionTime);

// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
Expand Down
116 changes: 116 additions & 0 deletions src/modules/analytics/ga4.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
export {};
declare global {
interface Window {
dataLayer: any;
}
}

const { app } = require('electron').remote;
const { JSONStorage } = require('node-localstorage');
const nodeStorage = new JSONStorage(app.getPath('userData'));
const remote = window.require('electron').remote;
const env = remote.getGlobal('process').env;

// const measurementId = process.env.GA4_MEASUREMENT_ID ?? env.GA4_MEASUREMENT_ID;
const measurementId = 'G-HTY5MME75G';
const apiSecret = 'Xb8Rtz75T52vgGyQ1H-d2g';
const gtagScriptUrl = `https://www.googletagmanager.com/gtag/js?id=${measurementId}`;
let GA_LOCAL_STORAGE_KEY = 'ga:clientId';

function gtag() {
window.dataLayer.push(arguments);
}

const loadScript = async (url: string) => {
try {
const response = await fetch(url);
const script = await response.text();
eval(script);
} catch (error) {
console.warn(`Can't load script ${url} because of the error: ${error.msg}`);
}
};

const gtagGetPromisify = (propertyName: string): Promise<string> => {
return new Promise((resolve, reject) => {
// @ts-ignore
gtag('get', measurementId, propertyName, (value) => {
resolve(value);
});
});
};

// Get clientId from localStorage
// or get it from gtag() and save it to localStorage
const getClientId = async () => {
const clientIdFromLocalStorage = nodeStorage.getItem(GA_LOCAL_STORAGE_KEY);

if (clientIdFromLocalStorage) return clientIdFromLocalStorage;
else {
const clientId = await gtagGetPromisify('client_id');
nodeStorage.setItem(GA_LOCAL_STORAGE_KEY, clientId);
return clientId;
}
};

const register = async () => {
await loadScript(gtagScriptUrl);

window.dataLayer = window.dataLayer || [];
// console.log('window.dataLayer', window.dataLayer);

if (!nodeStorage)
return Promise.reject(`Can't start GA4. LocalStorage isn't available`);

// @ts-ignore
gtag('js', new Date());

const clientId = await getClientId();

// Use localStorage instead of cookies, since 🍪 aren't available on desktop app.
// https://developers.google.com/analytics/devguides/collection/analyticsjs/cookies-user-id#using_localstorage_to_store_the_client_id
const options = {
storage: 'none',
clientId,
};
// @ts-ignore
gtag('config', measurementId, options);

// Disable file protocol checking
// @ts-ignore
gtag('set', { checkProtocolTask: null });
// @ts-ignore
gtag('set', { checkStorageTask: null }); // Disable cookie storage checking
// @ts-ignore
gtag('set', { historyImportTask: null }); // Disable history checking (requires reading from cookies)
};

const sendEvent = async (name: string, params: unknown) => {
const clientId = await getClientId();

try {
await fetch(
`https://www.google-analytics.com/mp/collect?measurement_id=${measurementId}&api_secret=${apiSecret}`,
{
method: 'POST',
body: JSON.stringify({
client_id: clientId,
user_id: 'dev_user',
events: [
{
name: name,
params: params,
},
],
}),
}
);
} catch (error) {
console.warn('Error sending event to GA4: ', error.message);
}
};

export default {
register,
sendEvent,
};
52 changes: 33 additions & 19 deletions src/modules/analytics/google.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,51 @@
import { app } from 'electron';
import ua from 'universal-analytics';
// import ua from 'universal-analytics';

// import Analytics from 'electron-google-analytics';
import userId from '../../main/userId';

const GA_API_KEY = 'UA-173935505-1';
const appName = app.getName();
const appVersion = app.getVersion();
// const GA_API_KEY = 'UA-173935505-1';
// const GA_API_KEY = 'G-15X5TFP4CY';
// const appName = app.getName();
// const appVersion = app.getVersion();

const gaApiKey = process.env.GA_API_KEY || GA_API_KEY || '';
const visitor = ua(gaApiKey, userId);
// const gaApiKey = process.env.GA_API_KEY || GA_API_KEY || '';
// const visitor = ua(gaApiKey, userId);
// Allows filtering by the 'Application?' field in GA
// visitor.set('ds', 'app');
visitor.set('uid', userId);
// visitor.set('uid', userId);

// console.log('gaApiKey', gaApiKey);

// console.log('userId', userId);

// const analytics = new Analytics(GA_API_KEY);
// analytics.set('uid', userId);

// analytics.pageview('http://example.com', '/home', 'Example');

// visitor.pageview("/").send();

function trackEvent(category, action, label, value) {
visitor
.event({
ec: category,
ea: action,
el: label,
ev: value,
})
.send();
// visitor
// .event({
// ec: category,
// ea: action,
// el: label,
// ev: value,
// })
// .send();
}

// trackEvent('Test Event', 'test action');
visitor.event('Event Category', 'Event Action').send();
// visitor.event('Event Category', 'Event Action').send();

function trackScreenView(screenName: string) {
visitor.screenview(screenName, appName, appVersion).send();
// visitor.screenview(screenName, appName, appVersion).send();
}

function trackSessionTiming(time: string) {
visitor.timing('User interaction', 'User Session Time', time).send();
// visitor.timing('User interaction', 'User Session Time', time).send();
}

export default { trackEvent, trackScreenView, trackSessionTiming };
export default { trackEvent, trackScreenView, trackSessionTiming, analytics };
8 changes: 4 additions & 4 deletions src/modules/analytics/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
*/
// import Nucleus from '@modules/analytics.nucleus';

const { remote } = require('electron');
const analyticsGoogle = remote.getGlobal('analyticsGoogle');
// const { remote } = require('electron');
// const analyticsGoogle = remote.getGlobal('analyticsGoogle');

/**
* GA started in main process
Expand All @@ -26,7 +26,7 @@ const trackEvent = ({
label: string;
value: string | number;
}) => {
analyticsGoogle.event?.(name, action, label, value);
// analyticsGoogle.trackEvent?.(name, action, label, value);
// Nucleus.track?.(name, {
// searchQuery: value,
// });
Expand All @@ -37,7 +37,7 @@ const trackEvent = ({
* Nucleas track as another event
*/
const screenview = (screenName: string) => {
analyticsGoogle.screenview?.(screenName);
// analyticsGoogle.screenview?.(screenName);
// Nucleus.track?.(screenName);
};

Expand Down
Loading

0 comments on commit d13e374

Please sign in to comment.