Skip to content

Commit

Permalink
add ga4
Browse files Browse the repository at this point in the history
  • Loading branch information
domechn committed Aug 5, 2023
1 parent c6397c3 commit 53e4591
Show file tree
Hide file tree
Showing 9 changed files with 91 additions and 14 deletions.
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
"private": true,
"version": "0.0.0",
"type": "module",
"repository": {
"type": "git",
"url": "https://github.com/domechn/track3.git"
},
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
Expand All @@ -22,6 +26,7 @@
"react": "^18.2.0",
"react-chartjs-2": "^5.2.0",
"react-dom": "^18.2.0",
"react-ga4": "^2.1.0",
"react-hot-toast": "^2.4.1",
"tauri-plugin-sql-api": "https://github.com/tauri-apps/tauri-plugin-sql",
"uuid": "^9.0.0",
Expand Down
1 change: 0 additions & 1 deletion src-tauri/Cargo.lock

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

1 change: 0 additions & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ sqlx = {version = "0.6", features = ["runtime-tokio-rustls", "sqlite"] }
tauri = {version = "1.2", features = ["app-all", "dialog-open", "dialog-save", "fs-read-file", "fs-write-file", "http-all", "process-relaunch", "updater"] }
tokio = {version = "1", features = ["sync"] }
uuid = "1.3.3"
version-compare = "0.1.1"

[features]
# by default Tauri runs in production mode
Expand Down
3 changes: 2 additions & 1 deletion src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ async fn get_polybase_namespace(handle: tauri::AppHandle) -> Result<String, Stri
fn main() {
tauri::Builder::default()
.setup(|app| {
let app_version = app.package_info().version.to_string();
let resource_path = app.path_resolver();
let resource_dir = resource_path.resource_dir().unwrap();
let app_dir = resource_path.app_data_dir().unwrap();
Expand All @@ -170,7 +171,7 @@ fn main() {
if is_first_run(app_dir.as_path()) {
init_sqlite_file(app_dir.as_path());
}
init_sqlite_tables(app_dir.as_path(), resource_dir.as_path());
init_sqlite_tables(app_version, app_dir.as_path(), resource_dir.as_path());

if is_from_v01_to_v02(app_dir.as_path()).unwrap() {
// upgrade from v0.1 to v0.2
Expand Down
36 changes: 25 additions & 11 deletions src-tauri/src/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,17 @@ use std::{
};

use sqlx::{Connection, Executor, SqliteConnection};
use tauri::api::version;
use tokio::runtime::Runtime;
use uuid::Uuid;
use version_compare::{compare_to, Cmp};
use uuid::{Uuid};

use crate::types::{AssetsV1, AssetsV2, Configuration};

static CLIENT_ID_CONFIGURATION_ID: i32 = 998;
static VERSION_CONFIGURATION_ID: i32 = 999;
static CURRENT_VERSION: &str = "v0.3";

static CONFIGURATION_TABLE_NAME: &str = "configuration";
static ASSETS_V2_TABLE_NAME: &str = "assets_v2";

pub fn is_first_run(path: &Path) -> bool {
// check sqlite file exists
Expand All @@ -26,7 +29,7 @@ fn get_sqlite_file_path(path: &Path) -> String {
String::from(path.join("track3.db").to_str().unwrap())
}

pub fn init_sqlite_tables(app_dir: &Path, resource_dir: &Path) {
pub fn init_sqlite_tables(app_version:String, app_dir: &Path, resource_dir: &Path) {
println!("start initing sqlite tables in rust");
let sqlite_path = get_sqlite_file_path(app_dir);
let configuration =
Expand All @@ -47,14 +50,25 @@ pub fn init_sqlite_tables(app_dir: &Path, resource_dir: &Path) {
conn.execute(cloud_sync.as_str()).await.unwrap();
conn.execute(currency_rates_sync.as_str()).await.unwrap();

sqlx::query("INSERT INTO configuration (id, data) VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET data = ?")
// record current app version
sqlx::query(format!("INSERT INTO {} (id, data) VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET data = ?", CONFIGURATION_TABLE_NAME).as_str())
.bind(VERSION_CONFIGURATION_ID)
.bind(CURRENT_VERSION)
.bind(CURRENT_VERSION)
.bind(app_version.as_str())
.bind(app_version.as_str())
.execute(&mut conn)
.await
.unwrap();

let client_id = Uuid::new_v4();
// record client id
sqlx::query(format!("INSERT OR IGNORE INTO {} (id, data) VALUES (?, ?)", CONFIGURATION_TABLE_NAME).as_str())
.bind(CLIENT_ID_CONFIGURATION_ID)
.bind(client_id.to_string())
.execute(&mut conn)
.await
.unwrap();


conn.close().await.unwrap();
println!("init sqlite tables in tokio spawn done");
});
Expand Down Expand Up @@ -104,15 +118,15 @@ pub fn is_from_v02_to_v03(path: &Path) -> Result<bool, Box<dyn std::error::Error
return Ok(rt.block_on(async move {
println!("check if from v0.2 to v0.3 in tokio spawn");
let mut conn = SqliteConnection::connect(&sqlite_path).await.unwrap();
let data = sqlx::query_as::<_, Configuration>("select * from configuration where id = ?")
let data = sqlx::query_as::<_, Configuration>(format!("select * from {} where id = ?", CONFIGURATION_TABLE_NAME).as_str())
.bind(VERSION_CONFIGURATION_ID)
.fetch_one(&mut conn)
.await;
conn.close().await.unwrap();


let res = match data {
Ok(data) => Ok(compare_to(data.data ,"v0.3", Cmp::Lt) == Ok(true)),
Ok(data) => Ok(version::compare(&data.data, "v0.3").unwrap_or(-1) > 0),
Err(e) => {
// if error is RowNotFound, not need to migrate
match e {
Expand Down Expand Up @@ -157,7 +171,7 @@ pub fn migrate_from_v01_to_v02(app_dir: &Path, resource_dir: &Path) {

// insert data_v2 to assets_v2
for row in data_v2 {
sqlx::query("insert into assets_v2 (uuid, symbol, amount, value, price, createdAt) values (?, ?, ?, ?, ?, ?)")
sqlx::query(format!("insert into {} (uuid, symbol, amount, value, price, createdAt) values (?, ?, ?, ?, ?, ?)", ASSETS_V2_TABLE_NAME).as_str())
.bind(row.uuid)
.bind(row.symbol)
.bind(row.amount)
Expand Down Expand Up @@ -192,7 +206,7 @@ pub fn migrate_from_v02_to_v03(app_dir: &Path, resource_dir: &Path) {
let mut conn = SqliteConnection::connect(&sqlite_path).await.unwrap();
conn.execute(assets_v2.as_str()).await.unwrap();

sqlx::query("INSERT INTO configuration (id, data) VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET data = ?")
sqlx::query(format!("INSERT INTO {} (id, data) VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET data = ?", CONFIGURATION_TABLE_NAME).as_str())
.bind(VERSION_CONFIGURATION_ID)
.bind(new_version)
.bind(new_version)
Expand Down
38 changes: 38 additions & 0 deletions src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,47 @@ import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./style.css";
import ReactGA from "react-ga4";
import { getClientID, getVersion } from './utils/app'


ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<App />
</React.StrictMode>
);

function disableContextmenu() {
if (window.location.hostname !== 'tauri.localhost') {
return
}
document.addEventListener('contextmenu', e => {
e.preventDefault();
return false;
}, { capture: true })
}

disableContextmenu()

// ga4
;(async () => {
const GAID = "G-QTHN28P1Q3"
try {
const cid = await getClientID()
const version = await getVersion()
ReactGA.initialize([{
trackingId: GAID,
gaOptions: {
app_version: version,
clientId: cid
},
gtagOptions: {
app_version: version,
clientId: cid
}
}])
} catch (e) {
ReactGA.initialize(GAID)
throw e
}
})()
6 changes: 6 additions & 0 deletions src/middlelayers/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { getCurrencyRate, getDefaultCurrencyRate } from './currency'
const prefix = "!ent:"
const fixId = "1"
const cloudSyncFixId = "2"
const clientInfoFixId = "998"

export async function getConfiguration(): Promise<GlobalConfig | undefined> {
const model = await getConfigurationById(fixId)
Expand Down Expand Up @@ -95,3 +96,8 @@ export async function getCurrentPreferCurrency(): Promise<CurrencyRateDetail> {

return getCurrencyRate(pc)
}

export async function getClientIDConfiguration(): Promise<string | undefined> {
const model = await getConfigurationById(clientInfoFixId)
return model?.data
}
10 changes: 10 additions & 0 deletions src/utils/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import * as api from '@tauri-apps/api'
import { getClientIDConfiguration } from '../middlelayers/configuration'

export async function getVersion() {
return api.app.getVersion()
}

export async function getClientID() {
return getClientIDConfiguration()
}
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1213,6 +1213,11 @@ react-dom@^18.2.0:
loose-envify "^1.1.0"
scheduler "^0.23.0"

react-ga4@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/react-ga4/-/react-ga4-2.1.0.tgz#56601f59d95c08466ebd6edfbf8dede55c4678f9"
integrity sha512-ZKS7PGNFqqMd3PJ6+C2Jtz/o1iU9ggiy8Y8nUeksgVuvNISbmrQtJiZNvC/TjDsqD0QlU5Wkgs7i+w9+OjHhhQ==

react-hot-toast@^2.4.1:
version "2.4.1"
resolved "https://registry.yarnpkg.com/react-hot-toast/-/react-hot-toast-2.4.1.tgz#df04295eda8a7b12c4f968e54a61c8d36f4c0994"
Expand Down

0 comments on commit 53e4591

Please sign in to comment.