GithubHelp home page GithubHelp logo

foosoft / anki-connect Goto Github PK

View Code? Open in Web Editor NEW
1.9K 41.0 218.0 715 KB

Anki plugin to expose a remote API for creating flash cards.

Home Page: https://foosoft.net/projects/anki-connect/

License: Other

Python 99.22% Shell 0.78%
anki

anki-connect's Introduction

anki-connect's People

Contributors

abdnh avatar antistic avatar aquafina-water-bottle avatar bertoncelj1 avatar c-okelly avatar charleshenry avatar corollari avatar degrangem avatar derxe avatar feilongfl avatar foosoft avatar glutanimate avatar grepmew avatar hgiesel avatar introt avatar itsmepvr avatar mikkkee avatar oakkitten avatar renebrals avatar ripose-jp avatar salkrr avatar snoyes avatar sudarshang avatar tatsumoto-ren avatar techdavid avatar thiswillbeyourgithub avatar toasted-nutbread avatar tsmgodoi avatar z1lc avatar zhengpeiru21 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

anki-connect's Issues

Space or other symbols between words within Deck name.

Hello.
On the following points - doesn't works cause the Deck name has space or other symbols (e.g., brackets) between words:

  • [deleteDecks]
  • [findCards]
  • ... [didn't check the rest of]

I can rename are existing and reformat the following, but maybe is it possible to add some regexp to fix this?

Thanks in advance.

Exposing an API for synchronize in anki-connect

Thanks for releasing anki-connect. It works great from the emacs anki-editor plugin. I want to add a command to the anki-editor plugin to ensure that new cards added from the plugin are synchronized to anki web so that I can access them from my ios app. For this to work the anki-connect plugin needs to expose an API that calls the anki sync functionality. Please let me know how I should go about implementing this.

changeDeck api doesn't work for Anki 2.0.52 on Win7

Hi, I have used several anki-connect apis to develop some cmdline tools to help me to deal with English words automatically using Node.js, but today I find the changeDeck api doesn't work. Although the return result show that the operation is successful, but the card's deck just doesn't change when I check in the Anki Browser.
Finally, thanks for your great job!

Calling suspend resets the progress of part-learned cards

Just posting this in case you can figure out the problem - I've been trying to make it work but haven't been successful.

When suspend is called it resets the progress of any part-learned cards (= new cards that have been marked good 10min, but not good 1d yet) in any deck, regardless which cards have been suspended. The unsuspend function doesn't cause this.

From looking at the relevant file in the Anki source code (line 1265) this means it's either caused by remFromDyn line 981 or removeLrn line 682 (probably the latter). The problem also occurs when calling the following in the dev console - but does not occur when suspending from the browser:

aqt.mw.col.sched.suspendCards([])  # array can be empty, or have any CIDs - problem still occurs

When cards are suspended from the browser, the onSuspend function (line 1250) is run, which in turn runs saveNow (line 300 + 390 for saveTags). However, the editor object isn't accessible from add-ons unless you create the editor from within the add-on, and I get the feeling this isn't what's causing the problem.

I've tried wrapping the function with startEditing() / stopEditing() but this doesn't work. Any ideas what could be the problem?

RuntimeError when importing both PyQt4 and 5 inside anki 2.1

I have both pyqt4 and pyqt5 installed, so the ImportError check won't help here.

An error occurred in an add-on.
Please post on the add-on forum:
https://anki.tenderapp.com/discussions/add-ons

Traceback (most recent call last):
  File "/usr/share/anki/aqt/addons.py", line 47, in loadAddons
    __import__(file.replace(".py", ""))
  File "/home/dx/.local/share/Anki2/addons21/AnkiConnect.py", line 53, in <module>
    from PyQt4.QtCore import QTimer
RuntimeError: the PyQt4.QtCore and PyQt5.QtCore modules both wrap the QObject class

This works for me:

try:
    QTimer = aqt.QTimer
    QMessageBox = aqt.QMessageBox
except AttributeError:
    try:
        from PyQt4.QtCore import QTimer
        from PyQt4.QtGui import QMessageBox
    except ImportError:
        from PyQt5.QtCore import QTimer
        from PyQt5.QtWidgets import QMessageBox

(Also, thanks for writing this plugin and yomichan! I was looking for a webextensions replacement to rikaichan, didn't actually expect this upgrade in functionality!)

<class 'TypeError'>: Object of type 'map' is not JSON serializable

I tried with beta 42 and the latest AnkiConnect from 2018-06-24. This is the only addon installed. I don't call AnkiConnect directly but from within an emacs package that's called anki-editor. This package allows to send/push notes to AnkiConnect. When I run the "push" command in this package I get the following error message in Anki.

This emacs package works fine with AnkiConnect in 2.0.52. So I assume that the problem is not with this emacs-package? I don't know about the internals of emacs/elisp so I can't tell you what exactly is sent to AnkiConnect. Nevertheless I decided to post because this error message might still be useful for you ? If you feel that a novice like me can help with further information just give me instructions on what to do.

Anyway thanks for your great software.


Debug info:
Anki 2.1.0beta42 Python 3.6.2 Qt 5.9.2 PyQt 5.9
Platform: Linux
Flags: frz=True ao=True sv=1

Caught exception:
  File "/the/path/to/profile/addons21/2055492159/__init__.py", line 293, in advance
    self.server.advance()
  File "/the/path/to/profile/addons21/2055492159/__init__.py", line 204, in advance
    self.advanceClients()
  File "/the/path/to/profile/addons21/2055492159/__init__.py", line 219, in advanceClients
    self.clients = list(filter(lambda c: c.advance(), self.clients))
  File "/the/path/to/profile/addons21/2055492159/__init__.py", line 219, in <lambda>
    self.clients = list(filter(lambda c: c.advance(), self.clients))
  File "/the/path/to/profile/addons21/2055492159/__init__.py", line 126, in advance
    self.writeBuff += self.handler(req)
  File "/the/path/to/profile/addons21/2055492159/__init__.py", line 238, in handlerWrapper
    body = makeBytes(json.dumps(self.handler(params)))
  File "json/__init__.py", line 231, in dumps
  File "json/encoder.py", line 199, in encode
  File "json/encoder.py", line 257, in iterencode
  File "json/encoder.py", line 180, in default
<class 'TypeError'>: Object of type 'map' is not JSON serializable

Ability to create custom note types.

I'd like the ability to add custom note types.

With Polar I want the ability to add new fields like Author, URL, screenshot, so that when I sync over notes they have extended metadata.

Right now I can only use the pre-existing note types ...

Is there ability to create a new empty deck?

Apologies in advance if I have missed something in the docs but is there a specific action to create an empty deck? Or is there a reason that this functionality is not supported?

Thanks for releasing anki-connect!

[feature request] a optional parameter for doe option.

in line#371-372, there is a control to avoid duplication.

        if not note.dupeOrEmpty():
            return note

But, sometimes, people need make duplicated cards while headword having multi-meaning.
They want to make one card each time when they read it in different context.

book

Currently, I hardcode it like below and distribute it in my learning English community to those who may want "duplicated card" feature.

        doe = note.dupeOrEmpty()
        if not doe or doe == 2:
            return note

Recently, I noticed you made some new code to detect version and upgrade itself.
So, I want to all my users can just keep same version( not customized)

Use Plugin without Anki?

Hi,

so I'd like to write a CLI-Tool for Anki. However, I can't use the Anki-GUI program itself, because I can't interact with it on the command line. Is there a way that I can still use this plugin, because I really like that you can do curl stuff with it.

Thanks,
Niklas

Deck and note type parameters for guiAddCards

It would be nice to be able to open the GUI entry window with the correct deck/note type already preselected, e.g. for creating a keyboard shortcut:

function addCard {
  local deck=$1
  local note=$2
  # from package `httpie`
  http --json POST localhost:8765 action=guiAddCards "params={\"deck\": \"$deck\", \"note_type=$note\"}"
}

# add these to your keybindings
addCard Japanese "Japanese (recall)"
addCard English Basic

something like that.

[feature request] add notes in batch with addNotes function

discussed it before, just put a placeholder here.

while reading API, I noticed that canAddNotes function actually checked note status in batch already. So, as result, AnkiConnect definitely can have a function called addNotes which add notes in batch.

Documentation errors

Hey guys,

First of all thanks for the great plugin, saved me a lot of time!

One small thing I came across while trying to add nodes via the API. The documentation for adding notes has two errors:

  1. There is a comma after the the "Back" and "Tags" items "Back": "back content", & "yomichan", making the example malformed JSON
  2. The audio section totally fails to mention the "fields" item which is necessary for the plugin to download the audio file

Request headers should be case insensitive per RFC2616

In fact, there's an assumption on AnkiConnect that the Content-Length header is on camel case.
That will break the behavior when you use a lib which doesn't write the headers like that.
That is the case when you use the node request (https://github.com/request/request) lib to call AnkiConnect.
I've wiresharked it and compared with a request made with Postman and found out it was the Content-Length header's fault, which was being sent as content-length.
AnkiConnect will use 0 as body length, bodyLength = int(headers.get(makeBytes('Content-Length'), 0)) (https://github.com/FooSoft/anki-connect/blob/master/AnkiConnect.py#L186) and will then return the default string AnkiConnect v.4 (due to if len(req.body) == 0: on https://github.com/FooSoft/anki-connect/blob/master/AnkiConnect.py#L259)
I'm already working on a Pull Request to make them case insensitive.

Propose standard for handling releases / managing API version

With more and more changes going into this plugin, I think we need to devise a way to handle releases so that we can ensure that the functionality we require is in a certain version, without incrementing the API version every change.

The scenario here is that my app checks that API version 4 is running, but since changes are going in frequently there is a possibility that the user may or may not have the specific change I need in their version, even though they have version 4.

Once solution is to increment the API version on demand, when a dependant app is ready for a code release, so that we can be sure that the required functionality is present?

Create guiExitAnki endpoint

It would be nice if we could exit anki through a rest api. When running inside Docker, I've managed to close it gracefully by sending the SIGINT signal, but I don't quite like that approach. If I could exit it through a REST API call it would be better (it would be more guaranteed it would close gracefully and the data saved successfully).

Do you guys think that makes sense? If so, I could develop a PR.

post request with CURL windows

In the tutorial,

curl localhost:8765 -X POST -d '{"action": "deckNames", "version": 5}'

for CURL Windows, it should be given as:

curl localhost:8765 -X POST -d "{\"action\": \"deckNames\", \"version\": 5}"

adding images

Hi,

is there a way to add images to the cards, link the audio files?

Thanks

Kelly

[feature request] multi-thread support

Just wondering if anki-connect can support multi-thread to improve performance.

Understood it was originally designed to support yomichan extension which performs "one click, one card" function. Actually, It can be extended as a standard interface to support other app's batch cards importing interface. I tried to export Excel sheet by using VBA XMLHttpRequest lib, but the embedded socket server performance is very poor. After 20 cards, It definitely would be blocked.

I found a simple, but not completed project here. https://github.com/pbkhrv/anki-http-server
don't know it will help or not.

addNote should support duplicate notes...

If I have a flashcard with the same field you prevent it from being added BUT the anki client itself can add it just fine as a duplicate card?

Duplicate cards are SUPPORTED just not recommended but anki connect blocks them.

I get the message "cannot create note because it is a duplicate"

I suggest adding a param of "allow_duplicates"

List of clients?

So, I know of Yomichan, but are there any other users of ankiconnect?

If so, perhaps these known users should be added in the documentation or wiki.

Adding https support

I'm trying to use AnkiConnect on https website and it wont let me connect since https pages can only access other htttps resources.

I'm just asking if adding https support to the script would be acceptable. In other words would you accept pull request with this feature.

I still not 100% if it is going to solve my problem, but it would be still nice to know if the feature is going to be accepted, so that I don't work on something that is not going to be used.

canAddNote returns false when note with same field's value exists in a different deck

Hi,
For example I have a deck named Test with node with field Front which has the value Front Test.

When I issue the following request I get false:

{
    "action": "canAddNotes",
    "version": 5,
    "params": {
        "notes": [
            {
                "deckName": "Another Test",
                "modelName": "Basic",
                "fields": {
                    "Front": "Test"
                }
            }
        ]
    }
}

It's different deck, so I think it should return true or I'm wrong?
Thank you.

Socket already in use, cannot connect

After installing the add-on on Mac, Anki starts up to the following error:

Traceback (most recent call last):
  File "/Users/felix/Library/Application Support/Anki2/addons/yomi_base/anki_connect.py", line 41, in advance
    self.server.listen()
  File "/Users/felix/Library/Application Support/Anki2/addons/yomi_base/ajax.py", line 132, in listen
    self.sock.bind((address, port))
  File "socket.pyc", line 228, in meth
socket.error: [Errno 48] Address already in use

After initially showing other errors when activating the connection in the Chrome browser extension, it eventually does work (the data gets sent to Anki), but the error on startup remains.

It's lovely work through and through by the way. Congratulations and thanks.

More informative response to audio download failure?

Looks like it was decided that failure to download audio shouldn't be a fatal error for creating the card. But at the moment it just fails silently. Perhaps a compromise would be to write the reason for the error into the audio field?

HTTPS downloading broken in Anki 2.1 Mac/Linux

The exception is <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:748)>

I'm using the Anki 2.1.5 binary release on Fedora 28. Other reports: FooSoft/yomichan#137

It works for me in source or binary 2.0.52 on Fedora; both versions on Windows 7; and if I run the relevant AnkiConnect code in system python3 on Fedora (so the issue is probably in Anki's bundled libraries, and it would probably work if I was running Anki 2.1 from source).

I think I have a good solution so will post that shortly.

Cannot unsuspend

Instead, it give me this error:

{'result': None, 'error': "AnkiBridge instance has no attribute 'isSuspended'"}

updateNoteFields returns errorless but does nothing

I have been trying to write a program that inserts example sentences into a vocabulary deck using a few APIs, but have gotten hung up because updateNoteFields seems to do nothing. I can run noteInfo and get the note's information fine, but running updateNoteFields on the same note ID seems to do nothing. The request also returns "error": null despite clearly not following intended behavior.

how do we attach a local audio file to back content and make it play automatically on back content showing ?

how do we attach a local audio file to back content and make it play automatically on back content showing ?

test code if you need for test

import requests

r = requests.post('http://127.0.0.1:8765', json={
    "action": "addNote",
    "version": 6,
    "params": {
        "note": {
            "deckName": "英酷词典",
            "modelName": "Basic",
            "fields": {
                "Front": "front content",
                "Back": "back content"
            },
            "tags": [
                "yomichan"
            ],
            "audio": {#won' work right now
                "url": 'file:///D:/BaiduYunDownload/%E7%BC%96%E7%A8%8B/Python/Project/EngkuDict/positioned.mp3',  
                "filename": r"D:\Python\Project\EngkuDict\positioned.mp3",
                "fields": [
                    "Back"
                ]
            }
        }
    }
})

print(r.json())

Headless Anki

Is there any way to run Anki headless on linux with this add-on (i.e., without a graphical environment) in order to expose the API of anki-connect to the local network from a linux server / VM (with the ability to sync to AnkiWeb). Has anyone tried this?

can not add new card with cURL if there is any HTML mark

The following command works right
curl localhost:8765 -X POST -d "{\"action\":\"addNote\",\"version\":5,\"params\" :{\"note\" :{\"deckName\":\"Default\",\"modelName\":\"Basic\",\"fields\" :{\"Front\":\"2676\",\"Back\":\"End1123\"},\"tags\":[\"123\"]}}}"

But when adding some HTML mark to the front or back content, the CMD window says "The system cannot find the file specified."

curl localhost:8765 -X POST -d "{\"action\":\"addNote\",\"version\":5,\"params\" :{\"note\" :{\"deckName\":\"Default\",\"modelName\":\"Basic\",\"fields\" :{\"Front\":\"2676\",\"Back\":\"End1<br>123\"},\"tags\":[\"123\"]}}}"

please notify that there is a <br> mark in \"Back\":\"End1<br>123\"

unsuspend method doesn't works

When trying to unsuspend the card I get the error:

AnkiBridge instance has no attribute "isSuspended"

That happened because in commit a6c15d7 isSuspended was changed and renamed to areSuspended but unsuspend code still uses isSuspended (which doesn't exists anymore).

The easiest solution is to add function isSuspended as it was:

anki-connect/AnkiConnect.py

Lines 404 to 409 in dc01014

def isSuspended(self, card):
card = self.collection().getCard(card)
if card.queue == -1:
return True
else:
return False

Documentation request.

Thank you for your work.

It seems that this project lacks documentation.

I have figured out how to check deckNames and modelNames by myself, but I'm having a hard time getting "addNote" work, what's the format of json data I should POST? Could you give me some examples ? Thanks!

Configure travis to run tests for the addon

It would be great if we could write tests for the plugin API using the travis build server. We could run the addon on a dockerized version of Anki (txgio/anki, for example). We should choose a framework (in python, maybe) to write tests for the API running on a real Anki.

Allow connections from other ip addresses

Is it a security issue to allow connections only from 127.0.0.1?
On a docker environment, I needed to change NET_ADDRESS to 0.0.0.0. (At least to access it from a Windows environment with Docker Toolbox)
If it's not a security issue I could make a PR to change that.

How to disable App Nap for Anki 2.1?

Hi, previously,

defaults write net.ichi2.anki NSAppSleepDisabled -bool true

works for Anki 2.0 indeed. But it seems that this trick does not work for Anki 2.1 anymore, I have tried many times. I cannot understand why this trick does not work anymore, should net.ichi2.anki be replaced by some other item?

Errors are only reported on an exception

Hey,

I was using the api end point addNotes / addNote to insert new notes into the system and a noticed that there are a number of use cases where the note would fail to be created and the result would be None. There was no specific error message though as this two returned none.

Looking over the code I noticed that you only seem to return an error messages when an exception is thrown and caught. What would you think about refactoring the code to to include error messages when you have a logical failure.

An example of this might => attempt to add a new note. Deck specified doesn't exist.
Results: None, Error: "The deck for specified note does note exist"

Just a suggestion anyway!

Thanks,

C

[Discussion] Support for running arbitrary hooks

I'm working on a few projects where it would be nice if there was a way to call an add-on function through anki-connect. This would allow me to invoke the custom card previewer I implemented in Internal References from an outside app, for instance. Currently there doesn't seem to be any way to do this aside from monkey-patching anki-connect's internals, which does not seem like a good option in the long-run.

That's why I was thinking about submitting a PR that would add an API call for running an arbitrary hook through anki-connect. Add-on authors would then be able to make their functions callable with addHook("hookname", function). To avoid interfering with Anki's own hooks and make the API call safer, perhaps it would also be best if we enforced the hook names to follow a specific naming scheme, e.g. "acHook...".

Would you be open to this idea, generally speaking? I'm more than happy to submit a PR, but I thought it would be better if I asked beforehand.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.