예제 #1
0
            'filename': os.path.join(BASE_DIR, 'joplin_web.log'),
            'maxBytes': 61280,
            'backupCount': 3,
            'formatter': 'verbose',
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins', 'file'],
            'level': 'ERROR',
            'propagate': True,
        },
        'joplin_web.app': {
            'handlers': ['console', 'file'],
            'level': 'INFO',
        }
    }
}

# CONFIG TO GET DATA FROM JOPLIN
JOPLIN_WEBCLIPPER_TOKEN = env.str('JOPLIN_WEBCLIPPER_TOKEN', default='')

# check if Joplin is started
joplin = JoplinApiSync(token=JOPLIN_WEBCLIPPER_TOKEN)
try:
    joplin.ping()
except httpx.ConnectError:
    console.print("/!\ Joplin is not started, launch it first of all",
                  style="red")
    exit(0)
예제 #2
0
"""
from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from joplin_api import JoplinApiSync
from joplin_web.forms import NoteForm, FolderForm, TagForm
from joplin_web.utils import tag_for_notes
import logging

from rich import console
console = console.Console()

logger = logging.getLogger("joplin_web.app")

joplin = JoplinApiSync(token=settings.JOPLIN_WEBCLIPPER_TOKEN)


def home(request, *args, **kwargs):
    template_name = "index.html"
    form_folder = FolderForm()
    form_tag = TagForm()
    res = joplin.get_notes()
    notes = tag_for_notes(res)

    form = NoteForm(request.POST or None)
    if request.POST:
        if form.is_valid():
            title = form.cleaned_data['title']
            text = form.cleaned_data['text']
            parent_id = form.cleaned_data['parent_id']
예제 #3
0
    def export_to_joplin(self, token: str, nsx_content: dict) -> None:
        """exports notes to joplin

        parameters
        ----------
        token : str
            authorization token. within the joplin app, go to
            tools/options/web clipper to find token.
        nsx_content : dict
            python dictionary with keys 'notebooks' and 'notes'.
            it will contain all relevant extracted information
            that will be necessary to use for an import into
            another note taking app.

        returns
        -------
        none
        """
        joplin = JoplinApiSync(token=token)

        def create_folder(notebook_title):
            res = joplin.create_folder(folder=notebook_title)
            data = res.json()
            parent_id = data["id"]
            assert type(parent_id) is str

            return parent_id

        def create_resource(attachments, content, attachment_path):
            for index, attachment in enumerate(attachments, start=0):

                attachment_type = attachment["type"]
                name = attachment["name"]

                res = joplin.create_resource(attachment_path.joinpath(name),
                                             **{"title": name})
                resource_id = res.json()["id"]
                attachments[index]["joplin_resource_id"] = resource_id
                assert res.status_code == 200

                if attachment_type == "image":
                    content = re.sub(
                        r"!\[\]\(.*\)",
                        f"![{name}](:/{resource_id})",
                        content,
                        1,
                    )
                elif attachment_type == "binary":
                    content = f"[{name}](:/{resource_id})\n\n" + content

            return content

        def create_note(
            joplin_id,
            note_title,
            note_content,
            note_tags,
            user_created_time,
            user_updated_time,
        ):
            body = note_content
            assert type(body) is str
            kwargs = {
                "tags": note_tags,
                "user_created_time": user_created_time,
                "user_updated_time": user_updated_time,
            }
            res = joplin.create_note(title=note_title,
                                     body=body,
                                     parent_id=joplin_id,
                                     **kwargs)
            assert res.status_code == 200

        for notebook in nsx_content["notebooks"]:
            joplin_id = create_folder(notebook["title"])

            # filter notes that belong to current notebook
            filtered_notes = [
                note for note in nsx_content["notes"]
                if note["parent_nb_id"] == notebook["id"]
            ]
            num_filtered_notes = len(filtered_notes)

            for idx, note in enumerate(filtered_notes, start=1):

                print(
                    f"writing note {idx}/{num_filtered_notes} in {notebook['title']}: "
                    f"{note['title']}")

                # transform list of tags to string
                tag = None
                if note["tag"]:
                    tag = ",".join(note["tag"])

                # create resource, if necessary
                if note["attachment"]:
                    note["content"] = create_resource(
                        attachments=note["attachment"],
                        content=note["content"],
                        attachment_path=notebook["media_path"],
                    )
                create_note(
                    joplin_id=joplin_id,
                    note_title=note["title"],
                    note_content=note["content"],
                    note_tags=tag,
                    user_created_time=note["ctime"] * 1000,
                    user_updated_time=note["mtime"] * 1000,
                )

                if idx % 1000 == 0:
                    seconds = 300
                    print(
                        f"sleep for {seconds} seconds in order to not crash joplin web "
                        "clipper")
                    time.sleep(seconds)
                elif idx % 500 == 0:
                    seconds = 120
                    print(
                        f"sleep for {seconds} seconds in order to not crash joplin web "
                        "clipper")
                    time.sleep(seconds)