Skip to main content

Subsections of Development

fastapi Server / mqtt client / pyrc - PWA

This fastapi server enables access to a sqlite DB (sqlalchemy) with SmartMeter data from an mqtt broker and the SmartMeter data from a FritzBox. The database therefore contains the measurement data and devices and this data is made available via pydantic and fastapi. In addition, the fastapi server starts a scheduler (apscheduler) in a background process - the SmartMeter data of the tasmota SmartMeter from bitShake with connection to the electricity meter and also the SmartMeter devices of the FritzBox are read out via background processes using an mqtt client. This read data is periodically written to the sqlite DB and is then available again via the fastapi server. In addition, a reorganization job is started that deletes redundant data and performs data aggregation or normalization. To ensure that the scheduler and job information is available to all work processes of the fastapi server, an rpyc server and client are also implemented locally, i.e. the background job starts the scheduler and the rpyc server and makes this data available locally to the fastapi processes.

Installation - clone and pip

Please get standard installation of python on your system and install this server as follows:

git clone https://github.com/jankstar/py_hab.git
cd py_hab
python3 -m venv env
pip install -r requirements.txt 
./start.sh

Environtment - .env for defines.py

We use ‘.env’ for defines:

FRITZBOX_URL = "http://xxx.xxx.xxx.xxx"
USERNAME = "*******"
PASSWORD = "*******"
DATABASE = 'sqlite:///datenbank.db'
MQTT_SERVER = "xxx.xxx.xxx.xxx"
MQTT_PORT = 1883
MQTT_CLIENT_ID = "*******"
SLEEP_TIME = 600
WAIT_TIME = 10
TIMEZONE = 'Europe/Berlin'

FRONTEND_URL= 'http://xxx.xxx.xxx.xxx:8000'
RPYX_PORT=8001

# -- SESSION --
# Secret phrase for session encryption
SESSION_SECRET=xxxxxxxxxxx

This file will be used in define.py:

FRITZBOX_URL = os.getenv('FRITZBOX_URL',"http://0.0.0.0")
USERNAME = os.getenv('USERNAME', "") 
PASSWORD = os.getenv('PASSWORD', "")
DATABASE = os.getenv('DATABASE','sqlite:///datenbank.db')
MQTT_SERVER = os.getenv('MQTT_SERVER',"0.0.0.0")
MQTT_PORT = int(os.getenv('MQTT_PORT',1883)) #1883
MQTT_CLIENT_ID = os.getenv('MQTT_CLIENT_ID', "TEST") 
SLEEP_TIME = int(os.getenv('SLEEP_TIME',600)) #600
WAIT_TIME = int(os.getenv('WAIT_TIME',10)) #10
TIMEZONE = os.getenv('TIMEZONE', 'Europe/Berlin')
SESSION_SECRET = os.getenv('SESSION_SECRET', 'secret')
FRONTEND_URL = os.getenv('FRONTEND_URL',"http://localhost:8000")
RPYX_PORT = int(os.getenv('RPYX_PORT',8001))
DEFAULT_LIMIT = 200
MODE = 'NO_DEBUG' #'DEBUG'

REST api Server - fastapi and pydantic

The Model.py defines the structure for the API and automatically converts from the DB structure.

class MeasurementData(Base):
    '''Measurement as sqlalchemy model'''
    __table__ = Table('measurement_data', Base.metadata,
        Column('id', String, primary_key=True), # key id, we use UUID
        Column('device', String),      # device
        Column('topic', String),       # topic of mqtt
        Column('entity', String),      # sensor
        Column('sub_entity', String),  # sensor sub device
        Column('time', String),        # timestamp of measurement
        Column('amount', Float),       # value of measurement
    )

    __table_args__ = (
            Index('idx_01', 'device', 'sub_entity', 'time'),
        )
    
    def __repr__(self):
        return f"<measurement(topic='{self.topic}', time={self.time}, device={self.device}, amount={self.amount}, )>"

class Measurement(BaseModel):
    '''Measurement as pydantic model'''
    id: str
    device: str
    topic: str
    entity: str
    sub_entity: str
    time: str
    amount: float

    model_config = ConfigDict(from_attributes=True)

class DeviceData(Base):
    '''Device as sqlalchemy model'''
    __table__ = Table('device_data', Base.metadata,
        Column('device', String, primary_key=True),     # device
        Column('sub_entity', String, primary_key=True), # sensor sub device
        Column('device_name', String),
        Column('product_name', String),
        Column('manufacturer', String),
        Column('firmware_version', String),
        Column('unit', String),               # unit of measurement
        Column('cumulative', Boolean),        # if measurement is cumulative
    )

    def __repr__(self):
        return f"<device(device={self.device}, device_name={self.device_name}, unit={self.unit})>"

class Device(BaseModel):
    '''Device as pydantic model'''
    device: str
    sub_entity: str
    device_name: str
    product_name: str
    manufacturer: str
    firmware_version: str
    unit: str
    cumulative: bool

    model_config = ConfigDict(from_attributes=True)    

There is an indicator for distinguishing cumulative measurements, e.g. power consumption, i.e. this value increases with each measurement. In contrast, the power or temperature is the value at the exact time of the measurement.
So we have an DB structure and an pydantic structure for the fastapi api json response.

Database and sqlalchemy

We use sqlite db - so we can only run the sync driver and sync session make.

def get_db_session_sync():
    '''get_db_session    start and get database Session'''
    return sessionmaker(bind=get_db_sync())

def get_db_sync():
    '''get_db_sync    start and get database connection'''
    return create_engine(DATABASE,
                         pool_size=20,
                         max_overflow=30)

The .env define DATABASE = os.getenv('DATABASE','sqlite:///datenbank.db'). The function get_db_session_sync() is used as db: Session = Depends(get_db_session_sync) at endpint-function. In the fastapi endpoint we execute sql to grep data and move it to response_model.

@router.get("/api/mesurement/{device}/{sub_entity}", response_model=list[Measurement])
async def get_measurement_by_device_sub_entity(device: str, sub_entity: str,limit: int = DEFAULT_LIMIT, offset: int = 0, db: Session = Depends(get_db_session_sync)):
    '''get_measurement get measurement data by device and sub_entity from database'''

    try:
        session = db()
        last_data = session.scalars(select(MeasurementData)
                                    .where(and_(MeasurementData.device == device, MeasurementData.sub_entity == sub_entity))
                                    .order_by(MeasurementData.time.desc())
                                    .offset(offset)
                                    .limit(limit)).all()
        session.close()
        result = [Measurement.model_validate(data) for data in last_data]
    except Exception as e:
        logger.error("Error while getting mesurement by device and sub_entity: " + str(e))
        raise HTTPException(status_code=404, detail="No Items found")

    return result

The result line result = [Measurement.model_validate(data) for data in last_data] converts the data from DB to pydantic as json response_model=list[Measurement] .

Scheduler - apscheduler and rpyc

We use rpyc server for the scheduler apscheduler. If we start the fastapi server via unicorn with worker, we need only one scheduler and all worker needs access to the scheduler. The solution is stand alone rpyc server for the apscheduler. The lifespan from fastapi is cheching fcntl.lockf() via file and starts one task für the server.

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Code for Startup
    app.server = None
    app.scheduler = None
    app.scheduler_task = None
    try:
        #we need only one scheduler

        # +++++++
        _ = open("/tmp/fastapi.lock","w")
        _fd = _.fileno()
        fcntl.lockf(_fd,fcntl.LOCK_EX|fcntl.LOCK_NB)
        # +++++++

        app.scheduler_task =  asyncio.create_task(background_process(app))

    except BlockingIOError:
            pass

    app.logger.info("Server starts...")

    yield
    # Code  for Shutdown
    if app.server != None: app.server.close()
    if app.scheduler != None: app.scheduler.shutdown()
    if app.scheduler_task != None: app.scheduler_task.cancel(msg='Shutting down...')
    app.logger.info("Server shuts down...")

The asyncio.create_task(background_process(app)) starts the server in background. The rpyc.server is quit simple, we define an services class for the remote access from fastapi async anedpont.

async def background_process(app: FastAPI):
    '''background_process() starts the scheduler ansd the rpyc-server'''
    app.logger.info("background_process() started")

    app.scheduler = BackgroundScheduler()
    app.scheduler.configure(
        misfire_grace_time=300,  # 5 Minuten
        coalesce=True
    )
    
    # Add background task
    app.scheduler.add_job(periodic_task, 'date', id='periodic_task_1', run_date=datetime.now() + timedelta(seconds=3))
    app.scheduler.add_job(periodic_task, 'interval', id='periodic_task_2', seconds=SLEEP_TIME)
    app.scheduler.add_job(reorganisation_task, 'interval', id='reorganisation_task', seconds=60*60*24)
    app.scheduler.start()

    protocol_config = {"allow_public_attrs": True, "allow_pickle": True}
    app.server = ThreadedServer(
       SchedulerService, port=RPYX_PORT, protocol_config=protocol_config
    )

    try:
        app.server._start_in_thread()
        #blocking server start
        while True:
            await asyncio.sleep(1)
    except Exception as e:
        app.logger.error("Error while Server stopped with: "+str(e))  
       
    app.servers.close()
    app.servers = None

    app.scheduler.shutdown()
    app.scheduler = None

If we starts services remotely, we need {"allow_public_attrs": True, "allow_pickle": True} elsewhere only string parameters will work. In this example we starts fix job for the mqtt client and reading FritzBox. The second job cleans up redundant data and performs periodic summarizations.

Fastapi endpint /jobs is getting the jobs via remote access.

@app.get("/jobs")
async def get_jobs():
    jobs = []
    try:
        conn = rpyc.connect("localhost", RPYX_PORT)
        conn_jobs  = conn.root.get_jobs() 
        jobs = copy.deepcopy(conn_jobs) # deep copy required for build response
        conn.close() 
    except Exception as e:
        app.logger.error("Error while getting jobs: " + str(e))
        raise HTTPException(status_code=404, detail="No Items found")
        

    return [{"id": f"{obj.id}", "func": f"{obj.func.__name__}", "trigger": f"{obj.trigger}", "next_run_time": f"{obj.next_run_time}"} for obj in jobs]

mqtt client

The sensor sends the measured values every 6 seconds via the tasmota server via mqtt broker. Background job periodic_task()`` is started every 10 minutes via the scheduler apscheduler``` and then waits 10 seconds to receive one measurement. The received data is then stored in the SQLite DB.

def periodic_task():
    '''
    start mqtt client and save data to database one time
    '''

    logger = logging.getLogger("py_hab")
    engine = get_db_sync()
    Base.metadata.create_all(engine)
    Session = sessionmaker(bind=engine)

   
    mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2,protocol=mqtt.MQTTv5, client_id=MQTT_CLIENT_ID)
    properties = Properties(PacketTypes.CONNECT)
    properties.SessionExpiryInterval = 3600  # Sets the session runtime to 1 hour

    userdata = {
        'engine': engine,
        'session': Session,
        'logger': logger
    }

    mqttc._userdata = userdata
    mqttc.on_connect = on_connect
    mqttc.on_message = on_message

    try:
          
        mqttc.connect(MQTT_SERVER, MQTT_PORT, 60, clean_start=False, properties=properties)
        mqttc.loop_start()
        time.sleep(WAIT_TIME)  # if mqtt does not buffer, all measurement messages are read from these 10 sec 
        mqttc.disconnect()
        mqttc.loop_stop()
        if (USERNAME != "" and PASSWORD != ""):
            logger.info("Check FritzBox ...")
            connect_fritzbox(userdata)



    except (KeyboardInterrupt, SystemExit):
        pass
    finally:
        mqttc.disconnect()
        mqttc.loop_stop()

Only in the period between mqttc.loop_start() and mqttc.loop_stop() are the messages from the broker received and saved in the database. The tasmota server only sends qos=0 messages that are not buffered. Two event functions are registered: on_connect() for establishing the connection and on_message() for processing the messages. The structure _userdata is passed to the event functions and contains the DB session maker and the logger.

FritzBox

The code is from FritzBox forum We need user/password on FritzBox with smartMeter credentials. The temperature from the radiator controller is read and stored in the DB. The battery status and the opening or closing of the window contacts are also stored.

(2024/12/27)
Index

Dec 27, 2024

Rust: Tauri + OAuth2 + Google

This example is a Tauri app with a Vue 3 / TS client and for an authentication of the user via a Google account/email, i.e., the Google login window opens and the user must log in and agree to the transfer of his profile data (name and email). The user data and the refresh token are stored, so that subsequently at the start of the app an automatic login takes place.

Attention: this application is not intended for productive use, because user data and token are not encrypted, but stored in plain text!

1 Code / Example

The code can be found at: tauri_oauth

npm run tauri dev

2 Preparation

2.1 Google GOOGLE_CLIENT_ID/GOOGLE_CLIENT_SECRET

For an authentication via a Google account we need a Google Client ID and a Cliebt Secret key for the API gmail and oauth2 for our application. For this purpose there are instructions https://cloud.google.com/docs/authentication at Google.

The settings are done via https://console.cloud.google.com/ in the item ‘Enable API and services/ceredentials’ and ‘OAuth2 client IDs’. Here are some settings to consider if we want to authenticate with Tauri.

We are using authentication a web app, our application is running in Tauri on a server on the one hand, on the other hand we need our own server for the redirect. This redirect URI must be specified there ‘Authorized redirect URIs’. In my example I use for the server http://localhost:1420 (this is in the tari.conf.json) and for the redirect http://127.0.0.1:1421 - so the port 1421. This URL is used in Tauri and must be authenticated with Google for the request.

The Client ID and Client Secrete data can be found on the page.

2.2 .env File

A .env file with the following data is needed in the src-tauri directory:

GOOGLE_CLIENT_ID=<CLIENT_ID>
GOOGLE_CLIENT_SECRET=>CLIENT_SECRET>

For the application, the Google Client/Secrete must be created and written to the file, otherwise the program will not work.

2.3 Google Playground

The google oauth2 functions can be tested via the URL “https://developers.google.com/oauthplayground/".

3 Tauri App

3.1 User, UserData and AppData

In addition to authentication via OAuth2, the access token should also query user data from Google. If the values profile email are requested as scope in the request, the following structure is available:

#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Default)]
/// # User
/// struct for the google user data
pub struct User {
    pub id: String,
    pub email: String,
    pub verified_email: bool,
    pub name: String,
    pub given_name: String,
    pub family_name: String,
    pub picture: String,
    pub locale: String,
}
...

The request and the passing of the scope is described below.

The app should also record a refresh token in addition to the user data:

#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Default)]
/// # UserData
/// are the central data of the application and are stored in a local file and <br>
/// read with the start of the server or initialized if the file does not yet exist.
/// - user
/// - refresh_token
pub struct UserData {
    pub user: User,
    pub refresh_token: Option<oauth2::RefreshToken>,
}
...

This class is also used to read and set the user data, the token and the save as file. Attention: this function is only a test implementation and not intended for productive use. With the refresh token, an automatic attempt is made to log in again when the application is started, i.e. if this works, the user remains logged in right away.

The app itself gets the structure AppData via manage:

/// # AppData
/// is managed via the tauri app
pub struct AppData {
    pub user_data: Mutex<UserData>,
    pub logged_in: Mutex<bool>,
    //pub db: Mutex<SqliteConnection>,
}

The structure contains the user data and an indicator whether a user is logged in, i.e. whether the login worked. This data must be encapsulated via a mutex because of the asynchronous processing.

3.2 The main function: manage AppData and ExitRequested Event

The main routine contains the tauri-builder with the manage of the app data. An invoke-handler js2rs is registered. At this point a handler of the event ExitRequested can also be registered.

fn main() {
    tracing_subscriber::fmt::init();

    let app = tauri::Builder::default()
        .manage(AppData {
            user_data: UserData::init_user_data().into(), //the user data
            logged_in: false.into(),                      //log in state
                                                          //db: establish_connection(&database_name).into(),
        }) // AppData to manage
        .invoke_handler(tauri::generate_handler![js2rs])
        .build(tauri::generate_context!())   
        .unwrap()
        .run(move |_app_handler, _event| {
            if let RunEvent::ExitRequested { api, .. } = &_event {
                println!("Exit requested: {:?}", _event);
                // Keep the event loop running even if all windows are closed
                // This allow us to catch tray icon events when there is no window
                //api.prevent_exit();
              }            
        });

        //.expect("error while running tauri application");
}

3.4 Tauri: rust from/to Vue.js

The transfer of data from/to rust or from/to Vue.js is done as a json string. In my example two commands are implemented as string: get_user: liefert die Daten zum User bzw. führt ein Login durch, wenn kein User eingeloggt ist.

logout: deletes the user data, the tokens and the logged_in flag in the app and file. Note: There is also the possibility to log out the Google user via the token, this function is available but not implemented here. For this reason the user is immediately available at a new login, because the browser still has the cookies, the user is still logged in there.

// A function that sends a message from Rust to JavaScript via a Tauri Event
pub fn rs2js<R: tauri::Runtime>(message: String, manager: &impl tauri::Manager<R>) {
    let mut sub_message = message.clone();
    sub_message.truncate(50);
    info!(?sub_message, "rs2js");
    match manager.emit_all("rs2js", message) {
        Ok(_) => {}
        Err(err) => {
            error!(?err);
        }
    };
}
/// The Tauri command that gets called when Tauri `invoke` JavaScript API is called
#[tauri::command(async)]
async fn js2rs(
    window: tauri::Window,
    message: String,
    app_data: tauri::State<'_, AppData>,
) -> Result<String, String> {
    info!(message, "message_handler: ");

    if message == "get_user" {
        //get the data from the mutex
        let mut user_data = app_data.user_data.lock().await;
        let mut logged_in = app_data.logged_in.lock().await;

        if logged_in.clone() != true {
            match window.get_window("main") {
                Some(main_window) => {
                    main_window.hide();

                    *logged_in = user_data.log_in(&window).await;

                    main_window.show();
                }
                _ => {}
            };
        }

        return Ok(json!(user_data.user).to_string());
    }

    if message == "logout" {
        //get the data from the mutex
        let mut user_data = app_data.user_data.lock().await;
        let mut logged_in = app_data.logged_in.lock().await;

        //clear all user data
        user_data.user = User::new();
        user_data.refresh_token = None;
        user_data.save_me();
        *logged_in = false;

        *logged_in = user_data.log_in(&window).await;

        return Ok(json!(user_data.user).to_string());
    }

    //return else
    Ok("".to_string())
}

3.5 Calling the OAuth2

The solution used here is taken from oauth2 crate and slightly optimised.

The log_in() function first fetches the access token via OAuth2 and then the user data for authentication. Only if both actions were successful, true is returned.

Match the get_token() function:

    pub async fn log_in(&mut self, window: &tauri::Window) -> bool {
        let l_do: i32 = 'block: {
            let (l_access_token, l_refresh_token) =
                match get_token(&window, self.user.email.clone(), self.refresh_token.clone()).await
                {
                    Ok(token) => token,
                    Err(e) => {
                        error!("error - Access token could not be retrieved {}", e);

                        self.user.name = "".to_string();
                        self.user.email = "".to_string();
                        self.refresh_token = None;

                        self.save_me();

                        return false;
                    }
                };


    ...

The login via get_toek() can use the email address or suggest it in the mask. If there is a refresh token, this can be used first. For this case a login is not necessary. These values are passed.

The get_token() function:

...
    //get the google client ID and the client secret from .env file
    dotenv().ok();

    let google_client_id = ClientId::new(std::env::var("GOOGLE_CLIENT_ID")?);
    let google_client_secret = ClientSecret::new(std::env::var("GOOGLE_CLIENT_SECRET")?);
    let auth_url = AuthUrl::new("https://accounts.google.com/o/oauth2/v2/auth".to_string())?; //.expect("Invalid authorization endpoint URL");
    let token_url = TokenUrl::new("https://www.googleapis.com/oauth2/v3/token".to_string())?; //.expect("Invalid token endpoint URL");

    // Set up the config for the Google OAuth2 process.
    let client = BasicClient::new(
        google_client_id,
        Some(google_client_secret),
        auth_url,
        Some(token_url),
    )
    // This example will be running its own server at http://127.0.0.1:1421
    // See below for the server implementation.
    .set_redirect_uri(
        RedirectUrl::new("http://127.0.0.1:1421".to_string())?, //.expect("Invalid redirect URL"),
    )
    // Google supports OAuth 2.0 Token Revocation (RFC-7009)
    .set_revocation_uri(
        RevocationUrl::new("https://oauth2.googleapis.com/revoke".to_string())?, //.expect("Invalid revocation endpoint URL"),
    ); //.set_introspection_uri(introspection_url);
...

At this point, the client is initialised for the OAuth2 call with the URLs :
auth_url - Authentication
token_url - Token endpoint
redirect_uri - the Redirect URL, which is an additional server that accepts the token. This URL must be authenticated for the Google client.
revocation_uri- URL for revoking the token

If the refresh token is transferred, the authentication token is first requested with this token:

...
    if refresh_token.is_some() {
        println!("get_token() refresh_token found");

        match client
        .exchange_refresh_token(&refresh_token.unwrap().clone())
        .request_async(async_http_client)
        .await {
            Ok(token_response) => {
                let access_token = token_response.access_token().clone();
                let refresh_token = token_response.refresh_token().cloned();
                return Ok((access_token, refresh_token));
            },
            Err(_) => {},
        };
        println!("get_token() refresh_token not valid, login required");
    }
...

In this case, no new login is necessary.

A CSRF token is required for the login. The permissions requested from the application must be specified via Scope. Here, profile is required for the user data and email for the email address. If, for example, the email is to be queried via the Google Email API, the scope https://mail.google.com is required.

    // Google supports Proof Key for Code Exchange (PKCE - https://oauth.net/2/pkce/).
    // Create a PKCE code verifier and SHA-256 encode it as a code challenge.
    let (pkce_code_challenge, pkce_code_verifier) = PkceCodeChallenge::new_random_sha256();

    // Generate the authorization URL to which we'll redirect the user.
    let (authorize_url, csrf_state) = client
        .authorize_url(CsrfToken::new_random)
        // This example is requesting access to the "gmail" features and the user's profile.
        //.add_scope(Scope::new("https://mail.google.com".into()))
        .add_scope(Scope::new("profile email".into()))
        .add_extra_param("access_type", "offline")
        .add_extra_param("login_hint", email)
        //.add_extra_param("prompt", "none")
        .set_pkce_challenge(pkce_code_challenge)
        .url();

    println!("The authorization URL is:\n{}\n", authorize_url.to_string());
...

The extra_param control the login screen, the email address is pre-faded.

This authorize_url is now started in a new Tauri window:

...
    let handle = window.app_handle();

    let login_window = tauri::WindowBuilder::new(
        &handle,
        "Google_Login", /* the unique window label */
        tauri::WindowUrl::External(
            authorize_url.to_string().parse()?, //.expect("error WindowBuilder WindowUrl parse"),
        ),
    )
    .build()?; //.expect("error WindowBuilder build");
    login_window.set_title("Google Login");
    login_window.set_always_on_top(true);
...

Now, of course, a server must be started on the redirected URL, which then reads out the code and state from the URL or the error in the event of an error:

...
    // A very naive implementation of the redirect server.
    let listener = std::net::TcpListener::bind("127.0.0.1:1421")?; //.expect("error TcpListener bind");
    let local_addr = listener.local_addr()?;
...
    //this is blocking listener! we use guard schedule for time out
    for stream in listener.incoming() {
        let _ = login_window.is_visible()?; //check if login_window is visible

        if let Ok(mut stream) = stream {
            info!("listener stream");

            let code;
            let state;
            let errorinfo;
            {
                let mut reader = BufReader::new(&stream);

                let mut request_line = String::new();
                reader.read_line(&mut request_line)?;

                let redirect_url = match request_line.split_whitespace().nth(1) {
                    Some(url_data) => url_data,
                    _ => {
                        login_window.close()?;
                        break;
                    }
                };
                println!("redirect_url: \n{}", redirect_url.clone());
                let url = url::Url::parse(&("http://localhost".to_string() + redirect_url))?;

                use std::borrow::Cow;
                //extract code from url
                let code_pair = url
                    .query_pairs()
                    .find(|pair| {
                        let &(ref key, _) = pair;
                        key == "code"
                    })
                    .unwrap_or((Cow::from(""), Cow::from("")));

                let (_, value) = code_pair;
                code = AuthorizationCode::new(value.into_owned());

                //extract state from url
                let state_pair = url
                    .query_pairs()
                    .find(|pair| {
                        let &(ref key, _) = pair;
                        key == "state"
                    })
                    .unwrap_or((Cow::from(""), Cow::from("")));

                let (_, value) = state_pair;
                state = CsrfToken::new(value.into_owned());

                //extract error from url
                let errorinfo_pair = url
                    .query_pairs()
                    .find(|pair| {
                        let &(ref key, _) = pair;
                        key == "error"
                    })
                    .unwrap_or((Cow::from(""), Cow::from("")));

                let (_, value) = errorinfo_pair;
                errorinfo = String::from(value.into_owned());
            }
...

            // Exchange the code with a token.
            let token_response = match client
                .exchange_code(code)
                .set_pkce_verifier(pkce_code_verifier)
                .request_async(async_http_client)
                .await
            {
                Ok(res) => res,
                Err(err) => {
                    login_window.close()?;
                    Err("--  no permission --")?
                }
            };
...

With code and the pkce_code_verifier the access token is requested.

The Tauri window for the login must be closed at the right moment, furthermore, if the window is closed (CloseRequested) or if it times out, the login process must be aborted:

...
    let timer = timer::Timer::new();

    let _guard = timer.schedule_with_delay(chrono::Duration::seconds(25), move || {
        //the time out as connect to close server
        let _ = std::net::TcpStream::connect(local_addr); 
    });

    login_window.on_window_event(move |event| {
        if let WindowEvent::CloseRequested { api, .. } = &event {
        info!("event close-requested");
        let _ = std::net::TcpStream::connect(local_addr); //connect to server to close it
        };
    });

...

The timer or the event CloseRequested connects to the server, which then causes the login to be aborted.

The following answer provides StandardTokenResponse:

StandardTokenResponse {
    access_token: AccessToken([redacted]),
    token_type: Bearer,
    expires_in: Some(
        3599,
    ),
    refresh_token: Some(
        RefreshToken([redacted]),
    ),
    scopes: Some(
        [
            Scope(
                "https://www.googleapis.com/auth/userinfo.profile",
            ),
            Scope(
                "https://www.googleapis.com/auth/userinfo.email",
            ),
        ],
    ),
    extra_fields: EmptyExtraTokenFields,
}

3.6 Vue.js Client

The client was not implemented further for this example, only a get_user is started as invoke(..) when the app is created, name and email are displayed and the commands get_user() or logout() can be issued via a button.

  methods: {
    async on_login() {
      const that = this;
      invoke("js2rs", {
        message: "get_user"
      }).then((data: any) => {
        try {
          let me_data = JSON.parse(data)
          that.me.name = me_data.name ? me_data.name : "";
          that.me.email = me_data.email ? me_data.email : "";
        } catch (err) {
          console.error(err);
        }
        that.loading = false;
      });
    },
...
<template>
  <div>
    Name: {{ me.name }} <br>
    Email: {{ me.email }}
  </div>
  <div>
    <button v-if="me.email == ''"  type="button" @click="on_login()" style="background-color: green;">Log in</button>
    <button v-if="me.email != ''"  type="button" @click="on_logout()" style="background-color: red;">Log out</button>
    <button type="button" @click="on_end()" style="background-color: black;">End</button>
  </div>
</template>
...

4 Conclusion

Setting up OAuth2 authentication for Google and using it in Tauri is not easy, but it can be done. This is a simple way to link a Tauri app to a Google account or email.

The Rust Crate for OAuth provides nice examples, but you have to search and try out the details. All in all, the functions are ready for productive use.

(2023/10/01)
Index

Jul 16, 2023

MovieCat - PWA

Chrome App (PWA): Record from camera or screen and save as a movie.

MovieCat

App

It is a PWA app developed in Quasar and Vue with Tailwindcss. The application should be used in Chrome, because Chrome uses a certificate in interaction with a Mac, so that the application can access the screen, a camera or the microphone. Some other browsers do not support these functions!

Resolution, frame rate

Before starting the recording, the resolution and the frame rate should be adjusted. These settings determine the required memory or file size of the recording.

Compression

The media format depends on the capabilities of the browser. The file format and compression depend on these selections. The selection must be made before starting the recording.

Recording duration / memory size

Depending on the computer, the memory for the recording is limited, i.e. the recording is kept in blocks in the memory and this memory is limited to 4 GByte on a Mac with 64 bit operating system, for example. Depending on the resolution, frame rate and compression, the recording time is thus limited.

It would be possible to create several files, which you later join together with ffmpeg - this is not currently supported.

For decoding the WebM data, arrayBuffer objects are used; these are limited to 2 GByte - this function is only available for smaller files. The upload processes slices in 2 GByte blocks (array of blobs).

File api

If the function showDirectoryPicker is available, a card for a directory and file handling is displayed. A file can be read and also written to this directory when saving (download button/function). Depending on the mime type, only files with the defined extension are displayed and can be loaded. For WebM, the file is decoded and the metadata, e.g. duration, is determined. This function is asynchronous and depends on the file size, it needs a few seconds.

Supported codec

The supported codec depends on the browser - Chrome in version 113, for example, only supports WebM as a container and VP8, VP9 or H.264 for video encoding. The media player, however, can play mp4. For this reason, only files with the WebM extension are selected in the file api. The button for native upload also loads any other file. For ts (mpeg), for example, only the sound is decoded and played on. So if you need a player, you should use VLC.

Server

The application uses a server in go (gin-gonic), but node.js or any other can also be used. The go server works locally with generated certificates that have to be created in the /key directory. For testing, I generated the certificates on my local IP address, so that the server can start at another IP address without HTTPS and thus use HTTPS when deploying to Azure via the proxy there. If golang is deployed to the Azure Cloud, version 1.17 must be used.

Of course, node.js can also be used.

Please note: the application must either use HTTPS or localhost, which is a prerequisite for every PWA application.

Build

The application is generated with the following command:

quasar build -m pwa

In the configuration, minify: false can be set if the source code is to be analysed. In addition, useFilenameHashes: false can be used to prevent new file names from being generated again and again for the generated assets and, if necessary, to force the server to reload them.

2024/07/21: I have set publicPath to the path movie_cat. Also vite.config.js the variable base so that the programme runs on the sub-URI. This means that this repository can no longer be diployed directly to Azure.

The server is generated under linux (Azure Cloud) with the command env GOOS=linux GOARCH=amd64 go build -o server main.go . In the Azure Cloud, the server is then started /home/site/wwwroot/server. Of course, node.js can also be used.

(2023/04/01)

Jul 16, 2023

Rust: Tauri + Diesel + SQLite

Small documentation, tips and experiences for accessing a SQLite database from Rust with the ORM library diesel.
Complete and possibly extended code can be found in the repository archive_cat.

Requirements

I use the following library

[build-dependencies]
tauri-build = { version = "1.3", features = [] }

[dependencies]
tauri = { version = "1.4.1", features = ["shell-open", "window-close"] }
serde = { version = "1.0", features = ["derive"] }

serde_json = { version = "1.0", features = ["raw_value"] }
home = "0.5.5"
diesel = { version = "2.1.0", features = ["sqlite", "64-column-tables"] }
dotenvy = "0.15.7"
chrono = "0.4.26"
url = "2.4.0"
tokio = { version = "1.28.2", features = ["full"] }
tracing = "0.1.37"
tracing-subscriber = "0.3.17"
base64 = "0.21.2"

[dependencies.uuid]
version = "1.4.1"
features = [
    "v4",                # Lets you generate random UUIDs
    "fast-rng",          # Use a faster (but still sufficiently random) RNG
    "macro-diagnostics", # Enable better diagnostics for compile-time UUIDs
]

If necessary, install the libraries with cargo add xxx.

For the tauri installation please look here TAURI and for diesel here diesel.rs.


Connection with the database

The usual way is the access via a .env file. The access is somewhat dependent on the database, i.e., there are also databases that support pool-connections. For SQLite, the SqliteConnection::establish function should be used.

Example 1 database.rs:

use std::env;

use diesel::prelude::*;
use dotenvy::dotenv;
use tracing::info;

pub fn establish_connection() -> SqliteConnection {
    info!("start establish_connection()",);
    
    dotenv().ok();

    let database_url = env::var("DATABASE_URL")
        .expect("DATABASE_URL must be set");
    SqliteConnection::establish(&database_url)
        .unwrap_or_else(|_| panic!("Error connecting to the database: {}", 
            database_url))
}

Here the library dotenvy is taken for loading the .env file. The variable here has the name DATABASE_URL.

Example 2.env

DATABASE_URL=sqlite:///Users/jankstar/tauri_database.db

The database connection is then used as follows:

use crate::database::*;
...
    let mut conn = establish_connection();
...

Alternatively, the user’s home directory is accessed.

Example 3 database.rs

use diesel::prelude::*;
use tracing::info;
use home::home_dir;

pub fn establish_connection(database_filename: &str) -> SqliteConnection {
    info!("start establish_connection()",);

    let home_dir = home_dir().unwrap_or("").to_string(); 

    let database_url = format!("sqlite://{}/{}",
        home_dir.to_string_lossy(), 
        database_filename);

    SqliteConnection::establish(&database_url)
        .unwrap_or_else(|_| panic!("Error connecting to the database: {}", 
            database_url))
}

The database connection is then used as follows:

use crate::database::*;
...
    let mut conn = establish_connection("tauri_database.db");
...

Model and schema

The model defines the structure and the schema the database table. There is also the possibility to generate the rust objects from the database. I proceeded like this, but I had to adjust certain fields and settings, so here I present the working result.

Example 4 models.rs

use chrono::NaiveDateTime;
use diesel::{ Insertable, Queryable, Selectable, Table};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug, Selectable, Insertable, Queryable)]
#[diesel(table_name = crate::schema::document)]
pub struct Document {
    pub id: String,
    pub subject: String,
    pub status: String,
    pub date: String,
    pub sender_name: Option<String>,
    pub sender_addr: Option<String>,
    pub recipient_name: Option<String>,
    pub recipient_addr: Option<String>,
    pub from: Option<String>,
    pub to: Option<String>,
    pub body: Option<String>,
    pub document_type: Option<String>,
    pub metadata: Option<String>,
    pub category: Option<String>,
    pub amount: Option<f64>,
    pub currency: Option<String>,
    pub template_name: Option<String>,
    pub doc_data: Option<String>,
    pub input_path: Option<String>,
    pub langu: Option<String>,
    pub num_pages: Option<f64>,
    pub protocol: Option<String>,
    pub sub_path: Option<String>,
    pub filename: Option<String>,
    pub file_extension: Option<String>,
    pub file: Option<String>,
    pub base64: Option<String>,
    pub ocr_data: Option<String>,
    pub jpg_file: Option<String>,
    pub parent_document: Option<String>,
    pub created_at: String,
    pub updated_at: String,
    pub deleted_at: Option<String>,
}

schema.rs

table! {
    document (id) {
        id -> Text,
        subject -> Text,
        status -> Text,
        date -> Timestamp,
        sender_name -> Nullable<Text>,
        sender_addr -> Nullable<Text>,
        recipient_name -> Nullable<Text>,
        recipient_addr -> Nullable<Text>,
        from -> Nullable<Text>,
        to -> Nullable<Text>,
        body -> Nullable<Text>,
        #[sql_name = "type"]
        document_type -> Nullable<Text>,
        metadata -> Nullable<Text>,
        category -> Nullable<Text>,
        amount -> Nullable<Double>,
        currency -> Nullable<Text>,
        template_name -> Nullable<Text>,
        doc_data -> Nullable<Text>,
        input_path -> Nullable<Text>,
        langu -> Nullable<Text>,
        num_pages -> Nullable<Double>,
        protocol -> Nullable<Text>,
        sub_path -> Nullable<Text>,
        filename -> Nullable<Text>,
        file_extension -> Nullable<Text>,
        file -> Nullable<Text>,
        base64 -> Nullable<Text>,
        ocr_data -> Nullable<Text>,
        jpg_file -> Nullable<Text>,
        parent_document -> Nullable<Text>,
        #[sql_name = "createdAt"]
        created_at -> Timestamp,
        #[sql_name = "updatedAt"]
        updated_at -> Timestamp,
        #[sql_name = "deletedAt"]
        deleted_at -> Nullable<Timestamp>,
    }
}

Diesel features “64-column-tables”

In this example, more than 32 fields have been defined in the document table. For this case, the features “64-column-tables” must be set in the diesel: Cargo.toml

...
diesel = { version = "2.1.0", features = ["sqlite", "64-column-tables"] }
...

Change fieldname

In addition, field names that are not defined snake_case or correspond to invalid syntax in rust, e.g. type, must be mapped.

 #[sql_name = "type"]
 document_type -> Nullable<Text>,

Here the database field type is mapped to the rust field document_type.

CREATE TABLE IF NOT EXISTS

The library diesel does not yet directly support the creating of the tables. So if you want to create the tables first in an application with the start of the server, if they do not exist, then you have to implement the SQL statement itself. In my example I have defined the function check_tables in the file schema.rs.

Example 5:

use diesel::sqlite::Sqlite;
use diesel::debug_query;
use diesel::prelude::*;
use tracing::info;
pub fn check_tables(mut con: diesel::SqliteConnection) -> Result<usize, diesel::result::Error> {
    info!("start check_tables()");

    let mut sql_sing = concat!(
        "CREATE TABLE IF NOT EXISTS `document` (",
        "`id` TEXT NOT NULL PRIMARY KEY, ",
        "`subject` TEXT NOT NULL, ",
        "`status` TEXT NOT NULL, ",
        "`date` DATETIME NOT NULL, ",
        "`sender_name` TEXT DEFAULT '', ",
        "`sender_addr` TEXT DEFAULT '', ",
        "`recipient_name` TEXT DEFAULT '', ",
        "`recipient_addr` TEXT DEFAULT '', ",
        "`from` TEXT DEFAULT '[]', ",
        "`to` TEXT DEFAULT '[]', ",
        "`body` TEXT DEFAULT '', ",
        "`type` TEXT DEFAULT '', ",
        "`metadata` TEXT DEFAULT '{}', ",
        "`category` TEXT DEFAULT '[]', ",
        "`amount` DECIMAL(10,2) DEFAULT 0, ",
        "`currency` TEXT DEFAULT '', ",
        "`template_name` TEXT DEFAULT '', ",
        "`doc_data` TEXT DEFAULT '{}', ",
        "`input_path` TEXT DEFAULT '', ",
        "`langu` TEXT DEFAULT '', ",
        "`num_pages` NUMBER DEFAULT 0, ",
        "`protocol` TEXT DEFAULT '', ",
        "`sub_path` TEXT DEFAULT '', ",
        "`filename` TEXT DEFAULT '', ",
        "`file_extension` TEXT DEFAULT '',",
        "`file` TEXT DEFAULT '', ",
        "`base64` TEXT DEFAULT '', ",
        "`ocr_data` TEXT DEFAULT '', ",
        "`jpg_file` TEXT DEFAULT '[]', ",
        "`parent_document` TEXT DEFAULT '', ",
        "`createdAt` DATETIME NOT NULL, ",
        "`updatedAt` DATETIME NOT NULL, ",
        "`deletedAt` DATETIME ",
        ");"
    );

    let exec_query = diesel::sql_query(sql_sing.to_string());
    info!("debug sql\n{}", debug_query::<Sqlite, _>(&exec_query));
    exec_query.execute(&mut con)
}    

Selection of data

For the selection of data, a distinction must be made between two variants - on the one hand, a table can be accessed like an “object”, on the other hand, an SQL-like query is available under DSL. This must be differentiated already when including the libraries.

Select single by id

The simplest variant is the selection via the ID.

Example 6 - Read a document for a document ID:

use crate::database::*;
use crate::models::*;
use crate::schema;                // like document
use crate::schema::document::dsl; // like dsl::document
use crate::schema::Response;

use diesel::prelude::*;
use serde_json::json;
use tracing::{info, warn, error};
use tracing_subscriber;

...
        let mut conn = establish_connection("tauri_database.db");

        let my_document = match dsl::document   
            .filter(dsl::id.eq(my_query.id))
            .select(Document::as_select())
            .first::<Document>(&mut conn)
        {
            Ok(record) => record,
            Err(err) => {
                error!(?err, "Error: ");

                return Response {
                    dataname: data,
                    data: "[]".to_string(),
                    error: format!("{}", err),
                };
            }
        };

...

The fields of the selection are specified in .select(), in the example all fields. The type of the result must be specified after .first and must necessarily match the fields from .select.

Select a subset of the fields

Here it is very easy to define and select a subset of the fields using a separate structure. The definition of the structure has the advantage that also an object and if necessary a vector to this object can be defined.

Example 7 - select only certain fields: models.rs

#[derive(Serialize, Deserialize, Debug, Selectable, Queryable)]
#[diesel(table_name = crate::schema::document)]
pub struct  DocumentFile { 
    pub id: String,
    pub sub_path: Option<String>,
    pub filename: Option<String>,
    pub file_extension: Option<String>,
    pub file: Option<String>,
    pub base64: Option<String>,
}
...
        let mut conn = establish_connection("tauri_database.db");

        let my_document = match dsl::document
            .filter(dsl::id.eq(my_query.id))
            .select(DocumentFile::as_select())
            .first::<DocumentFile>(&mut conn)
        {
            Ok(record) => record,
            Err(err) => {
                error!(?err, "Error: ");

                return Response {
                    dataname: data,
                    data: "[]".to_string(),
                    error: format!("{}", err),
                };
            }
        };
...

Dynamic selection into a vector (local table)

An elegant variant for a dynamic selection is the definition query as BoxedDsl. This can be used to combine and dynamically generate order_by() or filter() sorts. In the following example, a URL is parsed dynamically and the selection conditions are built depending on the URL parameters. The notation is along the lines of `solr'.

For example 8:

http://localhost:8080/get_document?q=body:*Apple*&sort=date%20desc&rows=50

In this example, the string Apple is to be searched for in the field body. The records are sorted by the field date in descending order and the first 50 records are selected.

Example 9:

use crate::database::*;
use crate::models::*;
use crate::schema;
use crate::schema::document::dsl;
use crate::schema::Response;

use diesel::prelude::*;
use serde_json::json;
use tracing::info;
use tracing_subscriber;
use url::Url;
...
    let parsed_url = match Url::parse(&my_query_url) {
        Ok(result) => result,
        Err(err) => {
            return Response {
            dataname: path,
            data: "[]".to_string(),
            error: err.to_string(),
        }}
    };

    let mut query = dsl::document.into_boxed();

    let mut limit = 50;

    let mut search: String; // = "".to_string();

     //loop via URL parameter
    for pair in parsed_url.query_pairs() {
        info!(?pair, "document url pair");
        //------------------------------------
        if pair.0 == "rows" {
            //limit of rows parameter
            match pair.1.parse::<i64>() {
                Ok(v) => {
                    limit = v;
                }
                _ => {}
            };
        }
        //------------------------------------
        if pair.0 == "sort" {
            //sort parameter
            let mut sort_field_iter = pair.1.split_whitespace();
            let sort_field_name =  sort_field_iter.next().unwrap_or(r#""#);
            let sort_field_order =  sort_field_iter.next().unwrap_or(r#""#);
            match sort_field_name {
                "date" => {
                    if sort_field_order == "desc" {
                        query = query.order_by(dsl::date.desc());
                    } else {
                        query = query.order_by(dsl::date.asc());
                    }
                }
                "subject" => {
                    if sort_field_order == "desc" {
                        query = query.order_by(dsl::subject.desc())
                    } else {
                        query = query.order_by(dsl::subject.asc())
                    }
                }
                "status" => {
                    if sort_field_order == "desc" {
                        query = query.order_by(dsl::status.desc());
                    } else {
                        query = query.order_by(dsl::status.asc());
                    }
                }
                "amount" => {
                    if sort_field_order == "desc" {
                        query = query.order_by(dsl::amount.desc());
                    } else {
                        query = query.order_by(dsl::amount.asc());
                    }
                }
                _ => query = query.order_by(dsl::date.desc()),
            }
        }
        //------------------------------------
        if pair.0 == "q" {
            //where parameter
            let mut filter_field_iter = pair.1.split(':');
            let filter_field_name = filter_field_iter.next().unwrap_or(r#""#);
            let filter_field_match =  filter_field_iter.next().unwrap_or(r#""#);
            //the `*`from the transfer string into placeholder `%`for the selection
            search = String::from(str::replace(&filter_field_match, "*", "%"));
            match filter_field_name {
                "body" => query = query.filter(dsl::body.like(search)),
                "subject" => query = query.filter(dsl::subject.like(search)),
                "status" => query = query.filter(dsl::status.like(search)),
                "date" => query = query.filter(dsl::date.eq(search)),
                "amount" => {
                    //Conversion of the transfer string into a number
                    query = query.filter(dsl::amount.eq(search.parse::<f64>().unwrap_or(0_f64)))},
                "sender_name" => query = query.filter(dsl::sender_name.like(search)),
                "recipient_name" => query = query.filter(dsl::recipient_name.like(search)),
                "category" => query = query.filter(dsl::category.like(search)),

                _ => {}
            };
        }
    }

    let mut conn = establish_connection("tauri_database.db");

    match query
        .limit(limit)
        .filter(dsl::deleted_at.is_null())
        .select(DocumentSmall::as_select())
        .load::<DocumentSmall>(&mut conn)
    {
        Ok(result) => Response {
            dataname: path,
            data: json!(&result).to_string(),
            error: String::from(""),
        },
        Err(err) => Response {
            dataname: path,
            data: "[]".to_string(),
            error: err.to_string(),
        },
    }
...

The coding is not completely dynamic, because the used fields must have been defined in the structures of the database schema.rs and models.rs. Only the selection statemnt is dynamically assembled. In the example all conversions were also checked for validity by match, so that no panic is triggered, especially with transfer values from users.

SQL functions count(*) or sum(amount)

The standard functions in SQL for count(*) or sum(x) are available in diesel. But I only got the function count(*) to work, so here is the variant as native sql.

Example 10:

...
use crate::diesel::sqlite::Sqlite;
use crate::schema::document::dsl;
use diesel::debug_query;
use diesel::prelude::*;
use diesel::dsl::sql;
use diesel::sql_types::Double;
...

                let operation: &str;
                if path.as_str() == "chart_count" {       //parameter to control statement
                    operation = "count(id) AS count";     //count documents
                } else {
                    operation = "sum(amount) AS sum";     //sum the amount
                }

                let exec_query = document::table
                    .into_boxed()
                    .filter(
                        dsl::deleted_at
                            .is_null()
                            .and(dsl::date.le(local_start.to_string()))       //date from/to start datetime
                            .and(dsl::date.ge(local_end.to_string()))
                            .and(dsl::category.like(format!("%{}%", query)))  //query contains the selected category
                            .and(dsl::amount.is_not_null()),
                    )
                    .select(sql::<Double>(operation));

                info!("debug first sql\n{}", debug_query::<Sqlite, _>(&exec_query));
 
                let y_value = exec_query.first::<f64>(&mut conn).unwrap_or(0_f64);

It is a bit strange, but in the where condition the datatype is required to be dubble, because my field amount is of this type and the return value is f64 - the values are converted between FromSql/ToSql and the application.

Insert and update function

For an insert, the structure ‘Insertable’ must be entered.

Example 11:

...
#[derive(Serialize, Deserialize, Debug, Selectable, Insertable, Queryable, AsChangeset)]
#[diesel(table_name = crate::schema::document)]
pub struct Document {
    pub id: String,
    pub subject: String,
    pub status: String,
    pub date: String,
    ...
}

Subsequently, with an ‘insert’ and specification of the complete struture, processing can take place.

Example 12:

 match insert_into(document::dsl::document)
                .values(Document {
                    id: my_id,
                    subject: ele.subject.clone(),
                    status: ele.status.clone(),
                    date: ele.date.clone(),
                    sender_name: ele.sender_name.clone(),
                    sender_addr: ele.sender_addr.clone(),
                    recipient_name: ele.recipient_name.clone(),
                    recipient_addr: ele.recipient_addr.clone(),
                    from: Some(json!(from_partner).to_string()),
                    to: Some(json!(to_partner).to_string()),
                    body: ele.body.clone(),
                    document_type: Some("PDF".to_string()),
                    metadata: None,
                    //replace {} in []
                    category: Some(category_array.clone()),
                    //value round to 2 decimal places
                    amount: Some(amount_round),
                    currency: ele.currency.clone(),
                    template_name: ele.template_name.clone(),
                    doc_data: None,
                    input_path: ele.input_path.clone(),
                    langu: Some("DE".to_string()),
                    num_pages: None,
                    protocol: ele.protocol.clone(),
                    sub_path: ele.sub_path.clone(),
                    filename: data_attachment.filename.clone(),
                    file_extension: None,
                    file: data_attachment.file.clone(),
                    base64: None,
                    ocr_data: data_attachment.ocr_data.clone(),
                    jpg_file: Some(conv_obj_to_array(
                        data_attachment.jpg_file.clone().unwrap_or("[]".to_string()),
                    )),
                    parent_document: my_parent_document.clone(),
                    created_at: Local::now().to_string(),
                    updated_at: "".to_string(),
                    deleted_at: get_deleted_at(ele.deleted.clone()),
                })
                .execute(&mut akt_con)
            {
                Ok(_) => {}
                Err(err) => {
                    error!("insert document: {}", err)
                }
            };

For an update of a dataset you can use .set() or for all fields of the structure AsChangeset, i.e., in the model this macro is entered and then you can update all fields of this structure.

Example 13 models.rs:

...
use chrono::NaiveDateTime;
use diesel::{ Insertable, Queryable, Selectable, Table, AsChangeset};
use serde::{Deserialize, Serialize};
...

#[derive(Serialize, Deserialize, Debug, Selectable, Queryable, AsChangeset)]
#[diesel(table_name = crate::schema::document)]
pub struct  DocumentSmall {
    pub id: String,
    pub subject: String, 
    pub status: String,
    pub date: String,
    pub sender_name: Option<String>,
    pub sender_addr: Option<String>,
    pub recipient_name: Option<String>,
    pub recipient_addr: Option<String>,   
    pub from: Option<String>,
    pub to: Option<String>,
    pub category: Option<String>,
    pub amount: Option<f64>,   
    pub currency: Option<String>,
    pub body: Option<String>, 
    pub filename: Option<String>,
    pub file_extension: Option<String>,
    pub file: Option<String>,
    pub protocol: Option<String>,
}
...

The update is called with .filter(dsl::id.eq(my_document_new.id.clone()))) so that exactly one record gets the update. Several .set() are defined as tuples, in my example the structure my_document_new is set as AsChangeset and also the field updated_at is set to the current date and time.

Example 14:

...
    let database_name = format!("{}/{}", MAIN_PATH, DATABASE_NAME);
    let mut conn = establish_connection(&database_name);
...

 let exec_update = diesel::update(dsl::document
        .filter(dsl::id.eq(my_document_new.id.clone())))
        .set((
            &my_document_new,                            //update AsChangeset
            dsl::updated_at.eq(Local::now().to_string()) //update datetime
        ));
    info!("debug sql\n{}", debug_query::<Sqlite, _>(&exec_update));

    match exec_update.execute(&mut conn)
    {
        Ok(_) => {
            Response {
                dataname: path,
                data: json!(&my_document_new).to_string(),
                error: "".to_string(),
            }
        }
        Err(err) => {
            error!(?err, "Error: ");

            Response {
                dataname: path,
                data: "[]".to_string(),
                error: err.to_string(),
            }
        }
    }

Function debug_query extracts the statement for the output

There is also a function to output the generated SQL statement. In this case you separate selection and execution.

Example 15:

...
use diesel::debug_query;
use crate::diesel::sqlite::Sqlite;
use diesel::prelude::*;
use tracing::{error, info, warn};
use tracing_subscriber;
...

        let mut conn = establish_connection("tauri_database.db");

        let exec_query = dsl::document
            .filter(dsl::id.eq(my_query.id))
            .select(DocumentFile::as_select());
        info!("debug sql\n{}", debug_query::<Sqlite, _>(&exec_query));

        let my_document = match exec_query.first::<DocumentFile>(&mut conn) {
            Ok(record) => record,
            Err(err) => {
                error!(?err, "Error: ");

                return Response {
                    dataname: data,
                    data: "[]".to_string(),
                    error: format!("{}", err),
                };
            }
        };

The function debug_query extracts the statement for the output. Afterwards the execution and further processing of the data takes place.


Read PDF file to base64 conversion

In my example the name and path of the PDF file is in the SQLite database. In the examples shown above the file name from field file and also the path from field sub_path is read to the document ID exactly for one document. The files are in the home directory in a main directory MAIN_PATH belonging to the program and in this then in a FILE_PATH.

Example 16 - Definition of constants for the directories to be used in the home directory: database.rs

pub const MAIN_PATH: &str = r#"archive"#;
pub const DATABASE_NAME: &str = r#"tauri_database.db"#;
pub const FILE_PATH: &str = r#"data"#;

After the selection of the data from the database the following determination of the home directory takes place:

Example 17:

        info!(?my_document.id, "select document id" );
        info!(?my_document.sub_path, "select document subpath" );

        use home::home_dir;
        let home_dir = match home_dir() {
            Some(result) => result,
            None => {
                return Response {
                    dataname: data,
                    data: "[]".to_string(),
                    error: r#"no pdf found"#.to_string(),
                };
            }
        };

        let filename = my_document.file.unwrap_or("".to_string());
        if filename.is_empty() {
            return Response {
                dataname: data,
                data: "[]".to_string(),
                error: r#"no pdf found"#.to_string(),
            };
        }

        //Build PDF Filenames
        let pdf_file = format!(
            "{}/{}/{}/{}{}",
            home_dir.to_str().unwrap_or("").to_string(),
            MAIN_PATH,
            FILE_PATH,
            my_document.sub_path.unwrap_or("".to_string()),
            filename
        );
        info!(?pdf_file, "select document file");

At the end pdf_file contains the complete path for accessing the file, so that now the file can be opened and loaded as binary into a variable list_of_chunks of type Vec<u8>.

Example 18:

        //open file by name
        let mut file = match std::fs::File::open(&pdf_file) {
            Ok(file) => file,
            Err(err) => {
                error!(?err, "Error: ");

                return Response {
                    dataname: data,
                    data: "[]".to_string(),
                    error: format!("{}", err),
                };
            }
        };
        info!(?filename, "open file by name ");

        //Read PDF as binary file
        use std::io::{self, Read, Seek, SeekFrom};
        let mut list_of_chunks = Vec::new();
        let chunk_size = 0x4000;

        loop {
            let mut chunk = Vec::with_capacity(chunk_size);
            let n = match file
                .by_ref()
                .take(chunk_size as u64)
                .read_to_end(&mut chunk)
            {
                Ok(data) => data,
                Err(err) => {
                    info!(?err, "error file read");
                    break;
                }
            };
            if n == 0 {
                break;
            }
            for ele in chunk {
                list_of_chunks.push(ele);
            }
            if n < chunk_size {
                break;
            }
        }

The data from the PDF file is now in list_of_chunks and is converted to base64 and returned.

Example 19:

       if list_of_chunks.len() != 0 {
            //binary encode to base64
            use base64::{engine::general_purpose, Engine as _};
            let base64_data = general_purpose::STANDARD.encode(list_of_chunks);

            return Response {
                dataname: data,
                data: json!(&base64_data).to_string(),
                error: "".to_string(),
            };

Tauri server

Communication between Tauri and Vue

Finally an info about the communication between Tauri and Vue. For this I can recommend the very good documentation at Rob Donnelly. I have implemented this variant. The transfer from/to Vue is always done as string in the end, so all structures have to be converted in and out as json string.

Example 20 - Vue javascript file to call Tauri

  import { invoke } from "@tauri-apps/api/tauri";
...
      invoke("js2rs", {
        message: JSON.stringify({
          path: "category",
          query: "?json=true",
          data: "category",
        }),
      });
...

In my example, the message field is transmitted as a JSON string and then needs to be parsed in Tauri into the path, query and data components.

Example 21 Tauri command for the invoke:

#[tauri::command]
async fn js2rs(message: String, state: tauri::State<'_, AsyncProcInputTx>) -> Result<(), String> {
    let mut sub_message = message.clone();
    sub_message.truncate(50);
    info!(?sub_message, "js2rs");
    let async_proc_input_tx = state.inner.lock().await;
    async_proc_input_tx.send(message).await.map_err(|e| {
        println!("{}", e.to_string());
        e.to_string()
    })
}

Here the string is sent into the channel async_proc_input_tx to be processed one after the other.

Example 22.

async fn async_process_model(
    mut input_rx: mpsc::Receiver<String>,
    output_tx: mpsc::Sender<String>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    while let Some(input) = input_rx.recv().await {
        let mut parse_error = false;
        let my_input_data: Receiver = match serde_json::from_str(input.as_str()) {
            Ok(data) => data,
            Err(err) => {
                parse_error = true;
                let my_output_data = Response {
                    dataname: "".to_string(),
                    data: "[]".to_string(),
                    error: err.to_string()
                };
                let output = json!(my_output_data).to_string();
                match output_tx.send(output).await {
                    _ => {}
                }
                Receiver {
                    path: "".to_string(),
                    query: "".to_string(),
                    data: "[]".to_string()
                }
            }
        };

        if !parse_error {
            let my_output_data: Response =
                message_handler(my_input_data.path, my_input_data.query, my_input_data.data).await;
            let output = json!(my_output_data).to_string();
            match output_tx.send(output).await {
                _ => {}
            }
        } 
    }

    Ok(())
}

There are the following structures in my example that are converted between Tauri and Vue:

Example 23 from schema.rs.

#[derive(serde::Serialize, Debug)]
pub struct Response {
    pub dataname: String,
    pub data: String,
    pub error: String,
}

#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct Receiver {
    pub path: String,
    pub query: String,
    pub data: String,
}

Central data app_data

In the Tauri - Vue communication, the tauri-handler contains a Stauts parameter that controls the processing of the channel. Similarly, in my application I need central information that the server manages and that should be available in the handlers, i.e., read, used or changed there and persistently saved. I decided to use a json file in the home directory. With the start of the server the data is read or, if the file does not exist, initialized and if the user maintains the data from the Vue application, the data should be written into the corresponding file.

First we need the data structure and the functions for reading, changing and saving.

Example 24 main.rs

#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct AppData {
    pub main_path: String,
    pub email: String,
    pub name: String,
    pub clone_dir: String,
}

impl AppData {

    //constructor from `app_data` as clone() 
    pub fn new(app_data: &AppData) -> Self {
        info!("AppData new()");

        AppData {
            main_path: app_data.main_path.clone(),
            email: app_data.email.clone(),
            name: app_data.name.clone(),
            clone_dir: app_data.clone_dir.clone(),
        }
    }

    //constructor from file 
    pub fn init_app_data() -> Self {
        info!("AppData init_app_data()");

        let home_dir = home_dir().unwrap_or("".into());

        let file_and_path = format!(
            "{}/{}",
            home_dir.to_str().unwrap_or("").to_string(),
            database::APP_DATA_FILENAME
        );

        use std::fs::read_to_string;
        let app_data_string = read_to_string(file_and_path).unwrap_or("".to_string());

        let app_data = match serde_json::from_str(&app_data_string) {
            Ok(result) => result,
            Err(err) => {
                error!(?err, "Error: ");
                AppData {
                    main_path: database::MAIN_PATH.to_string(),
                    email: "".to_string(),
                    name: "".to_string(),
                    clone_dir: "".to_string(),
                }
            }
        };
        return app_data;
    }

    pub fn set(&mut self, main_path: String, email: String, name: String, clone_dir: String) {
        self.main_path = main_path;
        self.email = email;
        self.name = name;
        self.clone_dir = clone_dir;
        self.save_me();
    }

    pub fn save_me(&self) {
        info!("AppData save_me()");

        let home_dir = home_dir().unwrap_or("".into());

        let file_and_path = format!(
            "{}/{}",
            home_dir.to_str().unwrap_or("").to_string(),
            database::APP_DATA_FILENAME
        );

        let app_data_json = json!(self).to_string();

        match fs::write(file_and_path, app_data_json) {
            Ok(_) => {}
            Err(err) => {
                error!(?err, "Error: ");
            }
        };
    }
}

There are two constuctor here - once with new(data) a new object is created over the passed data, on the other hand with the function init_app_data(), here we read from the file and generate the object. In both cases the instance of AppData is returned.

The file itself with the data from AppData is always read or written into the home directory with the name defined as from APP_DATA_FILENAME. There is now the function set(data) which also calls save_me() and finally saves the data as a json file.

In the main routine in the tauri server, the object can be passed via manage() and is then available optinally as a parameter in dan tauri-handlers.

Example 25:

fn main() {
    tracing_subscriber::fmt::init();

    generate_directory_database();

    let (async_proc_input_tx, async_proc_input_rx) = mpsc::channel(1);
    let (async_proc_output_tx, mut async_proc_output_rx) = mpsc::channel(1);

    tauri::Builder::default()
        .manage(AsyncProcInputTx {                         // Mutex to manage
            inner: Mutex::new(async_proc_input_tx),
        })
        .manage(AppData::init_app_data())                  // AppData to manage
        .invoke_handler(tauri::generate_handler![js2rs])   // tauri handler
        .setup(|app| {
            tauri::async_runtime::spawn(async move {
                async_process_model(async_proc_input_rx, async_proc_output_tx).await
            });

            let app_handle = app.handle();
            tauri::async_runtime::spawn(async move {
                loop {
                    if let Some(output) = async_proc_output_rx.recv().await {
                        rs2js(output, &app_handle);
                    }
                }
            });

            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

The tauri handler js2rs can now receive the new parameter:

Example 26:

#[tauri::command]
async fn js2rs(
    message: String,
    state: tauri::State<'_, AsyncProcInputTx>,
    app_data: tauri::State<'_, AppData>,
) -> Result<(), String> {
    let mut sub_message = message.clone();
    sub_message.truncate(50);
    info!(?sub_message, "js2rs");

    let async_proc_input_tx = state.inner.lock().await;
    async_proc_input_tx
        .send((message, AppData::new(app_data.inner())))
        .await
        .map_err(|e| {
            println!("{}", e.to_string());
            e.to_string()
        })
}

Async process model

Because at this point processing does not yet take place, but the data is first passed into a channel for asynchronous processing, the Message and AppData must be passed as tuples and the type of the Input parameter must also be adjusted.

Example 27:

...
struct AsyncProcInputTx {
    inner: Mutex<mpsc::Sender<(String, AppData)>>,
}
...
async fn async_process_model(
    mut input_rx: mpsc::Receiver<(String, AppData)>,     //input tuple with AppData
    output_tx: mpsc::Sender<String>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    while let Some((message, app_data)) = input_rx.recv().await {
        let mut parse_error = false;
        let my_message_data: Receiver = match serde_json::from_str(message.as_str()) {
            Ok(data) => data,
            Err(err) => {
                parse_error = true;
                let my_output_data = Response {
                    dataname: "".to_string(),
                    data: "[]".to_string(),
                    error: err.to_string(),
                };
                let output = json!(my_output_data).to_string();
                match output_tx.send(output).await {
                    _ => {}
                }
                Receiver {
                    path: "".to_string(),
                    query: "".to_string(),
                    data: "[]".to_string(),
                }
            }
        };

        if !parse_error {
            let my_output_data: Response = message_handler(
                app_data,                                     //app_data as parameter
                my_message_data.path,
                my_message_data.query,
                my_message_data.data,
            )
            .await;
            let output = json!(my_output_data).to_string();
            match output_tx.send(output).await {
                _ => {}
            }
        }
    }

    Ok(())
}

To do this, the channel and also the async_process_model function must be adapted accordingly and the app_Data parameter extended.

Tauri command message handler

In the tauri handler itself the object AppData can then be used. In my example there is user for reading and save_user for saving from the application.

Example 28:

#[tauri::command(async)]
async fn message_handler(
    //window: tauri::Window,
    //database: tauri::State<'_, Database>,
    mut app_data: AppData,
    path: String,
    query: String,
    data: String,
) -> Response {
    let message = format!(
        "path: {}, query: {}, data: {}",
        path.as_str().clone(),
        query.as_str().clone(),
        data.as_str().clone()
    );
    info!(message, "message_handler");
    io::stdout().flush().unwrap();

    match path.as_str() {
        //----
        "user" => {
            let home_dir = home_dir().unwrap();
            let message = format!("Your home directory, probably: {}", home_dir.display());
            info!(message, "message_handler");

            let my_data = json!( UserData {
                email: app_data.email,
                name: app_data.name,
                path_name: app_data.main_path,
                clone_path: app_data.clone_dir,
                avatar: "".to_string()
            }).to_string();

            Response {
                dataname: "me".to_string(),
                data: my_data,
                error: "".to_string(),
            }
        }
        //----
        "save_user" => {
            let my_save_user_data: SaveUserCommand = match serde_json::from_str(&data) {
                Ok(result) => result,
                Err(err) => {
                    error!(?err, "Error: ");

                    return Response {
                        dataname: data,
                        data: "[]".to_string(),
                        error: format!("{}", err),
                    };
                }
            };

            app_data.set(
                my_user_data.path_name.clone(),
                my_user_data.email.clone(),
                my_user_data.name.clone(),
                my_user_data.clone_path.clone(),
            );

            let my_data = json!(my_user_data).to_string();

            Response {
                dataname: "me".to_string(),
                data: my_data,
                error: "".to_string(),
            }
        }

...

    }
}

The save_user for the function set(data) off, which then also writes the data to the home directory, so that after a restart this data can be read.

Client invoke

On the client side in Vue, simply start the invoke with the data:

Example 29 MainLayout.vue:

  import { invoke } from "@tauri-apps/api/tauri";

...

      saveDialogMe() {
        console.log(`MainLayout saveDialogMe()`);

        this.me.name = this.dialogMeData.name || "";
        this.me.email = this.dialogMeData.email || "";
        this.me.path_name = this.dialogMeData.path_name || "";
        this.me.clone_path = this.dialogMeData.clone_path || "";
        this.me.avatar = this.getGravatarURL(this.me.email);
        invoke("js2rs", {
          message: JSON.stringify({
          path: "save_user",
          query: "",
          data: JSON.stringify(this.me),
        })});
        this.dialogMe = false;
      },
...

The avatar is determined on the client, that must be released for the access in the Tauri tauri.conf.json.

Client event listener

The communication from rust to Vue (Javascript) is done via a listener. This is registered in MainLayout.vue at the time create() and requests at this point also the user data via invoke.

Example 30:

async created() {
    console.log(`MainLayout created()`);

    const that = this;

    await listen('rs2js', (event) => {
      try {
        that.loading = false;

        let data = JSON.parse(event.payload);
        if (data.data) {
          data.data = JSON.parse(data.data);
        }

        let { dataname: lDataName, data: lData, error: lError } = data;
        console.log("listen rs2js event ", lDataName);

        if (lError) {
          that.$q.notify({
            message: "Error: " + lError,
            color: "negative",
            icon: "warning",
          });
          console.error(`Error listen rs2js event ${lError}`)
          return;
        }

        if (!lData || !lDataName) {
          return;
        }

        if (lDataName == "me") {
          that[lDataName] = lData;
          if (that.me.email) {
            that.me.avatar = that.getGravatarURL(that.me.email);
          }
        }

        that.ServerData = { dataname: lDataName, data: lData, error: lError };
      } catch (err) {
        console.error("listener rs2js error ", err);
      }
      return;
    });

    this.loading = true;

    invoke("js2rs", {
      message: JSON.stringify({
        path: "user",
        query: "?json=true",
        data: "me",
      })
    });

  },

In this example, the variable ServerData is distributed to the other Vue Componets depending on which one is currently active.


Conclusion

Rust is like any other programming language: you have to study it to understand it. Some features allow elegant programming, others are incomprehensible and make it difficult to use. There is always light and shadow. For the error messages of the compiler you quickly get a feeling what you did wrong, it is merciless. The language could be more understandable and coherent in my opinion, other programming languages are much better.

Dynamic parameters and also the forced error handling are really good. It creates a robust program, even if it takes a little longer. The channels reminded me of golang, but the powerful promise from JavaScript is not nearly reached.

Some of the libraries are still in their infancy, it will take some time to establish stability for productive use, but the path is the right one. In some places, one wishes for better documentation and more examples - which is what I tried to do with this post.

Thanks to the hardworking developers of dieseland tauri- it was fun and I will continue down the path because you can’t process media data in Electron for example and that runs in tauri, that’s my next project.

(2023/08/01)
Index