Contribution : Gnote to Joplin converter

Hi, it's my contribution for Joplin, it's a Python 3 script working with web clipper API. (Then you need to enable it.) :grinning:

After that, just do somes $ python3 script.py

Then the script convert all gnote notes to Joplin, with chronologic order (modification/created)

Of course, Joplin should be started before running this script :grin:

import os
import re
import time
import datetime
import json
import requests

# Joplin API configuration
JOPLIN_API_BASE_URL = "http://localhost:41184"  # Ensure the Joplin API is accessible
JOPLIN_API_TOKEN = "your_token_api_joplin"  # Replace with your Joplin API token

# Gnote notes directory
gnote_directory = os.path.expanduser("~/.local/share/gnote")  # Default path for Gnote

# Function to create a notebook in Joplin
def create_joplin_notebook(title):
    headers = {'Content-Type': 'application/json'}
    data = {'title': title}
    response = requests.post(f"{JOPLIN_API_BASE_URL}/folders?token={JOPLIN_API_TOKEN}", headers=headers, data=json.dumps(data))
    if response.status_code == 200:
        notebook_id = response.json()['id']
        print(f"Notebook '{title}' created successfully. ID: {notebook_id}")
        return notebook_id
    else:
        print(f"Error creating notebook '{title}': {response.text}")
        return None

# Function to create a note in Joplin
def create_joplin_note(title, body, created_time, updated_time, notebook_id):
    headers = {'Content-Type': 'application/json'}
    data = {
        'title': title,
        'body': body,
        'parent_id': notebook_id,
        'user_created_time': created_time,
        'user_updated_time': updated_time,
    }
    response = requests.post(f"{JOPLIN_API_BASE_URL}/notes?token={JOPLIN_API_TOKEN}", headers=headers, data=json.dumps(data))
    if response.status_code != 200:
        print(f"Error creating note '{title}': {response.text}")
    else:
        print(f"Note '{title}' created successfully.")

# Function to clean specific Gnote tags
def remove_gnote_tags(text):
    text = re.sub(r'<link:.*?>(.*?)</link:.*?>', r'\1', text)  # Remove <link:...> tags
    text = re.sub(r'<size:.*?>|</size:.*?>', '', text)  # Remove <size:...> tags
    text = re.sub(r'<[^>]+>', '', text)  # Remove any other XML tags
    return text

# Function to convert dates to timestamps
def convert_to_timestamp(date_str):
    # Replace the comma with a dot for a compatible format
    date_str = date_str.replace(',', '.')
    try:
        return int(datetime.datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%fZ").timestamp() * 1000)
    except ValueError:
        try:
            return int(datetime.datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%SZ").timestamp() * 1000)
        except ValueError:
            print(f"Unrecognized date format for date: {date_str}")
            return None

# Main function to convert notes
def convert_notes():
    # Create the notebook in Joplin
    notebook_id = create_joplin_notebook("Gnote Imports")
    if notebook_id:
        for filename in os.listdir(gnote_directory):
            if filename.endswith(".note"):
                filepath = os.path.join(gnote_directory, filename)
                
                with open(filepath, 'r') as file:
                    content = file.read()
                    
                    # Extract title, body, and dates
                    title = re.search(r'<title>(.*?)</title>', content).group(1)
                    body = re.search(r'<note-content .*?>(.*?)</note-content>', content, re.DOTALL).group(1)
                    body = remove_gnote_tags(body)  # Clean specific tags
                    created_time = re.search(r'<create-date>(.*?)</create-date>', content).group(1)
                    updated_time = re.search(r'<last-change-date>(.*?)</last-change-date>', content).group(1)
                    
                    # Convert dates to timestamp
                    created_timestamp = convert_to_timestamp(created_time)
                    updated_timestamp = convert_to_timestamp(updated_time)
                    
                    if created_timestamp and updated_timestamp:
                        # Create the note in Joplin
                        create_joplin_note(title, body, created_timestamp, updated_timestamp, notebook_id)

# Execute the note conversion
convert_notes()
2 Likes