anki/qt/aqt/mediasrv.py

719 lines
21 KiB
Python
Raw Normal View History

2019-02-05 04:59:03 +01:00
# Copyright: Ankitects Pty Ltd and contributors
2016-07-07 15:39:48 +02:00
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from __future__ import annotations
import enum
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
import logging
import mimetypes
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
import os
2019-12-20 10:19:03 +01:00
import re
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
import sys
2019-12-20 10:19:03 +01:00
import threading
2020-07-07 05:28:30 +02:00
import time
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
import traceback
from dataclasses import dataclass
from http import HTTPStatus
from typing import Callable
2016-07-07 15:39:48 +02:00
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
import flask
Move away from Bazel (#2202) (for upgrading users, please see the notes at the bottom) Bazel brought a lot of nice things to the table, such as rebuilds based on content changes instead of modification times, caching of build products, detection of incorrect build rules via a sandbox, and so on. Rewriting the build in Bazel was also an opportunity to improve on the Makefile-based build we had prior, which was pretty poor: most dependencies were external or not pinned, and the build graph was poorly defined and mostly serialized. It was not uncommon for fresh checkouts to fail due to floating dependencies, or for things to break when trying to switch to an older commit. For day-to-day development, I think Bazel served us reasonably well - we could generally switch between branches while being confident that builds would be correct and reasonably fast, and not require full rebuilds (except on Windows, where the lack of a sandbox and the TS rules would cause build breakages when TS files were renamed/removed). Bazel achieves that reliability by defining rules for each programming language that define how source files should be turned into outputs. For the rules to work with Bazel's sandboxing approach, they often have to reimplement or partially bypass the standard tools that each programming language provides. The Rust rules call Rust's compiler directly for example, instead of using Cargo, and the Python rules extract each PyPi package into a separate folder that gets added to sys.path. These separate language rules allow proper declaration of inputs and outputs, and offer some advantages such as caching of build products and fine-grained dependency installation. But they also bring some downsides: - The rules don't always support use-cases/platforms that the standard language tools do, meaning they need to be patched to be used. I've had to contribute a number of patches to the Rust, Python and JS rules to unblock various issues. - The dependencies we use with each language sometimes make assumptions that do not hold in Bazel, meaning they either need to be pinned or patched, or the language rules need to be adjusted to accommodate them. I was hopeful that after the initial setup work, things would be relatively smooth-sailing. Unfortunately, that has not proved to be the case. Things frequently broke when dependencies or the language rules were updated, and I began to get frustrated at the amount of Anki development time I was instead spending on build system upkeep. It's now about 2 years since switching to Bazel, and I think it's time to cut losses, and switch to something else that's a better fit. The new build system is based on a small build tool called Ninja, and some custom Rust code in build/. This means that to build Anki, Bazel is no longer required, but Ninja and Rust need to be installed on your system. Python and Node toolchains are automatically downloaded like in Bazel. This new build system should result in faster builds in some cases: - Because we're using cargo to build now, Rust builds are able to take advantage of pipelining and incremental debug builds, which we didn't have with Bazel. It's also easier to override the default linker on Linux/macOS, which can further improve speeds. - External Rust crates are now built with opt=1, which improves performance of debug builds. - Esbuild is now used to transpile TypeScript, instead of invoking the TypeScript compiler. This results in faster builds, by deferring typechecking to test/check time, and by allowing more work to happen in parallel. As an example of the differences, when testing with the mold linker on Linux, adding a new message to tags.proto (which triggers a recompile of the bulk of the Rust and TypeScript code) results in a compile that goes from about 22s on Bazel to about 7s in the new system. With the standard linker, it's about 9s. Some other changes of note: - Our Rust workspace now uses cargo-hakari to ensure all packages agree on available features, preventing unnecessary rebuilds. - pylib/anki is now a PEP420 implicit namespace, avoiding the need to merge source files and generated files into a single folder for running. By telling VSCode about the extra search path, code completion now works with generated files without needing to symlink them into the source folder. - qt/aqt can't use PEP420 as it's difficult to get rid of aqt/__init__.py. Instead, the generated files are now placed in a separate _aqt package that's added to the path. - ts/lib is now exposed as @tslib, so the source code and generated code can be provided under the same namespace without a merging step. - MyPy and PyLint are now invoked once for the entire codebase. - dprint will be used to format TypeScript/json files in the future instead of the slower prettier (currently turned off to avoid causing conflicts). It can automatically defer to prettier when formatting Svelte files. - svelte-check is now used for typechecking our Svelte code, which revealed a few typing issues that went undetected with the old system. - The Jest unit tests now work on Windows as well. If you're upgrading from Bazel, updated usage instructions are in docs/development.md and docs/build.md. A summary of the changes: - please remove node_modules and .bazel - install rustup (https://rustup.rs/) - install rsync if not already installed (on windows, use pacman - see docs/windows.md) - install Ninja (unzip from https://github.com/ninja-build/ninja/releases/tag/v1.11.1 and place on your path, or from your distro/homebrew if it's 1.10+) - update .vscode/settings.json from .vscode.dist
2022-11-27 06:24:20 +01:00
import flask_cors
import stringcase
from flask import Response, abort, request
from waitress.server import create_server
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
2021-01-22 14:37:24 +01:00
import aqt
import aqt.main
import aqt.operations
2020-11-09 10:45:14 +01:00
from anki import hooks
Integrate FSRS into Anki (#2654) * Pack FSRS data into card.data * Update FSRS card data when preset or weights change + Show FSRS stats in card stats * Show a warning when there's a limited review history * Add some translations; tweak UI * Fix default requested retention * Add browser columns, fix calculation of R * Property searches eg prop:d>0.1 * Integrate FSRS into reviewer * Warn about long learning steps * Hide minimum interval when FSRS is on * Don't apply interval multiplier to FSRS intervals * Expose memory state to Python * Don't set memory state on new cards * Port Jarret's new tests; add some helpers to make tests more compact https://github.com/open-spaced-repetition/fsrs-rs/pull/64 * Fix learning cards not being given memory state * Require update to v3 scheduler * Don't exclude single learning step when calculating memory state * Use relearning step when learning steps unavailable * Update docstring * fix single_card_revlog_to_items (#2656) * not need check the review_kind for unique_dates * add email address to CONTRIBUTORS * fix last first learn & keep early review * cargo fmt * cargo clippy --fix * Add Jarrett to about screen * Fix fsrs_memory_state being initialized to default in get_card() * Set initial memory state on graduate * Update to latest FSRS * Fix experiment.log being empty * Fix broken colpkg imports Introduced by "Update FSRS card data when preset or weights change" * Update memory state during (re)learning; use FSRS for graduating intervals * Reset memory state when cards are manually rescheduled as new * Add difficulty graph; hide eases when FSRS enabled * Add retrievability graph * Derive memory_state from revlog when it's missing and shouldn't be --------- Co-authored-by: Jarrett Ye <jarrett.ye@outlook.com>
2023-09-16 08:09:26 +02:00
from anki.collection import OpChanges, OpChangesOnly, Progress, SearchNode
from anki.decks import UpdateDeckConfigs
Migrate to protobuf-es (#2547) * Fix .no-reduce-motion missing from graphs spinner, and not being honored * Begin migration from protobuf.js -> protobuf-es Motivation: - Protobuf-es has a nicer API: messages are represented as classes, and fields which should exist are not marked as nullable. - As it uses modules, only the proto messages we actually use get included in our bundle output. Protobuf.js put everything in a namespace, which prevented tree-shaking, and made it awkward to access inner messages. - ./run after touching a proto file drops from about 8s to 6s on my machine. The tradeoff is slower decoding/encoding (#2043), but that was mainly a concern for the graphs page, and was unblocked by https://github.com/ankitects/anki/commit/37151213cd9d431f449ba4b3bc4c0329a1d9af78 Approach/notes: - We generate the new protobuf-es interface in addition to existing protobuf.js interface, so we can migrate a module at a time, starting with the graphs module. - rslib:proto now generates RPC methods for TS in addition to the Python interface. The input-arg-unrolling behaviour of the Python generation is not required here, as we declare the input arg as a PlainMessage<T>, which marks it as requiring all fields to be provided. - i64 is represented as bigint in protobuf-es. We were using a patch to protobuf.js to get it to output Javascript numbers instead of long.js types, but now that our supported browser versions support bigint, it's probably worth biting the bullet and migrating to bigint use. Our IDs fit comfortably within MAX_SAFE_INTEGER, but that may not hold for future fields we add. - Oneofs are handled differently in protobuf-es, and are going to need some refactoring. Other notable changes: - Added a --mkdir arg to our build runner, so we can create a dir easily during the build on Windows. - Simplified the preference handling code, by wrapping the preferences in an outer store, instead of a separate store for each individual preference. This means a change to one preference will trigger a redraw of all components that depend on the preference store, but the redrawing is cheap after moving the data processing to Rust, and it makes the code easier to follow. - Drop async(Reactive).ts in favour of more explicit handling with await blocks/updating. - Renamed add_inputs_to_group() -> add_dependency(), and fixed it not adding dependencies to parent groups. Renamed add() -> add_action() for clarity. * Remove a couple of unused proto imports * Migrate card info * Migrate congrats, image occlusion, and tag editor + Fix imports for multi-word proto files. * Migrate change-notetype * Migrate deck options * Bump target to es2020; simplify ts lib list Have used caniuse.com to confirm Chromium 77, iOS 14.5 and the Chrome on Android support the full es2017-es2020 features. * Migrate import-csv * Migrate i18n and fix missing output types in .js * Migrate custom scheduling, and remove protobuf.js To mostly maintain our old API contract, we make use of protobuf-es's ability to convert to JSON, which follows the same format as protobuf.js did. It doesn't cover all case: users who were previously changing the variant of a type will need to update their code, as assigning to a new variant no longer automatically removes the old one, which will cause an error when we try to convert back from JSON. But I suspect the large majority of users are adjusting the current variant rather than creating a new one, and this saves us having to write proxy wrappers, so it seems like a reasonable compromise. One other change I made at the same time was to rename value->kind for the oneofs in our custom study protos, as 'value' was easily confused with the 'case/value' output that protobuf-es has. With protobuf.js codegen removed, touching a proto file and invoking ./run drops from about 8s to 6s. This closes #2043. * Allow tree-shaking on protobuf types * Display backend error messages in our ts alert() * Make sourcemap generation opt-in for ts-run Considerably slows down build, and not used most of the time.
2023-06-14 14:47:37 +02:00
from anki.scheduler.v3 import SchedulingStatesWithContext, SetSchedulingStatesRequest
from anki.utils import dev_mode
from aqt.changenotetype import ChangeNotetypeDialog
from aqt.deckoptions import DeckOptionsDialog
Improve presentation of importing results (#2568) * Implement import log screen in Svelte * Show filename in import log screen title * Remove unused NoteRow property * Show number of imported notes * Use a single nid expression * Use 'count' as variable name for consistency * Import from @tslib/backend instead * Fix summary_template typing * Fix clippy warning * Apply suggestions from code review * Fix imports * Contents -> Fields * Increase max length of browser search bar https://github.com/ankitects/anki/pull/2568/files#r1255227035 * Fix race condition in Bootstrap tooltip destruction https://github.com/twbs/bootstrap/issues/37474 * summary_template -> summaryTemplate * Make show link a button * Run import ops on Svelte side * Fix geometry not being restored in CSV Import page * Make VirtualTable fill available height * Keep CSV dialog modal * Reword importing-existing-notes-skipped * Avoid mentioning matching based on first field * Change tick and cross icons * List skipped notes last * Pure CSS spinner * Move set_wants_abort() call to relevant dialogs * Show number of imported cards * Remove bold from first sentence and indent summaries * Update UI after import operations * Add close button to import log page Also make virtual table react to resize event. * Fix typing * Make CSV dialog non-modal again Otherwise user can't interact with browser window. * Update window modality after import * Commit DB and update undo actions after import op * Split frontend proto into separate file, so backend can ignore it Currently the automatically-generated frontend RPC methods get placed in 'backend.js' with all the backend methods; we could optionally split them into a separate 'frontend.js' file in the future. * Migrate import_done from a bridgecmd to a HTTP request * Update plural form of importing-notes-added * Move import response handling to mediasrv * Move task callback to script section * Avoid unnecessary :global() * .log cannot be missing if result exists * Move import log search handling to mediasrv * Type common params of ImportLogDialog * Use else if * Remove console.log() * Add way to test apkg imports in new log screen * Remove unused import * Get actual card count for CSV imports * Use import type * Fix typing error * Ignore import log when checking for changes in Python layer * Apply suggestions from code review * Remove imported card count for now * Avoid non-null assertion in assignment * Change showInBrowser to take an array of notes * Use dataclasses for import log args * Simplify ResultWithChanges in TS * Only abort import when window is modal * Fix ResultWithChanges typing * Fix Rust warnings * Only log one duplicate per incoming note * Update wording about note updates * Remove caveat about found_notes * Reduce font size * Remove redundant map * Give credit to loading.io * Remove unused line --------- Co-authored-by: RumovZ <gp5glkw78@relay.firefox.com>
2023-08-02 12:29:44 +02:00
from aqt.operations import on_op_finished
from aqt.operations.deck import update_deck_configs as update_deck_configs_op
Integrate FSRS into Anki (#2654) * Pack FSRS data into card.data * Update FSRS card data when preset or weights change + Show FSRS stats in card stats * Show a warning when there's a limited review history * Add some translations; tweak UI * Fix default requested retention * Add browser columns, fix calculation of R * Property searches eg prop:d>0.1 * Integrate FSRS into reviewer * Warn about long learning steps * Hide minimum interval when FSRS is on * Don't apply interval multiplier to FSRS intervals * Expose memory state to Python * Don't set memory state on new cards * Port Jarret's new tests; add some helpers to make tests more compact https://github.com/open-spaced-repetition/fsrs-rs/pull/64 * Fix learning cards not being given memory state * Require update to v3 scheduler * Don't exclude single learning step when calculating memory state * Use relearning step when learning steps unavailable * Update docstring * fix single_card_revlog_to_items (#2656) * not need check the review_kind for unique_dates * add email address to CONTRIBUTORS * fix last first learn & keep early review * cargo fmt * cargo clippy --fix * Add Jarrett to about screen * Fix fsrs_memory_state being initialized to default in get_card() * Set initial memory state on graduate * Update to latest FSRS * Fix experiment.log being empty * Fix broken colpkg imports Introduced by "Update FSRS card data when preset or weights change" * Update memory state during (re)learning; use FSRS for graduating intervals * Reset memory state when cards are manually rescheduled as new * Add difficulty graph; hide eases when FSRS enabled * Add retrievability graph * Derive memory_state from revlog when it's missing and shouldn't be --------- Co-authored-by: Jarrett Ye <jarrett.ye@outlook.com>
2023-09-16 08:09:26 +02:00
from aqt.progress import ProgressUpdate
2019-12-20 10:19:03 +01:00
from aqt.qt import *
from aqt.utils import aqt_data_path, show_warning, tr
2019-12-23 01:34:10 +01:00
app = flask.Flask(__name__, root_path="/fake")
flask_cors.CORS(app, resources={r"/*": {"origins": "127.0.0.1"}})
2019-12-23 01:34:10 +01:00
@dataclass
class LocalFileRequest:
# base folder, eg media folder
root: str
# path to file relative to root folder
path: str
@dataclass
class BundledFileRequest:
# path relative to aqt data folder
path: str
@dataclass
class NotFound:
message: str
DynamicRequest = Callable[[], Response]
class PageContext(enum.Enum):
UNKNOWN = 0
EDITOR = 1
REVIEWER = 2
# something in /_anki/pages/
NON_LEGACY_PAGE = 3
# Do not use this if you present user content (e.g. content from cards), as it's a
# security issue.
ADDON_PAGE = 4
@dataclass
class LegacyPage:
html: str
context: PageContext
class MediaServer(threading.Thread):
_ready = threading.Event()
daemon = True
def __init__(self, mw: aqt.main.AnkiQt) -> None:
super().__init__()
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
self.is_shutdown = False
# map of webview ids to pages
self._legacy_pages: dict[int, LegacyPage] = {}
2021-02-01 14:28:21 +01:00
def run(self) -> None:
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
try:
if dev_mode:
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
# idempotent if logging has already been set up
logging.basicConfig()
2020-07-07 02:50:12 +02:00
logging.getLogger("waitress").setLevel(logging.ERROR)
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
desired_host = os.getenv("ANKI_API_HOST", "127.0.0.1")
2023-06-26 07:29:14 +02:00
desired_port = int(os.getenv("ANKI_API_PORT") or 0)
2020-12-16 06:09:30 +01:00
self.server = create_server(
app,
host=desired_host,
2020-12-16 06:09:30 +01:00
port=desired_port,
clear_untrusted_proxy_headers=True,
)
if dev_mode:
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
print(
"Serving on http://%s:%s"
% (self.server.effective_host, self.server.effective_port) # type: ignore
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
)
self._ready.set()
self.server.run()
except Exception:
if not self.is_shutdown:
raise
def shutdown(self) -> None:
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
self.is_shutdown = True
sockets = list(self.server._map.values()) # type: ignore
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
for socket in sockets:
socket.handle_close()
# https://github.com/Pylons/webtest/blob/4b8a3ebf984185ff4fefb31b4d0cf82682e1fcf7/webtest/http.py#L93-L104
self.server.task_dispatcher.shutdown()
2016-07-07 15:39:48 +02:00
def getPort(self) -> int:
self._ready.wait()
return int(self.server.effective_port) # type: ignore
def set_page_html(
self, id: int, html: str, context: PageContext = PageContext.UNKNOWN
) -> None:
self._legacy_pages[id] = LegacyPage(html, context)
def get_page_html(self, id: int) -> str | None:
if page := self._legacy_pages.get(id):
return page.html
else:
return None
def get_page_context(self, id: int) -> PageContext | None:
if page := self._legacy_pages.get(id):
return page.context
else:
return None
def clear_page_html(self, id: int) -> None:
try:
del self._legacy_pages[id]
except KeyError:
pass
@app.route("/favicon.ico")
def favicon() -> Response:
request = BundledFileRequest(os.path.join("imgs", "favicon.ico"))
return _handle_builtin_file_request(request)
def _mime_for_path(path: str) -> str:
"Mime type for provided path/filename."
if path.endswith(".css"):
# some users may have invalid mime type in the Windows registry
return "text/css"
elif path.endswith(".js"):
return "application/javascript"
else:
# autodetect
mime, _encoding = mimetypes.guess_type(path)
return mime or "application/octet-stream"
def _handle_local_file_request(request: LocalFileRequest) -> Response:
directory = request.root
path = request.path
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
try:
isdir = os.path.isdir(os.path.join(directory, path))
except ValueError:
return flask.make_response(
f"Path for '{directory} - {path}' is too long!",
HTTPStatus.BAD_REQUEST,
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
)
directory = os.path.realpath(directory)
path = os.path.normpath(path)
fullpath = os.path.abspath(os.path.join(directory, path))
# protect against directory transversal: https://security.openstack.org/guidelines/dg_using-file-paths.html
if not fullpath.startswith(directory):
return flask.make_response(
f"Path for '{directory} - {path}' is a security leak!",
HTTPStatus.FORBIDDEN,
)
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
if isdir:
return flask.make_response(
f"Path for '{directory} - {path}' is a directory (not supported)!",
HTTPStatus.FORBIDDEN,
2019-12-23 01:34:10 +01:00
)
try:
mimetype = _mime_for_path(fullpath)
2020-07-07 02:50:12 +02:00
if os.path.exists(fullpath):
if fullpath.endswith(".css"):
# caching css files prevents flicker in the webview, but we want
# a short cache
max_age = 10
elif fullpath.endswith(".js"):
# don't cache js files
max_age = 0
else:
max_age = 60 * 60
return flask.send_file(
fullpath, mimetype=mimetype, conditional=True, max_age=max_age, download_name="foo" # type: ignore[call-arg]
)
2020-07-07 02:50:12 +02:00
else:
print(f"Not found: {path}")
2020-08-31 05:29:28 +02:00
return flask.make_response(
f"Invalid path: {path}",
2020-08-31 05:29:28 +02:00
HTTPStatus.NOT_FOUND,
)
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
except Exception as error:
if dev_mode:
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
print(
"Caught HTTP server exception,\n%s"
% "".join(traceback.format_exception(*sys.exc_info())),
)
# swallow it - user likely surfed away from
# review screen before an image had finished
# downloading
2020-08-31 05:29:28 +02:00
return flask.make_response(
str(error),
HTTPStatus.INTERNAL_SERVER_ERROR,
)
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
def _builtin_data(path: str) -> bytes:
"""Return data from file in aqt/data folder.
Path must use forward slash separators."""
Move away from Bazel (#2202) (for upgrading users, please see the notes at the bottom) Bazel brought a lot of nice things to the table, such as rebuilds based on content changes instead of modification times, caching of build products, detection of incorrect build rules via a sandbox, and so on. Rewriting the build in Bazel was also an opportunity to improve on the Makefile-based build we had prior, which was pretty poor: most dependencies were external or not pinned, and the build graph was poorly defined and mostly serialized. It was not uncommon for fresh checkouts to fail due to floating dependencies, or for things to break when trying to switch to an older commit. For day-to-day development, I think Bazel served us reasonably well - we could generally switch between branches while being confident that builds would be correct and reasonably fast, and not require full rebuilds (except on Windows, where the lack of a sandbox and the TS rules would cause build breakages when TS files were renamed/removed). Bazel achieves that reliability by defining rules for each programming language that define how source files should be turned into outputs. For the rules to work with Bazel's sandboxing approach, they often have to reimplement or partially bypass the standard tools that each programming language provides. The Rust rules call Rust's compiler directly for example, instead of using Cargo, and the Python rules extract each PyPi package into a separate folder that gets added to sys.path. These separate language rules allow proper declaration of inputs and outputs, and offer some advantages such as caching of build products and fine-grained dependency installation. But they also bring some downsides: - The rules don't always support use-cases/platforms that the standard language tools do, meaning they need to be patched to be used. I've had to contribute a number of patches to the Rust, Python and JS rules to unblock various issues. - The dependencies we use with each language sometimes make assumptions that do not hold in Bazel, meaning they either need to be pinned or patched, or the language rules need to be adjusted to accommodate them. I was hopeful that after the initial setup work, things would be relatively smooth-sailing. Unfortunately, that has not proved to be the case. Things frequently broke when dependencies or the language rules were updated, and I began to get frustrated at the amount of Anki development time I was instead spending on build system upkeep. It's now about 2 years since switching to Bazel, and I think it's time to cut losses, and switch to something else that's a better fit. The new build system is based on a small build tool called Ninja, and some custom Rust code in build/. This means that to build Anki, Bazel is no longer required, but Ninja and Rust need to be installed on your system. Python and Node toolchains are automatically downloaded like in Bazel. This new build system should result in faster builds in some cases: - Because we're using cargo to build now, Rust builds are able to take advantage of pipelining and incremental debug builds, which we didn't have with Bazel. It's also easier to override the default linker on Linux/macOS, which can further improve speeds. - External Rust crates are now built with opt=1, which improves performance of debug builds. - Esbuild is now used to transpile TypeScript, instead of invoking the TypeScript compiler. This results in faster builds, by deferring typechecking to test/check time, and by allowing more work to happen in parallel. As an example of the differences, when testing with the mold linker on Linux, adding a new message to tags.proto (which triggers a recompile of the bulk of the Rust and TypeScript code) results in a compile that goes from about 22s on Bazel to about 7s in the new system. With the standard linker, it's about 9s. Some other changes of note: - Our Rust workspace now uses cargo-hakari to ensure all packages agree on available features, preventing unnecessary rebuilds. - pylib/anki is now a PEP420 implicit namespace, avoiding the need to merge source files and generated files into a single folder for running. By telling VSCode about the extra search path, code completion now works with generated files without needing to symlink them into the source folder. - qt/aqt can't use PEP420 as it's difficult to get rid of aqt/__init__.py. Instead, the generated files are now placed in a separate _aqt package that's added to the path. - ts/lib is now exposed as @tslib, so the source code and generated code can be provided under the same namespace without a merging step. - MyPy and PyLint are now invoked once for the entire codebase. - dprint will be used to format TypeScript/json files in the future instead of the slower prettier (currently turned off to avoid causing conflicts). It can automatically defer to prettier when formatting Svelte files. - svelte-check is now used for typechecking our Svelte code, which revealed a few typing issues that went undetected with the old system. - The Jest unit tests now work on Windows as well. If you're upgrading from Bazel, updated usage instructions are in docs/development.md and docs/build.md. A summary of the changes: - please remove node_modules and .bazel - install rustup (https://rustup.rs/) - install rsync if not already installed (on windows, use pacman - see docs/windows.md) - install Ninja (unzip from https://github.com/ninja-build/ninja/releases/tag/v1.11.1 and place on your path, or from your distro/homebrew if it's 1.10+) - update .vscode/settings.json from .vscode.dist
2022-11-27 06:24:20 +01:00
# packaged build?
if getattr(sys, "frozen", False):
reader = aqt.__loader__.get_resource_reader("_aqt") # type: ignore
with reader.open_resource(path) as f:
return f.read()
Move away from Bazel (#2202) (for upgrading users, please see the notes at the bottom) Bazel brought a lot of nice things to the table, such as rebuilds based on content changes instead of modification times, caching of build products, detection of incorrect build rules via a sandbox, and so on. Rewriting the build in Bazel was also an opportunity to improve on the Makefile-based build we had prior, which was pretty poor: most dependencies were external or not pinned, and the build graph was poorly defined and mostly serialized. It was not uncommon for fresh checkouts to fail due to floating dependencies, or for things to break when trying to switch to an older commit. For day-to-day development, I think Bazel served us reasonably well - we could generally switch between branches while being confident that builds would be correct and reasonably fast, and not require full rebuilds (except on Windows, where the lack of a sandbox and the TS rules would cause build breakages when TS files were renamed/removed). Bazel achieves that reliability by defining rules for each programming language that define how source files should be turned into outputs. For the rules to work with Bazel's sandboxing approach, they often have to reimplement or partially bypass the standard tools that each programming language provides. The Rust rules call Rust's compiler directly for example, instead of using Cargo, and the Python rules extract each PyPi package into a separate folder that gets added to sys.path. These separate language rules allow proper declaration of inputs and outputs, and offer some advantages such as caching of build products and fine-grained dependency installation. But they also bring some downsides: - The rules don't always support use-cases/platforms that the standard language tools do, meaning they need to be patched to be used. I've had to contribute a number of patches to the Rust, Python and JS rules to unblock various issues. - The dependencies we use with each language sometimes make assumptions that do not hold in Bazel, meaning they either need to be pinned or patched, or the language rules need to be adjusted to accommodate them. I was hopeful that after the initial setup work, things would be relatively smooth-sailing. Unfortunately, that has not proved to be the case. Things frequently broke when dependencies or the language rules were updated, and I began to get frustrated at the amount of Anki development time I was instead spending on build system upkeep. It's now about 2 years since switching to Bazel, and I think it's time to cut losses, and switch to something else that's a better fit. The new build system is based on a small build tool called Ninja, and some custom Rust code in build/. This means that to build Anki, Bazel is no longer required, but Ninja and Rust need to be installed on your system. Python and Node toolchains are automatically downloaded like in Bazel. This new build system should result in faster builds in some cases: - Because we're using cargo to build now, Rust builds are able to take advantage of pipelining and incremental debug builds, which we didn't have with Bazel. It's also easier to override the default linker on Linux/macOS, which can further improve speeds. - External Rust crates are now built with opt=1, which improves performance of debug builds. - Esbuild is now used to transpile TypeScript, instead of invoking the TypeScript compiler. This results in faster builds, by deferring typechecking to test/check time, and by allowing more work to happen in parallel. As an example of the differences, when testing with the mold linker on Linux, adding a new message to tags.proto (which triggers a recompile of the bulk of the Rust and TypeScript code) results in a compile that goes from about 22s on Bazel to about 7s in the new system. With the standard linker, it's about 9s. Some other changes of note: - Our Rust workspace now uses cargo-hakari to ensure all packages agree on available features, preventing unnecessary rebuilds. - pylib/anki is now a PEP420 implicit namespace, avoiding the need to merge source files and generated files into a single folder for running. By telling VSCode about the extra search path, code completion now works with generated files without needing to symlink them into the source folder. - qt/aqt can't use PEP420 as it's difficult to get rid of aqt/__init__.py. Instead, the generated files are now placed in a separate _aqt package that's added to the path. - ts/lib is now exposed as @tslib, so the source code and generated code can be provided under the same namespace without a merging step. - MyPy and PyLint are now invoked once for the entire codebase. - dprint will be used to format TypeScript/json files in the future instead of the slower prettier (currently turned off to avoid causing conflicts). It can automatically defer to prettier when formatting Svelte files. - svelte-check is now used for typechecking our Svelte code, which revealed a few typing issues that went undetected with the old system. - The Jest unit tests now work on Windows as well. If you're upgrading from Bazel, updated usage instructions are in docs/development.md and docs/build.md. A summary of the changes: - please remove node_modules and .bazel - install rustup (https://rustup.rs/) - install rsync if not already installed (on windows, use pacman - see docs/windows.md) - install Ninja (unzip from https://github.com/ninja-build/ninja/releases/tag/v1.11.1 and place on your path, or from your distro/homebrew if it's 1.10+) - update .vscode/settings.json from .vscode.dist
2022-11-27 06:24:20 +01:00
else:
full_path = aqt_data_path() / ".." / path
return full_path.read_bytes()
def _handle_builtin_file_request(request: BundledFileRequest) -> Response:
path = request.path
mimetype = _mime_for_path(path)
data_path = f"data/web/{path}"
try:
data = _builtin_data(data_path)
return Response(data, mimetype=mimetype)
except FileNotFoundError:
Move away from Bazel (#2202) (for upgrading users, please see the notes at the bottom) Bazel brought a lot of nice things to the table, such as rebuilds based on content changes instead of modification times, caching of build products, detection of incorrect build rules via a sandbox, and so on. Rewriting the build in Bazel was also an opportunity to improve on the Makefile-based build we had prior, which was pretty poor: most dependencies were external or not pinned, and the build graph was poorly defined and mostly serialized. It was not uncommon for fresh checkouts to fail due to floating dependencies, or for things to break when trying to switch to an older commit. For day-to-day development, I think Bazel served us reasonably well - we could generally switch between branches while being confident that builds would be correct and reasonably fast, and not require full rebuilds (except on Windows, where the lack of a sandbox and the TS rules would cause build breakages when TS files were renamed/removed). Bazel achieves that reliability by defining rules for each programming language that define how source files should be turned into outputs. For the rules to work with Bazel's sandboxing approach, they often have to reimplement or partially bypass the standard tools that each programming language provides. The Rust rules call Rust's compiler directly for example, instead of using Cargo, and the Python rules extract each PyPi package into a separate folder that gets added to sys.path. These separate language rules allow proper declaration of inputs and outputs, and offer some advantages such as caching of build products and fine-grained dependency installation. But they also bring some downsides: - The rules don't always support use-cases/platforms that the standard language tools do, meaning they need to be patched to be used. I've had to contribute a number of patches to the Rust, Python and JS rules to unblock various issues. - The dependencies we use with each language sometimes make assumptions that do not hold in Bazel, meaning they either need to be pinned or patched, or the language rules need to be adjusted to accommodate them. I was hopeful that after the initial setup work, things would be relatively smooth-sailing. Unfortunately, that has not proved to be the case. Things frequently broke when dependencies or the language rules were updated, and I began to get frustrated at the amount of Anki development time I was instead spending on build system upkeep. It's now about 2 years since switching to Bazel, and I think it's time to cut losses, and switch to something else that's a better fit. The new build system is based on a small build tool called Ninja, and some custom Rust code in build/. This means that to build Anki, Bazel is no longer required, but Ninja and Rust need to be installed on your system. Python and Node toolchains are automatically downloaded like in Bazel. This new build system should result in faster builds in some cases: - Because we're using cargo to build now, Rust builds are able to take advantage of pipelining and incremental debug builds, which we didn't have with Bazel. It's also easier to override the default linker on Linux/macOS, which can further improve speeds. - External Rust crates are now built with opt=1, which improves performance of debug builds. - Esbuild is now used to transpile TypeScript, instead of invoking the TypeScript compiler. This results in faster builds, by deferring typechecking to test/check time, and by allowing more work to happen in parallel. As an example of the differences, when testing with the mold linker on Linux, adding a new message to tags.proto (which triggers a recompile of the bulk of the Rust and TypeScript code) results in a compile that goes from about 22s on Bazel to about 7s in the new system. With the standard linker, it's about 9s. Some other changes of note: - Our Rust workspace now uses cargo-hakari to ensure all packages agree on available features, preventing unnecessary rebuilds. - pylib/anki is now a PEP420 implicit namespace, avoiding the need to merge source files and generated files into a single folder for running. By telling VSCode about the extra search path, code completion now works with generated files without needing to symlink them into the source folder. - qt/aqt can't use PEP420 as it's difficult to get rid of aqt/__init__.py. Instead, the generated files are now placed in a separate _aqt package that's added to the path. - ts/lib is now exposed as @tslib, so the source code and generated code can be provided under the same namespace without a merging step. - MyPy and PyLint are now invoked once for the entire codebase. - dprint will be used to format TypeScript/json files in the future instead of the slower prettier (currently turned off to avoid causing conflicts). It can automatically defer to prettier when formatting Svelte files. - svelte-check is now used for typechecking our Svelte code, which revealed a few typing issues that went undetected with the old system. - The Jest unit tests now work on Windows as well. If you're upgrading from Bazel, updated usage instructions are in docs/development.md and docs/build.md. A summary of the changes: - please remove node_modules and .bazel - install rustup (https://rustup.rs/) - install rsync if not already installed (on windows, use pacman - see docs/windows.md) - install Ninja (unzip from https://github.com/ninja-build/ninja/releases/tag/v1.11.1 and place on your path, or from your distro/homebrew if it's 1.10+) - update .vscode/settings.json from .vscode.dist
2022-11-27 06:24:20 +01:00
if dev_mode:
print(f"404: {data_path}")
return flask.make_response(
f"Invalid path: {path}",
HTTPStatus.NOT_FOUND,
)
except Exception as error:
if dev_mode:
print(
"Caught HTTP server exception,\n%s"
% "".join(traceback.format_exception(*sys.exc_info())),
)
# swallow it - user likely surfed away from
# review screen before an image had finished
# downloading
return flask.make_response(
str(error),
HTTPStatus.INTERNAL_SERVER_ERROR,
)
@app.route("/<path:pathin>", methods=["GET", "POST"])
def handle_request(pathin: str) -> Response:
host = request.headers.get("Host", "").lower()
allowed_prefixes = ("127.0.0.1:", "localhost:", "[::1]:")
if not any(host.startswith(prefix) for prefix in allowed_prefixes):
# while we only bind to localhost, this request may have come from a local browser
2023-12-08 03:43:09 +01:00
# via a DNS rebinding attack; deny it unless we're doing non-local testing
if os.environ.get("ANKI_API_HOST") != "0.0.0.0":
print("deny non-local host", host)
abort(403)
2023-11-08 00:20:56 +01:00
req = _extract_request(pathin)
if dev_mode:
print(f"{time.time():.3f} {flask.request.method} /{pathin}")
2023-11-08 00:20:56 +01:00
if isinstance(req, NotFound):
print(req.message)
return flask.make_response(
f"Invalid path: {pathin}",
HTTPStatus.NOT_FOUND,
)
2023-11-08 00:20:56 +01:00
elif callable(req):
return _handle_dynamic_request(req)
elif isinstance(req, BundledFileRequest):
return _handle_builtin_file_request(req)
elif isinstance(req, LocalFileRequest):
return _handle_local_file_request(req)
else:
return flask.make_response(
f"unexpected request: {pathin}",
HTTPStatus.FORBIDDEN,
)
def _extract_internal_request(
path: str,
) -> BundledFileRequest | DynamicRequest | NotFound | None:
"Catch /_anki references and rewrite them to web export folder."
prefix = "_anki/"
if not path.startswith(prefix):
return None
dirname = os.path.dirname(path)
filename = os.path.basename(path)
additional_prefix = None
if dirname == "_anki":
if flask.request.method == "POST":
return _extract_collection_post_request(filename)
elif get_handler := _extract_dynamic_get_request(filename):
return get_handler
# remap legacy top-level references
base, ext = os.path.splitext(filename)
if ext == ".css":
additional_prefix = "css/"
elif ext == ".js":
if base in ("jquery-ui", "jquery", "plot"):
additional_prefix = "js/vendor/"
else:
additional_prefix = "js/"
# handle requests for vendored libraries
elif dirname == "_anki/js/vendor":
base, ext = os.path.splitext(filename)
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
if base == "jquery":
base = "jquery.min"
additional_prefix = "js/vendor/"
Replaced the mediasrv.py SimpleHttp server by flask and waitress, fixing HTML5 media support. https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server https://stackoverflow.com/questions/5052635/what-is-relation-between-content-length-and-byte-ranges-in-http-1-1 https://stackoverflow.com/questions/16725907/google-app-engine-serving-mp3-for-audio-element-needs-content-range-header I was trying to use HTML5 audio tag to display audios like: ```html <audio id="elem_audio" src="myfile.mp3" controls></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063321-565b5500-7c77-11ea-9f8d-6e1df6f07892.png) But the progress bar seek was not working. After researching, I found the problem was the HTML server not properly responding to the HTML5 header requests. The HTML server should respond to quite complicated things as 206 partial, properly handle keep-alive, provide media ranges and other HTTP headers: https://stackoverflow.com/questions/37044064/html-audio-cant-set-currenttime To implement all these on the Simple HTTP server would be quite complicated. Then, instead, I imported the `flask` web server, which is quite simple and straight forward to use. Now, the back-end is using a secure complaint HTTP back-end: 1. https://palletsprojects.com/p/flask/ > Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. > > Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy. 1. https://docs.pylonsproject.org/projects/waitress/en/latest/ > Waitress is meant to be a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in the Python standard library. It runs on CPython on Unix and Windows under Python 2.7+ and Python 3.5+. It is also known to run on PyPy 1.6.0 on UNIX. It supports HTTP/1.0 and HTTP/1.1. Right now, anki does not support fields passing file names directly to HTML audio tags, but this can be easily done with (https://github.com/ankitects/anki/pull 540 - Added arguments to the sound tag) plus the commit https://github.com/evandroforks/anki/commit/826a97df61b99814041c41c0f2c84268280ed8ad, the HTML5 audio tag can be used like this: ```html // Audio = [sound:myfile.mp3|onlyfilename] <audio id="elem_audio" src="{{Audio}}" controls controlsList="nodownload"></audio> ``` ![image](https://user-images.githubusercontent.com/5332158/79063736-c539ad80-7c79-11ea-8420-40b72185f4e7.png) # Conflicts: # qt/aqt/mediasrv.py
2020-04-29 12:38:35 +02:00
elif base == "jquery-ui":
base = "jquery-ui.min"
additional_prefix = "js/vendor/"
if additional_prefix:
oldpath = path
path = f"{prefix}{additional_prefix}{base}{ext}"
print(f"legacy {oldpath} remapped to {path}")
return BundledFileRequest(path=path[len(prefix) :])
2019-12-23 01:34:10 +01:00
def _extract_addon_request(path: str) -> LocalFileRequest | NotFound | None:
"Catch /_addons references and rewrite them to addons folder."
prefix = "_addons/"
if not path.startswith(prefix):
return None
addon_path = path[len(prefix) :]
try:
manager = aqt.mw.addonManager
except AttributeError as error:
if dev_mode:
print(f"_redirectWebExports: {error}")
return None
try:
addon, sub_path = addon_path.split("/", 1)
except ValueError:
return None
if not addon:
return None
2020-11-09 10:45:14 +01:00
pattern = manager.getWebExports(addon)
if not pattern:
return None
if re.fullmatch(pattern, sub_path):
return LocalFileRequest(root=manager.addonsFolder(), path=addon_path)
return NotFound(message=f"couldn't locate item in add-on folder {path}")
def _extract_request(
path: str,
) -> LocalFileRequest | BundledFileRequest | DynamicRequest | NotFound:
if internal := _extract_internal_request(path):
return internal
elif addon := _extract_addon_request(path):
return addon
if not aqt.mw.col:
return NotFound(message=f"collection not open, ignore request for {path}")
path = hooks.media_file_filter(path)
return LocalFileRequest(root=aqt.mw.col.media.dir(), path=path)
def congrats_info() -> bytes:
if not aqt.mw.col.sched._is_finished():
aqt.mw.taskman.run_on_main(lambda: aqt.mw.moveToState("review"))
return raw_backend_request("congrats_info")()
def get_deck_configs_for_update() -> bytes:
return aqt.mw.col._backend.get_deck_configs_for_update_raw(request.data)
def update_deck_configs() -> bytes:
2021-04-20 11:50:05 +02:00
# the regular change tracking machinery expects to be started on the main
# thread and uses a callback on success, so we need to run this op on
# main, and return immediately from the web request
input = UpdateDeckConfigs()
input.ParseFromString(request.data)
Integrate FSRS into Anki (#2654) * Pack FSRS data into card.data * Update FSRS card data when preset or weights change + Show FSRS stats in card stats * Show a warning when there's a limited review history * Add some translations; tweak UI * Fix default requested retention * Add browser columns, fix calculation of R * Property searches eg prop:d>0.1 * Integrate FSRS into reviewer * Warn about long learning steps * Hide minimum interval when FSRS is on * Don't apply interval multiplier to FSRS intervals * Expose memory state to Python * Don't set memory state on new cards * Port Jarret's new tests; add some helpers to make tests more compact https://github.com/open-spaced-repetition/fsrs-rs/pull/64 * Fix learning cards not being given memory state * Require update to v3 scheduler * Don't exclude single learning step when calculating memory state * Use relearning step when learning steps unavailable * Update docstring * fix single_card_revlog_to_items (#2656) * not need check the review_kind for unique_dates * add email address to CONTRIBUTORS * fix last first learn & keep early review * cargo fmt * cargo clippy --fix * Add Jarrett to about screen * Fix fsrs_memory_state being initialized to default in get_card() * Set initial memory state on graduate * Update to latest FSRS * Fix experiment.log being empty * Fix broken colpkg imports Introduced by "Update FSRS card data when preset or weights change" * Update memory state during (re)learning; use FSRS for graduating intervals * Reset memory state when cards are manually rescheduled as new * Add difficulty graph; hide eases when FSRS enabled * Add retrievability graph * Derive memory_state from revlog when it's missing and shouldn't be --------- Co-authored-by: Jarrett Ye <jarrett.ye@outlook.com>
2023-09-16 08:09:26 +02:00
def on_progress(progress: Progress, update: ProgressUpdate) -> None:
if progress.HasField("compute_memory"):
val = progress.compute_memory
update.max = val.total_cards
update.value = val.current_cards
update.label = val.label
elif progress.HasField("compute_weights"):
val2 = progress.compute_weights
update.max = val2.total
update.value = val2.current
pct = str(int(val2.current / val2.total * 100) if val2.total > 0 else 0)
label = tr.deck_config_optimizing_preset(
current_count=val2.current_preset, total_count=val2.total_presets
)
update.label = (
label
+ "\n"
+ tr.deck_config_percent_of_reviews(pct=pct, reviews=val2.fsrs_items)
)
else:
Integrate FSRS into Anki (#2654) * Pack FSRS data into card.data * Update FSRS card data when preset or weights change + Show FSRS stats in card stats * Show a warning when there's a limited review history * Add some translations; tweak UI * Fix default requested retention * Add browser columns, fix calculation of R * Property searches eg prop:d>0.1 * Integrate FSRS into reviewer * Warn about long learning steps * Hide minimum interval when FSRS is on * Don't apply interval multiplier to FSRS intervals * Expose memory state to Python * Don't set memory state on new cards * Port Jarret's new tests; add some helpers to make tests more compact https://github.com/open-spaced-repetition/fsrs-rs/pull/64 * Fix learning cards not being given memory state * Require update to v3 scheduler * Don't exclude single learning step when calculating memory state * Use relearning step when learning steps unavailable * Update docstring * fix single_card_revlog_to_items (#2656) * not need check the review_kind for unique_dates * add email address to CONTRIBUTORS * fix last first learn & keep early review * cargo fmt * cargo clippy --fix * Add Jarrett to about screen * Fix fsrs_memory_state being initialized to default in get_card() * Set initial memory state on graduate * Update to latest FSRS * Fix experiment.log being empty * Fix broken colpkg imports Introduced by "Update FSRS card data when preset or weights change" * Update memory state during (re)learning; use FSRS for graduating intervals * Reset memory state when cards are manually rescheduled as new * Add difficulty graph; hide eases when FSRS enabled * Add retrievability graph * Derive memory_state from revlog when it's missing and shouldn't be --------- Co-authored-by: Jarrett Ye <jarrett.ye@outlook.com>
2023-09-16 08:09:26 +02:00
return
if update.user_wants_abort:
update.abort = True
2021-04-20 11:50:05 +02:00
def on_success(changes: OpChanges) -> None:
if isinstance(window := aqt.mw.app.activeWindow(), DeckOptionsDialog):
window.reject()
2021-04-20 11:50:05 +02:00
def handle_on_main() -> None:
update_deck_configs_op(parent=aqt.mw, input=input).success(
2021-04-20 11:50:05 +02:00
on_success
Integrate FSRS into Anki (#2654) * Pack FSRS data into card.data * Update FSRS card data when preset or weights change + Show FSRS stats in card stats * Show a warning when there's a limited review history * Add some translations; tweak UI * Fix default requested retention * Add browser columns, fix calculation of R * Property searches eg prop:d>0.1 * Integrate FSRS into reviewer * Warn about long learning steps * Hide minimum interval when FSRS is on * Don't apply interval multiplier to FSRS intervals * Expose memory state to Python * Don't set memory state on new cards * Port Jarret's new tests; add some helpers to make tests more compact https://github.com/open-spaced-repetition/fsrs-rs/pull/64 * Fix learning cards not being given memory state * Require update to v3 scheduler * Don't exclude single learning step when calculating memory state * Use relearning step when learning steps unavailable * Update docstring * fix single_card_revlog_to_items (#2656) * not need check the review_kind for unique_dates * add email address to CONTRIBUTORS * fix last first learn & keep early review * cargo fmt * cargo clippy --fix * Add Jarrett to about screen * Fix fsrs_memory_state being initialized to default in get_card() * Set initial memory state on graduate * Update to latest FSRS * Fix experiment.log being empty * Fix broken colpkg imports Introduced by "Update FSRS card data when preset or weights change" * Update memory state during (re)learning; use FSRS for graduating intervals * Reset memory state when cards are manually rescheduled as new * Add difficulty graph; hide eases when FSRS enabled * Add retrievability graph * Derive memory_state from revlog when it's missing and shouldn't be --------- Co-authored-by: Jarrett Ye <jarrett.ye@outlook.com>
2023-09-16 08:09:26 +02:00
).with_backend_progress(on_progress).run_in_background()
2021-04-20 11:50:05 +02:00
aqt.mw.taskman.run_on_main(handle_on_main)
return b""
def get_scheduling_states_with_context() -> bytes:
return SchedulingStatesWithContext(
states=aqt.mw.reviewer.get_scheduling_states(),
context=aqt.mw.reviewer.get_scheduling_context(),
).SerializeToString()
def set_scheduling_states() -> bytes:
Migrate to protobuf-es (#2547) * Fix .no-reduce-motion missing from graphs spinner, and not being honored * Begin migration from protobuf.js -> protobuf-es Motivation: - Protobuf-es has a nicer API: messages are represented as classes, and fields which should exist are not marked as nullable. - As it uses modules, only the proto messages we actually use get included in our bundle output. Protobuf.js put everything in a namespace, which prevented tree-shaking, and made it awkward to access inner messages. - ./run after touching a proto file drops from about 8s to 6s on my machine. The tradeoff is slower decoding/encoding (#2043), but that was mainly a concern for the graphs page, and was unblocked by https://github.com/ankitects/anki/commit/37151213cd9d431f449ba4b3bc4c0329a1d9af78 Approach/notes: - We generate the new protobuf-es interface in addition to existing protobuf.js interface, so we can migrate a module at a time, starting with the graphs module. - rslib:proto now generates RPC methods for TS in addition to the Python interface. The input-arg-unrolling behaviour of the Python generation is not required here, as we declare the input arg as a PlainMessage<T>, which marks it as requiring all fields to be provided. - i64 is represented as bigint in protobuf-es. We were using a patch to protobuf.js to get it to output Javascript numbers instead of long.js types, but now that our supported browser versions support bigint, it's probably worth biting the bullet and migrating to bigint use. Our IDs fit comfortably within MAX_SAFE_INTEGER, but that may not hold for future fields we add. - Oneofs are handled differently in protobuf-es, and are going to need some refactoring. Other notable changes: - Added a --mkdir arg to our build runner, so we can create a dir easily during the build on Windows. - Simplified the preference handling code, by wrapping the preferences in an outer store, instead of a separate store for each individual preference. This means a change to one preference will trigger a redraw of all components that depend on the preference store, but the redrawing is cheap after moving the data processing to Rust, and it makes the code easier to follow. - Drop async(Reactive).ts in favour of more explicit handling with await blocks/updating. - Renamed add_inputs_to_group() -> add_dependency(), and fixed it not adding dependencies to parent groups. Renamed add() -> add_action() for clarity. * Remove a couple of unused proto imports * Migrate card info * Migrate congrats, image occlusion, and tag editor + Fix imports for multi-word proto files. * Migrate change-notetype * Migrate deck options * Bump target to es2020; simplify ts lib list Have used caniuse.com to confirm Chromium 77, iOS 14.5 and the Chrome on Android support the full es2017-es2020 features. * Migrate import-csv * Migrate i18n and fix missing output types in .js * Migrate custom scheduling, and remove protobuf.js To mostly maintain our old API contract, we make use of protobuf-es's ability to convert to JSON, which follows the same format as protobuf.js did. It doesn't cover all case: users who were previously changing the variant of a type will need to update their code, as assigning to a new variant no longer automatically removes the old one, which will cause an error when we try to convert back from JSON. But I suspect the large majority of users are adjusting the current variant rather than creating a new one, and this saves us having to write proxy wrappers, so it seems like a reasonable compromise. One other change I made at the same time was to rename value->kind for the oneofs in our custom study protos, as 'value' was easily confused with the 'case/value' output that protobuf-es has. With protobuf.js codegen removed, touching a proto file and invoking ./run drops from about 8s to 6s. This closes #2043. * Allow tree-shaking on protobuf types * Display backend error messages in our ts alert() * Make sourcemap generation opt-in for ts-run Considerably slows down build, and not used most of the time.
2023-06-14 14:47:37 +02:00
states = SetSchedulingStatesRequest()
states.ParseFromString(request.data)
Migrate to protobuf-es (#2547) * Fix .no-reduce-motion missing from graphs spinner, and not being honored * Begin migration from protobuf.js -> protobuf-es Motivation: - Protobuf-es has a nicer API: messages are represented as classes, and fields which should exist are not marked as nullable. - As it uses modules, only the proto messages we actually use get included in our bundle output. Protobuf.js put everything in a namespace, which prevented tree-shaking, and made it awkward to access inner messages. - ./run after touching a proto file drops from about 8s to 6s on my machine. The tradeoff is slower decoding/encoding (#2043), but that was mainly a concern for the graphs page, and was unblocked by https://github.com/ankitects/anki/commit/37151213cd9d431f449ba4b3bc4c0329a1d9af78 Approach/notes: - We generate the new protobuf-es interface in addition to existing protobuf.js interface, so we can migrate a module at a time, starting with the graphs module. - rslib:proto now generates RPC methods for TS in addition to the Python interface. The input-arg-unrolling behaviour of the Python generation is not required here, as we declare the input arg as a PlainMessage<T>, which marks it as requiring all fields to be provided. - i64 is represented as bigint in protobuf-es. We were using a patch to protobuf.js to get it to output Javascript numbers instead of long.js types, but now that our supported browser versions support bigint, it's probably worth biting the bullet and migrating to bigint use. Our IDs fit comfortably within MAX_SAFE_INTEGER, but that may not hold for future fields we add. - Oneofs are handled differently in protobuf-es, and are going to need some refactoring. Other notable changes: - Added a --mkdir arg to our build runner, so we can create a dir easily during the build on Windows. - Simplified the preference handling code, by wrapping the preferences in an outer store, instead of a separate store for each individual preference. This means a change to one preference will trigger a redraw of all components that depend on the preference store, but the redrawing is cheap after moving the data processing to Rust, and it makes the code easier to follow. - Drop async(Reactive).ts in favour of more explicit handling with await blocks/updating. - Renamed add_inputs_to_group() -> add_dependency(), and fixed it not adding dependencies to parent groups. Renamed add() -> add_action() for clarity. * Remove a couple of unused proto imports * Migrate card info * Migrate congrats, image occlusion, and tag editor + Fix imports for multi-word proto files. * Migrate change-notetype * Migrate deck options * Bump target to es2020; simplify ts lib list Have used caniuse.com to confirm Chromium 77, iOS 14.5 and the Chrome on Android support the full es2017-es2020 features. * Migrate import-csv * Migrate i18n and fix missing output types in .js * Migrate custom scheduling, and remove protobuf.js To mostly maintain our old API contract, we make use of protobuf-es's ability to convert to JSON, which follows the same format as protobuf.js did. It doesn't cover all case: users who were previously changing the variant of a type will need to update their code, as assigning to a new variant no longer automatically removes the old one, which will cause an error when we try to convert back from JSON. But I suspect the large majority of users are adjusting the current variant rather than creating a new one, and this saves us having to write proxy wrappers, so it seems like a reasonable compromise. One other change I made at the same time was to rename value->kind for the oneofs in our custom study protos, as 'value' was easily confused with the 'case/value' output that protobuf-es has. With protobuf.js codegen removed, touching a proto file and invoking ./run drops from about 8s to 6s. This closes #2043. * Allow tree-shaking on protobuf types * Display backend error messages in our ts alert() * Make sourcemap generation opt-in for ts-run Considerably slows down build, and not used most of the time.
2023-06-14 14:47:37 +02:00
aqt.mw.reviewer.set_scheduling_states(states)
return b""
Improve presentation of importing results (#2568) * Implement import log screen in Svelte * Show filename in import log screen title * Remove unused NoteRow property * Show number of imported notes * Use a single nid expression * Use 'count' as variable name for consistency * Import from @tslib/backend instead * Fix summary_template typing * Fix clippy warning * Apply suggestions from code review * Fix imports * Contents -> Fields * Increase max length of browser search bar https://github.com/ankitects/anki/pull/2568/files#r1255227035 * Fix race condition in Bootstrap tooltip destruction https://github.com/twbs/bootstrap/issues/37474 * summary_template -> summaryTemplate * Make show link a button * Run import ops on Svelte side * Fix geometry not being restored in CSV Import page * Make VirtualTable fill available height * Keep CSV dialog modal * Reword importing-existing-notes-skipped * Avoid mentioning matching based on first field * Change tick and cross icons * List skipped notes last * Pure CSS spinner * Move set_wants_abort() call to relevant dialogs * Show number of imported cards * Remove bold from first sentence and indent summaries * Update UI after import operations * Add close button to import log page Also make virtual table react to resize event. * Fix typing * Make CSV dialog non-modal again Otherwise user can't interact with browser window. * Update window modality after import * Commit DB and update undo actions after import op * Split frontend proto into separate file, so backend can ignore it Currently the automatically-generated frontend RPC methods get placed in 'backend.js' with all the backend methods; we could optionally split them into a separate 'frontend.js' file in the future. * Migrate import_done from a bridgecmd to a HTTP request * Update plural form of importing-notes-added * Move import response handling to mediasrv * Move task callback to script section * Avoid unnecessary :global() * .log cannot be missing if result exists * Move import log search handling to mediasrv * Type common params of ImportLogDialog * Use else if * Remove console.log() * Add way to test apkg imports in new log screen * Remove unused import * Get actual card count for CSV imports * Use import type * Fix typing error * Ignore import log when checking for changes in Python layer * Apply suggestions from code review * Remove imported card count for now * Avoid non-null assertion in assignment * Change showInBrowser to take an array of notes * Use dataclasses for import log args * Simplify ResultWithChanges in TS * Only abort import when window is modal * Fix ResultWithChanges typing * Fix Rust warnings * Only log one duplicate per incoming note * Update wording about note updates * Remove caveat about found_notes * Reduce font size * Remove redundant map * Give credit to loading.io * Remove unused line --------- Co-authored-by: RumovZ <gp5glkw78@relay.firefox.com>
2023-08-02 12:29:44 +02:00
def import_done() -> bytes:
def update_window_modality() -> None:
if window := aqt.mw.app.activeWindow():
Merging Notetypes on Import (#2612) * Remember original id when importing notetype * Reuse notetypes with matching original id * Add field and template ids * Enable merging imported notetypes * Fix test Note should be updated if the incoming note's notetype is remapped to the existing note's notetype. On the other hand, it should be skipped if its notetype id is mapped to some new notetype. * Change field and template ids to i32 * Add merge notetypes flag to proto message * Add dialog for apkg import * Move HelpModal into components * Generalize import dialog * Move SettingTitle into components * Add help modal to ImportAnkiPackagePage * Move SwitchRow into components * Fix backend method import * Make testable in browser * Fix broken modal * Wrap in container and fix margins * Update commented Anki version of new proto fields * Check ids when comparing notetype schemas * Add tooltip for merging notetypes. * Allow updating notes regardless of mtime * Gitignore yarn-error.log * Allow updating notetypes regardless of mtime * Fix apkg help carousel * Use i64s for template and field ids * Add option to omit importing scheduling info * Restore last settings in apkg import dialog * Display error when getting metadata in webview * Update manual links for apkg importing * Apply suggestions from code review Co-authored-by: Damien Elmes <dae@users.noreply.github.com> * Omit schduling -> Import all cards as new cards * Tweak importing-update-notes-help * UpdateCondition → ImportAnkiPackageUpdateCondition * Load keyboard.ftl * Skip updating dupes in 'update alwyas' case * Explain more when merging notetypes is required * "omit scheduling" → "with scheduling" * Skip updating notetype dupes if 'update always' * Merge duplicated notetypes from previous imports * Fix rebase aftermath * Fix panic when merging * Clarify 'update notetypes' help * Mention 'merge notetypes' in the log * Add a test which covers the previously panicking path * Use nested ftl messages to ensure consistency * Make order of merged fields deterministic * Rewrite test to trigger panic * Update version comment on new fields
2023-09-09 01:00:55 +02:00
from aqt.import_export.import_dialog import ImportDialog
Improve presentation of importing results (#2568) * Implement import log screen in Svelte * Show filename in import log screen title * Remove unused NoteRow property * Show number of imported notes * Use a single nid expression * Use 'count' as variable name for consistency * Import from @tslib/backend instead * Fix summary_template typing * Fix clippy warning * Apply suggestions from code review * Fix imports * Contents -> Fields * Increase max length of browser search bar https://github.com/ankitects/anki/pull/2568/files#r1255227035 * Fix race condition in Bootstrap tooltip destruction https://github.com/twbs/bootstrap/issues/37474 * summary_template -> summaryTemplate * Make show link a button * Run import ops on Svelte side * Fix geometry not being restored in CSV Import page * Make VirtualTable fill available height * Keep CSV dialog modal * Reword importing-existing-notes-skipped * Avoid mentioning matching based on first field * Change tick and cross icons * List skipped notes last * Pure CSS spinner * Move set_wants_abort() call to relevant dialogs * Show number of imported cards * Remove bold from first sentence and indent summaries * Update UI after import operations * Add close button to import log page Also make virtual table react to resize event. * Fix typing * Make CSV dialog non-modal again Otherwise user can't interact with browser window. * Update window modality after import * Commit DB and update undo actions after import op * Split frontend proto into separate file, so backend can ignore it Currently the automatically-generated frontend RPC methods get placed in 'backend.js' with all the backend methods; we could optionally split them into a separate 'frontend.js' file in the future. * Migrate import_done from a bridgecmd to a HTTP request * Update plural form of importing-notes-added * Move import response handling to mediasrv * Move task callback to script section * Avoid unnecessary :global() * .log cannot be missing if result exists * Move import log search handling to mediasrv * Type common params of ImportLogDialog * Use else if * Remove console.log() * Add way to test apkg imports in new log screen * Remove unused import * Get actual card count for CSV imports * Use import type * Fix typing error * Ignore import log when checking for changes in Python layer * Apply suggestions from code review * Remove imported card count for now * Avoid non-null assertion in assignment * Change showInBrowser to take an array of notes * Use dataclasses for import log args * Simplify ResultWithChanges in TS * Only abort import when window is modal * Fix ResultWithChanges typing * Fix Rust warnings * Only log one duplicate per incoming note * Update wording about note updates * Remove caveat about found_notes * Reduce font size * Remove redundant map * Give credit to loading.io * Remove unused line --------- Co-authored-by: RumovZ <gp5glkw78@relay.firefox.com>
2023-08-02 12:29:44 +02:00
if isinstance(window, ImportDialog):
Improve presentation of importing results (#2568) * Implement import log screen in Svelte * Show filename in import log screen title * Remove unused NoteRow property * Show number of imported notes * Use a single nid expression * Use 'count' as variable name for consistency * Import from @tslib/backend instead * Fix summary_template typing * Fix clippy warning * Apply suggestions from code review * Fix imports * Contents -> Fields * Increase max length of browser search bar https://github.com/ankitects/anki/pull/2568/files#r1255227035 * Fix race condition in Bootstrap tooltip destruction https://github.com/twbs/bootstrap/issues/37474 * summary_template -> summaryTemplate * Make show link a button * Run import ops on Svelte side * Fix geometry not being restored in CSV Import page * Make VirtualTable fill available height * Keep CSV dialog modal * Reword importing-existing-notes-skipped * Avoid mentioning matching based on first field * Change tick and cross icons * List skipped notes last * Pure CSS spinner * Move set_wants_abort() call to relevant dialogs * Show number of imported cards * Remove bold from first sentence and indent summaries * Update UI after import operations * Add close button to import log page Also make virtual table react to resize event. * Fix typing * Make CSV dialog non-modal again Otherwise user can't interact with browser window. * Update window modality after import * Commit DB and update undo actions after import op * Split frontend proto into separate file, so backend can ignore it Currently the automatically-generated frontend RPC methods get placed in 'backend.js' with all the backend methods; we could optionally split them into a separate 'frontend.js' file in the future. * Migrate import_done from a bridgecmd to a HTTP request * Update plural form of importing-notes-added * Move import response handling to mediasrv * Move task callback to script section * Avoid unnecessary :global() * .log cannot be missing if result exists * Move import log search handling to mediasrv * Type common params of ImportLogDialog * Use else if * Remove console.log() * Add way to test apkg imports in new log screen * Remove unused import * Get actual card count for CSV imports * Use import type * Fix typing error * Ignore import log when checking for changes in Python layer * Apply suggestions from code review * Remove imported card count for now * Avoid non-null assertion in assignment * Change showInBrowser to take an array of notes * Use dataclasses for import log args * Simplify ResultWithChanges in TS * Only abort import when window is modal * Fix ResultWithChanges typing * Fix Rust warnings * Only log one duplicate per incoming note * Update wording about note updates * Remove caveat about found_notes * Reduce font size * Remove redundant map * Give credit to loading.io * Remove unused line --------- Co-authored-by: RumovZ <gp5glkw78@relay.firefox.com>
2023-08-02 12:29:44 +02:00
window.hide()
window.setWindowModality(Qt.WindowModality.NonModal)
window.show()
aqt.mw.taskman.run_on_main(update_window_modality)
return b""
def import_request(endpoint: str) -> bytes:
output = raw_backend_request(endpoint)()
response = OpChangesOnly()
response.ParseFromString(output)
def handle_on_main() -> None:
window = aqt.mw.app.activeWindow()
Improve presentation of importing results (#2568) * Implement import log screen in Svelte * Show filename in import log screen title * Remove unused NoteRow property * Show number of imported notes * Use a single nid expression * Use 'count' as variable name for consistency * Import from @tslib/backend instead * Fix summary_template typing * Fix clippy warning * Apply suggestions from code review * Fix imports * Contents -> Fields * Increase max length of browser search bar https://github.com/ankitects/anki/pull/2568/files#r1255227035 * Fix race condition in Bootstrap tooltip destruction https://github.com/twbs/bootstrap/issues/37474 * summary_template -> summaryTemplate * Make show link a button * Run import ops on Svelte side * Fix geometry not being restored in CSV Import page * Make VirtualTable fill available height * Keep CSV dialog modal * Reword importing-existing-notes-skipped * Avoid mentioning matching based on first field * Change tick and cross icons * List skipped notes last * Pure CSS spinner * Move set_wants_abort() call to relevant dialogs * Show number of imported cards * Remove bold from first sentence and indent summaries * Update UI after import operations * Add close button to import log page Also make virtual table react to resize event. * Fix typing * Make CSV dialog non-modal again Otherwise user can't interact with browser window. * Update window modality after import * Commit DB and update undo actions after import op * Split frontend proto into separate file, so backend can ignore it Currently the automatically-generated frontend RPC methods get placed in 'backend.js' with all the backend methods; we could optionally split them into a separate 'frontend.js' file in the future. * Migrate import_done from a bridgecmd to a HTTP request * Update plural form of importing-notes-added * Move import response handling to mediasrv * Move task callback to script section * Avoid unnecessary :global() * .log cannot be missing if result exists * Move import log search handling to mediasrv * Type common params of ImportLogDialog * Use else if * Remove console.log() * Add way to test apkg imports in new log screen * Remove unused import * Get actual card count for CSV imports * Use import type * Fix typing error * Ignore import log when checking for changes in Python layer * Apply suggestions from code review * Remove imported card count for now * Avoid non-null assertion in assignment * Change showInBrowser to take an array of notes * Use dataclasses for import log args * Simplify ResultWithChanges in TS * Only abort import when window is modal * Fix ResultWithChanges typing * Fix Rust warnings * Only log one duplicate per incoming note * Update wording about note updates * Remove caveat about found_notes * Reduce font size * Remove redundant map * Give credit to loading.io * Remove unused line --------- Co-authored-by: RumovZ <gp5glkw78@relay.firefox.com>
2023-08-02 12:29:44 +02:00
on_op_finished(aqt.mw, response, window)
aqt.mw.taskman.run_on_main(handle_on_main)
Improve presentation of importing results (#2568) * Implement import log screen in Svelte * Show filename in import log screen title * Remove unused NoteRow property * Show number of imported notes * Use a single nid expression * Use 'count' as variable name for consistency * Import from @tslib/backend instead * Fix summary_template typing * Fix clippy warning * Apply suggestions from code review * Fix imports * Contents -> Fields * Increase max length of browser search bar https://github.com/ankitects/anki/pull/2568/files#r1255227035 * Fix race condition in Bootstrap tooltip destruction https://github.com/twbs/bootstrap/issues/37474 * summary_template -> summaryTemplate * Make show link a button * Run import ops on Svelte side * Fix geometry not being restored in CSV Import page * Make VirtualTable fill available height * Keep CSV dialog modal * Reword importing-existing-notes-skipped * Avoid mentioning matching based on first field * Change tick and cross icons * List skipped notes last * Pure CSS spinner * Move set_wants_abort() call to relevant dialogs * Show number of imported cards * Remove bold from first sentence and indent summaries * Update UI after import operations * Add close button to import log page Also make virtual table react to resize event. * Fix typing * Make CSV dialog non-modal again Otherwise user can't interact with browser window. * Update window modality after import * Commit DB and update undo actions after import op * Split frontend proto into separate file, so backend can ignore it Currently the automatically-generated frontend RPC methods get placed in 'backend.js' with all the backend methods; we could optionally split them into a separate 'frontend.js' file in the future. * Migrate import_done from a bridgecmd to a HTTP request * Update plural form of importing-notes-added * Move import response handling to mediasrv * Move task callback to script section * Avoid unnecessary :global() * .log cannot be missing if result exists * Move import log search handling to mediasrv * Type common params of ImportLogDialog * Use else if * Remove console.log() * Add way to test apkg imports in new log screen * Remove unused import * Get actual card count for CSV imports * Use import type * Fix typing error * Ignore import log when checking for changes in Python layer * Apply suggestions from code review * Remove imported card count for now * Avoid non-null assertion in assignment * Change showInBrowser to take an array of notes * Use dataclasses for import log args * Simplify ResultWithChanges in TS * Only abort import when window is modal * Fix ResultWithChanges typing * Fix Rust warnings * Only log one duplicate per incoming note * Update wording about note updates * Remove caveat about found_notes * Reduce font size * Remove redundant map * Give credit to loading.io * Remove unused line --------- Co-authored-by: RumovZ <gp5glkw78@relay.firefox.com>
2023-08-02 12:29:44 +02:00
return output
Plaintext import/export (#1850) * Add crate csv * Add start of csv importing on backend * Add Menomosyne serializer * Add csv and json importing on backend * Add plaintext importing on frontend * Add csv metadata extraction on backend * Add csv importing with GUI * Fix missing dfa file in build Added compile_data_attr, then re-ran cargo/update.py. * Don't use doubly buffered reader in csv * Escape HTML entities if CSV is not HTML Also use name 'is_html' consistently. * Use decimal number as foreign ease (like '2.5') * ForeignCard.ivl → ForeignCard.interval * Only allow fixed set of CSV delimiters * Map timestamp of ForeignCard to native due time * Don't trim CSV records * Document use of empty strings for defaults * Avoid creating CardGenContexts for every note This requires CardGenContext to be generic, so it works both with an owned and borrowed notetype. * Show all accepted file types in import file picker * Add import_json_file() * factor → ease_factor * delimter_from_value → delimiter_from_value * Map columns to fields, not the other way around * Fallback to current config for csv metadata * Add start of new import csv screen * Temporary fix for compilation issue on Linux/Mac * Disable jest bazel action for import-csv Jest fails with an error code if no tests are available, but this would not be noticable on Windows as Jest is not run there. * Fix field mapping issue * Revert "Temporary fix for compilation issue on Linux/Mac" This reverts commit 21f8a261408cdae49ec031aa21a1b659c4f66d82. * Add HtmlSwitch and move Switch to components * Fix spacing and make selectors consistent * Fix shortcut tooltip * Place import button at the top with path * Fix meta column indices * Remove NotetypeForString * Fix queue and type of foreign cards * Support different dupe resolution strategies * Allow dupe resolution selection when importing CSV * Test import of unnormalized text Close #1863. * Fix logging of foreign notes * Implement CSV exports * Use db_scalar() in notes_table_len() * Rework CSV metadata - Notetypes and decks are either defined by a global id or by a column. - If a notetype id is provided, its field map must also be specified. - If a notetype column is provided, fields are now mapped by index instead of name at import time. So the first non-meta column is used for the first field of every note, regardless of notetype. This makes importing easier and should improve compatiblity with files without a notetype column. - Ensure first field can be mapped to a column. - Meta columns must be defined as `#[meta name]:[column index]` instead of in the `#columns` tag. - Column labels contain the raw names defined by the file and must be prettified by the frontend. * Adjust frontend to new backend column mapping * Add force flags for is_html and delimiter * Detect if CSV is HTML by field content * Update dupe resolution labels * Simplify selectors * Fix coalescence of oneofs in TS * Disable meta columns from selection Plus a lot of refactoring. * Make import button stick to the bottom * Write delimiter and html flag into csv * Refetch field map after notetype change * Fix log labels for csv import * Log notes whose deck/notetype was missing * Fix hiding of empty log queues * Implement adding tags to all notes of a csv * Fix dupe resolution not being set in log * Implement adding tags to updated notes of a csv * Check first note field is not empty * Temporary fix for build on Linux/Mac * Fix inverted html check (dae) * Remove unused ftl string * Delimiter → Separator * Remove commented-out line * Don't accept .json files * Tweak tag ftl strings * Remove redundant blur call * Strip sound and add spaces in csv export * Export HTML by default * Fix unset deck in Mnemosyne import Also accept both numbers and strings for notetypes and decks in JSON. * Make DupeResolution::Update the default * Fix missing dot in extension * Make column indices 1-based * Remove StickContainer from TagEditor Fixes line breaking, border and z index on ImportCsvPage. * Assign different key combos to tag editors * Log all updated duplicates Add a log field for the true number of found notes. * Show identical notes as skipped * Split tag-editor into separate ts module (dae) * Add progress for CSV export * Add progress for text import * Tidy-ups after tag-editor split (dae) - import-csv no longer depends on editor - remove some commented lines
2022-06-01 12:26:16 +02:00
def import_csv() -> bytes:
Improve presentation of importing results (#2568) * Implement import log screen in Svelte * Show filename in import log screen title * Remove unused NoteRow property * Show number of imported notes * Use a single nid expression * Use 'count' as variable name for consistency * Import from @tslib/backend instead * Fix summary_template typing * Fix clippy warning * Apply suggestions from code review * Fix imports * Contents -> Fields * Increase max length of browser search bar https://github.com/ankitects/anki/pull/2568/files#r1255227035 * Fix race condition in Bootstrap tooltip destruction https://github.com/twbs/bootstrap/issues/37474 * summary_template -> summaryTemplate * Make show link a button * Run import ops on Svelte side * Fix geometry not being restored in CSV Import page * Make VirtualTable fill available height * Keep CSV dialog modal * Reword importing-existing-notes-skipped * Avoid mentioning matching based on first field * Change tick and cross icons * List skipped notes last * Pure CSS spinner * Move set_wants_abort() call to relevant dialogs * Show number of imported cards * Remove bold from first sentence and indent summaries * Update UI after import operations * Add close button to import log page Also make virtual table react to resize event. * Fix typing * Make CSV dialog non-modal again Otherwise user can't interact with browser window. * Update window modality after import * Commit DB and update undo actions after import op * Split frontend proto into separate file, so backend can ignore it Currently the automatically-generated frontend RPC methods get placed in 'backend.js' with all the backend methods; we could optionally split them into a separate 'frontend.js' file in the future. * Migrate import_done from a bridgecmd to a HTTP request * Update plural form of importing-notes-added * Move import response handling to mediasrv * Move task callback to script section * Avoid unnecessary :global() * .log cannot be missing if result exists * Move import log search handling to mediasrv * Type common params of ImportLogDialog * Use else if * Remove console.log() * Add way to test apkg imports in new log screen * Remove unused import * Get actual card count for CSV imports * Use import type * Fix typing error * Ignore import log when checking for changes in Python layer * Apply suggestions from code review * Remove imported card count for now * Avoid non-null assertion in assignment * Change showInBrowser to take an array of notes * Use dataclasses for import log args * Simplify ResultWithChanges in TS * Only abort import when window is modal * Fix ResultWithChanges typing * Fix Rust warnings * Only log one duplicate per incoming note * Update wording about note updates * Remove caveat about found_notes * Reduce font size * Remove redundant map * Give credit to loading.io * Remove unused line --------- Co-authored-by: RumovZ <gp5glkw78@relay.firefox.com>
2023-08-02 12:29:44 +02:00
return import_request("import_csv")
def import_anki_package() -> bytes:
return import_request("import_anki_package")
def import_json_file() -> bytes:
return import_request("import_json_file")
def import_json_string() -> bytes:
return import_request("import_json_string")
def search_in_browser() -> bytes:
node = SearchNode()
node.ParseFromString(request.data)
def handle_on_main() -> None:
aqt.dialogs.open("Browser", aqt.mw, search=(node,))
aqt.mw.taskman.run_on_main(handle_on_main)
return b""
def change_notetype() -> bytes:
Plaintext import/export (#1850) * Add crate csv * Add start of csv importing on backend * Add Menomosyne serializer * Add csv and json importing on backend * Add plaintext importing on frontend * Add csv metadata extraction on backend * Add csv importing with GUI * Fix missing dfa file in build Added compile_data_attr, then re-ran cargo/update.py. * Don't use doubly buffered reader in csv * Escape HTML entities if CSV is not HTML Also use name 'is_html' consistently. * Use decimal number as foreign ease (like '2.5') * ForeignCard.ivl → ForeignCard.interval * Only allow fixed set of CSV delimiters * Map timestamp of ForeignCard to native due time * Don't trim CSV records * Document use of empty strings for defaults * Avoid creating CardGenContexts for every note This requires CardGenContext to be generic, so it works both with an owned and borrowed notetype. * Show all accepted file types in import file picker * Add import_json_file() * factor → ease_factor * delimter_from_value → delimiter_from_value * Map columns to fields, not the other way around * Fallback to current config for csv metadata * Add start of new import csv screen * Temporary fix for compilation issue on Linux/Mac * Disable jest bazel action for import-csv Jest fails with an error code if no tests are available, but this would not be noticable on Windows as Jest is not run there. * Fix field mapping issue * Revert "Temporary fix for compilation issue on Linux/Mac" This reverts commit 21f8a261408cdae49ec031aa21a1b659c4f66d82. * Add HtmlSwitch and move Switch to components * Fix spacing and make selectors consistent * Fix shortcut tooltip * Place import button at the top with path * Fix meta column indices * Remove NotetypeForString * Fix queue and type of foreign cards * Support different dupe resolution strategies * Allow dupe resolution selection when importing CSV * Test import of unnormalized text Close #1863. * Fix logging of foreign notes * Implement CSV exports * Use db_scalar() in notes_table_len() * Rework CSV metadata - Notetypes and decks are either defined by a global id or by a column. - If a notetype id is provided, its field map must also be specified. - If a notetype column is provided, fields are now mapped by index instead of name at import time. So the first non-meta column is used for the first field of every note, regardless of notetype. This makes importing easier and should improve compatiblity with files without a notetype column. - Ensure first field can be mapped to a column. - Meta columns must be defined as `#[meta name]:[column index]` instead of in the `#columns` tag. - Column labels contain the raw names defined by the file and must be prettified by the frontend. * Adjust frontend to new backend column mapping * Add force flags for is_html and delimiter * Detect if CSV is HTML by field content * Update dupe resolution labels * Simplify selectors * Fix coalescence of oneofs in TS * Disable meta columns from selection Plus a lot of refactoring. * Make import button stick to the bottom * Write delimiter and html flag into csv * Refetch field map after notetype change * Fix log labels for csv import * Log notes whose deck/notetype was missing * Fix hiding of empty log queues * Implement adding tags to all notes of a csv * Fix dupe resolution not being set in log * Implement adding tags to updated notes of a csv * Check first note field is not empty * Temporary fix for build on Linux/Mac * Fix inverted html check (dae) * Remove unused ftl string * Delimiter → Separator * Remove commented-out line * Don't accept .json files * Tweak tag ftl strings * Remove redundant blur call * Strip sound and add spaces in csv export * Export HTML by default * Fix unset deck in Mnemosyne import Also accept both numbers and strings for notetypes and decks in JSON. * Make DupeResolution::Update the default * Fix missing dot in extension * Make column indices 1-based * Remove StickContainer from TagEditor Fixes line breaking, border and z index on ImportCsvPage. * Assign different key combos to tag editors * Log all updated duplicates Add a log field for the true number of found notes. * Show identical notes as skipped * Split tag-editor into separate ts module (dae) * Add progress for CSV export * Add progress for text import * Tidy-ups after tag-editor split (dae) - import-csv no longer depends on editor - remove some commented lines
2022-06-01 12:26:16 +02:00
data = request.data
def handle_on_main() -> None:
window = aqt.mw.app.activeWindow()
Improve presentation of importing results (#2568) * Implement import log screen in Svelte * Show filename in import log screen title * Remove unused NoteRow property * Show number of imported notes * Use a single nid expression * Use 'count' as variable name for consistency * Import from @tslib/backend instead * Fix summary_template typing * Fix clippy warning * Apply suggestions from code review * Fix imports * Contents -> Fields * Increase max length of browser search bar https://github.com/ankitects/anki/pull/2568/files#r1255227035 * Fix race condition in Bootstrap tooltip destruction https://github.com/twbs/bootstrap/issues/37474 * summary_template -> summaryTemplate * Make show link a button * Run import ops on Svelte side * Fix geometry not being restored in CSV Import page * Make VirtualTable fill available height * Keep CSV dialog modal * Reword importing-existing-notes-skipped * Avoid mentioning matching based on first field * Change tick and cross icons * List skipped notes last * Pure CSS spinner * Move set_wants_abort() call to relevant dialogs * Show number of imported cards * Remove bold from first sentence and indent summaries * Update UI after import operations * Add close button to import log page Also make virtual table react to resize event. * Fix typing * Make CSV dialog non-modal again Otherwise user can't interact with browser window. * Update window modality after import * Commit DB and update undo actions after import op * Split frontend proto into separate file, so backend can ignore it Currently the automatically-generated frontend RPC methods get placed in 'backend.js' with all the backend methods; we could optionally split them into a separate 'frontend.js' file in the future. * Migrate import_done from a bridgecmd to a HTTP request * Update plural form of importing-notes-added * Move import response handling to mediasrv * Move task callback to script section * Avoid unnecessary :global() * .log cannot be missing if result exists * Move import log search handling to mediasrv * Type common params of ImportLogDialog * Use else if * Remove console.log() * Add way to test apkg imports in new log screen * Remove unused import * Get actual card count for CSV imports * Use import type * Fix typing error * Ignore import log when checking for changes in Python layer * Apply suggestions from code review * Remove imported card count for now * Avoid non-null assertion in assignment * Change showInBrowser to take an array of notes * Use dataclasses for import log args * Simplify ResultWithChanges in TS * Only abort import when window is modal * Fix ResultWithChanges typing * Fix Rust warnings * Only log one duplicate per incoming note * Update wording about note updates * Remove caveat about found_notes * Reduce font size * Remove redundant map * Give credit to loading.io * Remove unused line --------- Co-authored-by: RumovZ <gp5glkw78@relay.firefox.com>
2023-08-02 12:29:44 +02:00
if isinstance(window, ChangeNotetypeDialog):
window.save(data)
Plaintext import/export (#1850) * Add crate csv * Add start of csv importing on backend * Add Menomosyne serializer * Add csv and json importing on backend * Add plaintext importing on frontend * Add csv metadata extraction on backend * Add csv importing with GUI * Fix missing dfa file in build Added compile_data_attr, then re-ran cargo/update.py. * Don't use doubly buffered reader in csv * Escape HTML entities if CSV is not HTML Also use name 'is_html' consistently. * Use decimal number as foreign ease (like '2.5') * ForeignCard.ivl → ForeignCard.interval * Only allow fixed set of CSV delimiters * Map timestamp of ForeignCard to native due time * Don't trim CSV records * Document use of empty strings for defaults * Avoid creating CardGenContexts for every note This requires CardGenContext to be generic, so it works both with an owned and borrowed notetype. * Show all accepted file types in import file picker * Add import_json_file() * factor → ease_factor * delimter_from_value → delimiter_from_value * Map columns to fields, not the other way around * Fallback to current config for csv metadata * Add start of new import csv screen * Temporary fix for compilation issue on Linux/Mac * Disable jest bazel action for import-csv Jest fails with an error code if no tests are available, but this would not be noticable on Windows as Jest is not run there. * Fix field mapping issue * Revert "Temporary fix for compilation issue on Linux/Mac" This reverts commit 21f8a261408cdae49ec031aa21a1b659c4f66d82. * Add HtmlSwitch and move Switch to components * Fix spacing and make selectors consistent * Fix shortcut tooltip * Place import button at the top with path * Fix meta column indices * Remove NotetypeForString * Fix queue and type of foreign cards * Support different dupe resolution strategies * Allow dupe resolution selection when importing CSV * Test import of unnormalized text Close #1863. * Fix logging of foreign notes * Implement CSV exports * Use db_scalar() in notes_table_len() * Rework CSV metadata - Notetypes and decks are either defined by a global id or by a column. - If a notetype id is provided, its field map must also be specified. - If a notetype column is provided, fields are now mapped by index instead of name at import time. So the first non-meta column is used for the first field of every note, regardless of notetype. This makes importing easier and should improve compatiblity with files without a notetype column. - Ensure first field can be mapped to a column. - Meta columns must be defined as `#[meta name]:[column index]` instead of in the `#columns` tag. - Column labels contain the raw names defined by the file and must be prettified by the frontend. * Adjust frontend to new backend column mapping * Add force flags for is_html and delimiter * Detect if CSV is HTML by field content * Update dupe resolution labels * Simplify selectors * Fix coalescence of oneofs in TS * Disable meta columns from selection Plus a lot of refactoring. * Make import button stick to the bottom * Write delimiter and html flag into csv * Refetch field map after notetype change * Fix log labels for csv import * Log notes whose deck/notetype was missing * Fix hiding of empty log queues * Implement adding tags to all notes of a csv * Fix dupe resolution not being set in log * Implement adding tags to updated notes of a csv * Check first note field is not empty * Temporary fix for build on Linux/Mac * Fix inverted html check (dae) * Remove unused ftl string * Delimiter → Separator * Remove commented-out line * Don't accept .json files * Tweak tag ftl strings * Remove redundant blur call * Strip sound and add spaces in csv export * Export HTML by default * Fix unset deck in Mnemosyne import Also accept both numbers and strings for notetypes and decks in JSON. * Make DupeResolution::Update the default * Fix missing dot in extension * Make column indices 1-based * Remove StickContainer from TagEditor Fixes line breaking, border and z index on ImportCsvPage. * Assign different key combos to tag editors * Log all updated duplicates Add a log field for the true number of found notes. * Show identical notes as skipped * Split tag-editor into separate ts module (dae) * Add progress for CSV export * Add progress for text import * Tidy-ups after tag-editor split (dae) - import-csv no longer depends on editor - remove some commented lines
2022-06-01 12:26:16 +02:00
aqt.mw.taskman.run_on_main(handle_on_main)
return b""
post_handler_list = [
congrats_info,
get_deck_configs_for_update,
update_deck_configs,
get_scheduling_states_with_context,
set_scheduling_states,
change_notetype,
Improve presentation of importing results (#2568) * Implement import log screen in Svelte * Show filename in import log screen title * Remove unused NoteRow property * Show number of imported notes * Use a single nid expression * Use 'count' as variable name for consistency * Import from @tslib/backend instead * Fix summary_template typing * Fix clippy warning * Apply suggestions from code review * Fix imports * Contents -> Fields * Increase max length of browser search bar https://github.com/ankitects/anki/pull/2568/files#r1255227035 * Fix race condition in Bootstrap tooltip destruction https://github.com/twbs/bootstrap/issues/37474 * summary_template -> summaryTemplate * Make show link a button * Run import ops on Svelte side * Fix geometry not being restored in CSV Import page * Make VirtualTable fill available height * Keep CSV dialog modal * Reword importing-existing-notes-skipped * Avoid mentioning matching based on first field * Change tick and cross icons * List skipped notes last * Pure CSS spinner * Move set_wants_abort() call to relevant dialogs * Show number of imported cards * Remove bold from first sentence and indent summaries * Update UI after import operations * Add close button to import log page Also make virtual table react to resize event. * Fix typing * Make CSV dialog non-modal again Otherwise user can't interact with browser window. * Update window modality after import * Commit DB and update undo actions after import op * Split frontend proto into separate file, so backend can ignore it Currently the automatically-generated frontend RPC methods get placed in 'backend.js' with all the backend methods; we could optionally split them into a separate 'frontend.js' file in the future. * Migrate import_done from a bridgecmd to a HTTP request * Update plural form of importing-notes-added * Move import response handling to mediasrv * Move task callback to script section * Avoid unnecessary :global() * .log cannot be missing if result exists * Move import log search handling to mediasrv * Type common params of ImportLogDialog * Use else if * Remove console.log() * Add way to test apkg imports in new log screen * Remove unused import * Get actual card count for CSV imports * Use import type * Fix typing error * Ignore import log when checking for changes in Python layer * Apply suggestions from code review * Remove imported card count for now * Avoid non-null assertion in assignment * Change showInBrowser to take an array of notes * Use dataclasses for import log args * Simplify ResultWithChanges in TS * Only abort import when window is modal * Fix ResultWithChanges typing * Fix Rust warnings * Only log one duplicate per incoming note * Update wording about note updates * Remove caveat about found_notes * Reduce font size * Remove redundant map * Give credit to loading.io * Remove unused line --------- Co-authored-by: RumovZ <gp5glkw78@relay.firefox.com>
2023-08-02 12:29:44 +02:00
import_done,
Plaintext import/export (#1850) * Add crate csv * Add start of csv importing on backend * Add Menomosyne serializer * Add csv and json importing on backend * Add plaintext importing on frontend * Add csv metadata extraction on backend * Add csv importing with GUI * Fix missing dfa file in build Added compile_data_attr, then re-ran cargo/update.py. * Don't use doubly buffered reader in csv * Escape HTML entities if CSV is not HTML Also use name 'is_html' consistently. * Use decimal number as foreign ease (like '2.5') * ForeignCard.ivl → ForeignCard.interval * Only allow fixed set of CSV delimiters * Map timestamp of ForeignCard to native due time * Don't trim CSV records * Document use of empty strings for defaults * Avoid creating CardGenContexts for every note This requires CardGenContext to be generic, so it works both with an owned and borrowed notetype. * Show all accepted file types in import file picker * Add import_json_file() * factor → ease_factor * delimter_from_value → delimiter_from_value * Map columns to fields, not the other way around * Fallback to current config for csv metadata * Add start of new import csv screen * Temporary fix for compilation issue on Linux/Mac * Disable jest bazel action for import-csv Jest fails with an error code if no tests are available, but this would not be noticable on Windows as Jest is not run there. * Fix field mapping issue * Revert "Temporary fix for compilation issue on Linux/Mac" This reverts commit 21f8a261408cdae49ec031aa21a1b659c4f66d82. * Add HtmlSwitch and move Switch to components * Fix spacing and make selectors consistent * Fix shortcut tooltip * Place import button at the top with path * Fix meta column indices * Remove NotetypeForString * Fix queue and type of foreign cards * Support different dupe resolution strategies * Allow dupe resolution selection when importing CSV * Test import of unnormalized text Close #1863. * Fix logging of foreign notes * Implement CSV exports * Use db_scalar() in notes_table_len() * Rework CSV metadata - Notetypes and decks are either defined by a global id or by a column. - If a notetype id is provided, its field map must also be specified. - If a notetype column is provided, fields are now mapped by index instead of name at import time. So the first non-meta column is used for the first field of every note, regardless of notetype. This makes importing easier and should improve compatiblity with files without a notetype column. - Ensure first field can be mapped to a column. - Meta columns must be defined as `#[meta name]:[column index]` instead of in the `#columns` tag. - Column labels contain the raw names defined by the file and must be prettified by the frontend. * Adjust frontend to new backend column mapping * Add force flags for is_html and delimiter * Detect if CSV is HTML by field content * Update dupe resolution labels * Simplify selectors * Fix coalescence of oneofs in TS * Disable meta columns from selection Plus a lot of refactoring. * Make import button stick to the bottom * Write delimiter and html flag into csv * Refetch field map after notetype change * Fix log labels for csv import * Log notes whose deck/notetype was missing * Fix hiding of empty log queues * Implement adding tags to all notes of a csv * Fix dupe resolution not being set in log * Implement adding tags to updated notes of a csv * Check first note field is not empty * Temporary fix for build on Linux/Mac * Fix inverted html check (dae) * Remove unused ftl string * Delimiter → Separator * Remove commented-out line * Don't accept .json files * Tweak tag ftl strings * Remove redundant blur call * Strip sound and add spaces in csv export * Export HTML by default * Fix unset deck in Mnemosyne import Also accept both numbers and strings for notetypes and decks in JSON. * Make DupeResolution::Update the default * Fix missing dot in extension * Make column indices 1-based * Remove StickContainer from TagEditor Fixes line breaking, border and z index on ImportCsvPage. * Assign different key combos to tag editors * Log all updated duplicates Add a log field for the true number of found notes. * Show identical notes as skipped * Split tag-editor into separate ts module (dae) * Add progress for CSV export * Add progress for text import * Tidy-ups after tag-editor split (dae) - import-csv no longer depends on editor - remove some commented lines
2022-06-01 12:26:16 +02:00
import_csv,
Improve presentation of importing results (#2568) * Implement import log screen in Svelte * Show filename in import log screen title * Remove unused NoteRow property * Show number of imported notes * Use a single nid expression * Use 'count' as variable name for consistency * Import from @tslib/backend instead * Fix summary_template typing * Fix clippy warning * Apply suggestions from code review * Fix imports * Contents -> Fields * Increase max length of browser search bar https://github.com/ankitects/anki/pull/2568/files#r1255227035 * Fix race condition in Bootstrap tooltip destruction https://github.com/twbs/bootstrap/issues/37474 * summary_template -> summaryTemplate * Make show link a button * Run import ops on Svelte side * Fix geometry not being restored in CSV Import page * Make VirtualTable fill available height * Keep CSV dialog modal * Reword importing-existing-notes-skipped * Avoid mentioning matching based on first field * Change tick and cross icons * List skipped notes last * Pure CSS spinner * Move set_wants_abort() call to relevant dialogs * Show number of imported cards * Remove bold from first sentence and indent summaries * Update UI after import operations * Add close button to import log page Also make virtual table react to resize event. * Fix typing * Make CSV dialog non-modal again Otherwise user can't interact with browser window. * Update window modality after import * Commit DB and update undo actions after import op * Split frontend proto into separate file, so backend can ignore it Currently the automatically-generated frontend RPC methods get placed in 'backend.js' with all the backend methods; we could optionally split them into a separate 'frontend.js' file in the future. * Migrate import_done from a bridgecmd to a HTTP request * Update plural form of importing-notes-added * Move import response handling to mediasrv * Move task callback to script section * Avoid unnecessary :global() * .log cannot be missing if result exists * Move import log search handling to mediasrv * Type common params of ImportLogDialog * Use else if * Remove console.log() * Add way to test apkg imports in new log screen * Remove unused import * Get actual card count for CSV imports * Use import type * Fix typing error * Ignore import log when checking for changes in Python layer * Apply suggestions from code review * Remove imported card count for now * Avoid non-null assertion in assignment * Change showInBrowser to take an array of notes * Use dataclasses for import log args * Simplify ResultWithChanges in TS * Only abort import when window is modal * Fix ResultWithChanges typing * Fix Rust warnings * Only log one duplicate per incoming note * Update wording about note updates * Remove caveat about found_notes * Reduce font size * Remove redundant map * Give credit to loading.io * Remove unused line --------- Co-authored-by: RumovZ <gp5glkw78@relay.firefox.com>
2023-08-02 12:29:44 +02:00
import_anki_package,
import_json_file,
import_json_string,
search_in_browser,
]
exposed_backend_list = [
Improve presentation of importing results (#2568) * Implement import log screen in Svelte * Show filename in import log screen title * Remove unused NoteRow property * Show number of imported notes * Use a single nid expression * Use 'count' as variable name for consistency * Import from @tslib/backend instead * Fix summary_template typing * Fix clippy warning * Apply suggestions from code review * Fix imports * Contents -> Fields * Increase max length of browser search bar https://github.com/ankitects/anki/pull/2568/files#r1255227035 * Fix race condition in Bootstrap tooltip destruction https://github.com/twbs/bootstrap/issues/37474 * summary_template -> summaryTemplate * Make show link a button * Run import ops on Svelte side * Fix geometry not being restored in CSV Import page * Make VirtualTable fill available height * Keep CSV dialog modal * Reword importing-existing-notes-skipped * Avoid mentioning matching based on first field * Change tick and cross icons * List skipped notes last * Pure CSS spinner * Move set_wants_abort() call to relevant dialogs * Show number of imported cards * Remove bold from first sentence and indent summaries * Update UI after import operations * Add close button to import log page Also make virtual table react to resize event. * Fix typing * Make CSV dialog non-modal again Otherwise user can't interact with browser window. * Update window modality after import * Commit DB and update undo actions after import op * Split frontend proto into separate file, so backend can ignore it Currently the automatically-generated frontend RPC methods get placed in 'backend.js' with all the backend methods; we could optionally split them into a separate 'frontend.js' file in the future. * Migrate import_done from a bridgecmd to a HTTP request * Update plural form of importing-notes-added * Move import response handling to mediasrv * Move task callback to script section * Avoid unnecessary :global() * .log cannot be missing if result exists * Move import log search handling to mediasrv * Type common params of ImportLogDialog * Use else if * Remove console.log() * Add way to test apkg imports in new log screen * Remove unused import * Get actual card count for CSV imports * Use import type * Fix typing error * Ignore import log when checking for changes in Python layer * Apply suggestions from code review * Remove imported card count for now * Avoid non-null assertion in assignment * Change showInBrowser to take an array of notes * Use dataclasses for import log args * Simplify ResultWithChanges in TS * Only abort import when window is modal * Fix ResultWithChanges typing * Fix Rust warnings * Only log one duplicate per incoming note * Update wording about note updates * Remove caveat about found_notes * Reduce font size * Remove redundant map * Give credit to loading.io * Remove unused line --------- Co-authored-by: RumovZ <gp5glkw78@relay.firefox.com>
2023-08-02 12:29:44 +02:00
# CollectionService
"latest_progress",
Plaintext import/export (#1850) * Add crate csv * Add start of csv importing on backend * Add Menomosyne serializer * Add csv and json importing on backend * Add plaintext importing on frontend * Add csv metadata extraction on backend * Add csv importing with GUI * Fix missing dfa file in build Added compile_data_attr, then re-ran cargo/update.py. * Don't use doubly buffered reader in csv * Escape HTML entities if CSV is not HTML Also use name 'is_html' consistently. * Use decimal number as foreign ease (like '2.5') * ForeignCard.ivl → ForeignCard.interval * Only allow fixed set of CSV delimiters * Map timestamp of ForeignCard to native due time * Don't trim CSV records * Document use of empty strings for defaults * Avoid creating CardGenContexts for every note This requires CardGenContext to be generic, so it works both with an owned and borrowed notetype. * Show all accepted file types in import file picker * Add import_json_file() * factor → ease_factor * delimter_from_value → delimiter_from_value * Map columns to fields, not the other way around * Fallback to current config for csv metadata * Add start of new import csv screen * Temporary fix for compilation issue on Linux/Mac * Disable jest bazel action for import-csv Jest fails with an error code if no tests are available, but this would not be noticable on Windows as Jest is not run there. * Fix field mapping issue * Revert "Temporary fix for compilation issue on Linux/Mac" This reverts commit 21f8a261408cdae49ec031aa21a1b659c4f66d82. * Add HtmlSwitch and move Switch to components * Fix spacing and make selectors consistent * Fix shortcut tooltip * Place import button at the top with path * Fix meta column indices * Remove NotetypeForString * Fix queue and type of foreign cards * Support different dupe resolution strategies * Allow dupe resolution selection when importing CSV * Test import of unnormalized text Close #1863. * Fix logging of foreign notes * Implement CSV exports * Use db_scalar() in notes_table_len() * Rework CSV metadata - Notetypes and decks are either defined by a global id or by a column. - If a notetype id is provided, its field map must also be specified. - If a notetype column is provided, fields are now mapped by index instead of name at import time. So the first non-meta column is used for the first field of every note, regardless of notetype. This makes importing easier and should improve compatiblity with files without a notetype column. - Ensure first field can be mapped to a column. - Meta columns must be defined as `#[meta name]:[column index]` instead of in the `#columns` tag. - Column labels contain the raw names defined by the file and must be prettified by the frontend. * Adjust frontend to new backend column mapping * Add force flags for is_html and delimiter * Detect if CSV is HTML by field content * Update dupe resolution labels * Simplify selectors * Fix coalescence of oneofs in TS * Disable meta columns from selection Plus a lot of refactoring. * Make import button stick to the bottom * Write delimiter and html flag into csv * Refetch field map after notetype change * Fix log labels for csv import * Log notes whose deck/notetype was missing * Fix hiding of empty log queues * Implement adding tags to all notes of a csv * Fix dupe resolution not being set in log * Implement adding tags to updated notes of a csv * Check first note field is not empty * Temporary fix for build on Linux/Mac * Fix inverted html check (dae) * Remove unused ftl string * Delimiter → Separator * Remove commented-out line * Don't accept .json files * Tweak tag ftl strings * Remove redundant blur call * Strip sound and add spaces in csv export * Export HTML by default * Fix unset deck in Mnemosyne import Also accept both numbers and strings for notetypes and decks in JSON. * Make DupeResolution::Update the default * Fix missing dot in extension * Make column indices 1-based * Remove StickContainer from TagEditor Fixes line breaking, border and z index on ImportCsvPage. * Assign different key combos to tag editors * Log all updated duplicates Add a log field for the true number of found notes. * Show identical notes as skipped * Split tag-editor into separate ts module (dae) * Add progress for CSV export * Add progress for text import * Tidy-ups after tag-editor split (dae) - import-csv no longer depends on editor - remove some commented lines
2022-06-01 12:26:16 +02:00
# DeckService
"get_deck_names",
# I18nService
"i18n_resources",
Plaintext import/export (#1850) * Add crate csv * Add start of csv importing on backend * Add Menomosyne serializer * Add csv and json importing on backend * Add plaintext importing on frontend * Add csv metadata extraction on backend * Add csv importing with GUI * Fix missing dfa file in build Added compile_data_attr, then re-ran cargo/update.py. * Don't use doubly buffered reader in csv * Escape HTML entities if CSV is not HTML Also use name 'is_html' consistently. * Use decimal number as foreign ease (like '2.5') * ForeignCard.ivl → ForeignCard.interval * Only allow fixed set of CSV delimiters * Map timestamp of ForeignCard to native due time * Don't trim CSV records * Document use of empty strings for defaults * Avoid creating CardGenContexts for every note This requires CardGenContext to be generic, so it works both with an owned and borrowed notetype. * Show all accepted file types in import file picker * Add import_json_file() * factor → ease_factor * delimter_from_value → delimiter_from_value * Map columns to fields, not the other way around * Fallback to current config for csv metadata * Add start of new import csv screen * Temporary fix for compilation issue on Linux/Mac * Disable jest bazel action for import-csv Jest fails with an error code if no tests are available, but this would not be noticable on Windows as Jest is not run there. * Fix field mapping issue * Revert "Temporary fix for compilation issue on Linux/Mac" This reverts commit 21f8a261408cdae49ec031aa21a1b659c4f66d82. * Add HtmlSwitch and move Switch to components * Fix spacing and make selectors consistent * Fix shortcut tooltip * Place import button at the top with path * Fix meta column indices * Remove NotetypeForString * Fix queue and type of foreign cards * Support different dupe resolution strategies * Allow dupe resolution selection when importing CSV * Test import of unnormalized text Close #1863. * Fix logging of foreign notes * Implement CSV exports * Use db_scalar() in notes_table_len() * Rework CSV metadata - Notetypes and decks are either defined by a global id or by a column. - If a notetype id is provided, its field map must also be specified. - If a notetype column is provided, fields are now mapped by index instead of name at import time. So the first non-meta column is used for the first field of every note, regardless of notetype. This makes importing easier and should improve compatiblity with files without a notetype column. - Ensure first field can be mapped to a column. - Meta columns must be defined as `#[meta name]:[column index]` instead of in the `#columns` tag. - Column labels contain the raw names defined by the file and must be prettified by the frontend. * Adjust frontend to new backend column mapping * Add force flags for is_html and delimiter * Detect if CSV is HTML by field content * Update dupe resolution labels * Simplify selectors * Fix coalescence of oneofs in TS * Disable meta columns from selection Plus a lot of refactoring. * Make import button stick to the bottom * Write delimiter and html flag into csv * Refetch field map after notetype change * Fix log labels for csv import * Log notes whose deck/notetype was missing * Fix hiding of empty log queues * Implement adding tags to all notes of a csv * Fix dupe resolution not being set in log * Implement adding tags to updated notes of a csv * Check first note field is not empty * Temporary fix for build on Linux/Mac * Fix inverted html check (dae) * Remove unused ftl string * Delimiter → Separator * Remove commented-out line * Don't accept .json files * Tweak tag ftl strings * Remove redundant blur call * Strip sound and add spaces in csv export * Export HTML by default * Fix unset deck in Mnemosyne import Also accept both numbers and strings for notetypes and decks in JSON. * Make DupeResolution::Update the default * Fix missing dot in extension * Make column indices 1-based * Remove StickContainer from TagEditor Fixes line breaking, border and z index on ImportCsvPage. * Assign different key combos to tag editors * Log all updated duplicates Add a log field for the true number of found notes. * Show identical notes as skipped * Split tag-editor into separate ts module (dae) * Add progress for CSV export * Add progress for text import * Tidy-ups after tag-editor split (dae) - import-csv no longer depends on editor - remove some commented lines
2022-06-01 12:26:16 +02:00
# ImportExportService
"get_csv_metadata",
Merging Notetypes on Import (#2612) * Remember original id when importing notetype * Reuse notetypes with matching original id * Add field and template ids * Enable merging imported notetypes * Fix test Note should be updated if the incoming note's notetype is remapped to the existing note's notetype. On the other hand, it should be skipped if its notetype id is mapped to some new notetype. * Change field and template ids to i32 * Add merge notetypes flag to proto message * Add dialog for apkg import * Move HelpModal into components * Generalize import dialog * Move SettingTitle into components * Add help modal to ImportAnkiPackagePage * Move SwitchRow into components * Fix backend method import * Make testable in browser * Fix broken modal * Wrap in container and fix margins * Update commented Anki version of new proto fields * Check ids when comparing notetype schemas * Add tooltip for merging notetypes. * Allow updating notes regardless of mtime * Gitignore yarn-error.log * Allow updating notetypes regardless of mtime * Fix apkg help carousel * Use i64s for template and field ids * Add option to omit importing scheduling info * Restore last settings in apkg import dialog * Display error when getting metadata in webview * Update manual links for apkg importing * Apply suggestions from code review Co-authored-by: Damien Elmes <dae@users.noreply.github.com> * Omit schduling -> Import all cards as new cards * Tweak importing-update-notes-help * UpdateCondition → ImportAnkiPackageUpdateCondition * Load keyboard.ftl * Skip updating dupes in 'update alwyas' case * Explain more when merging notetypes is required * "omit scheduling" → "with scheduling" * Skip updating notetype dupes if 'update always' * Merge duplicated notetypes from previous imports * Fix rebase aftermath * Fix panic when merging * Clarify 'update notetypes' help * Mention 'merge notetypes' in the log * Add a test which covers the previously panicking path * Use nested ftl messages to ensure consistency * Make order of merged fields deterministic * Rewrite test to trigger panic * Update version comment on new fields
2023-09-09 01:00:55 +02:00
"get_import_anki_package_presets",
# NotesService
Plaintext import/export (#1850) * Add crate csv * Add start of csv importing on backend * Add Menomosyne serializer * Add csv and json importing on backend * Add plaintext importing on frontend * Add csv metadata extraction on backend * Add csv importing with GUI * Fix missing dfa file in build Added compile_data_attr, then re-ran cargo/update.py. * Don't use doubly buffered reader in csv * Escape HTML entities if CSV is not HTML Also use name 'is_html' consistently. * Use decimal number as foreign ease (like '2.5') * ForeignCard.ivl → ForeignCard.interval * Only allow fixed set of CSV delimiters * Map timestamp of ForeignCard to native due time * Don't trim CSV records * Document use of empty strings for defaults * Avoid creating CardGenContexts for every note This requires CardGenContext to be generic, so it works both with an owned and borrowed notetype. * Show all accepted file types in import file picker * Add import_json_file() * factor → ease_factor * delimter_from_value → delimiter_from_value * Map columns to fields, not the other way around * Fallback to current config for csv metadata * Add start of new import csv screen * Temporary fix for compilation issue on Linux/Mac * Disable jest bazel action for import-csv Jest fails with an error code if no tests are available, but this would not be noticable on Windows as Jest is not run there. * Fix field mapping issue * Revert "Temporary fix for compilation issue on Linux/Mac" This reverts commit 21f8a261408cdae49ec031aa21a1b659c4f66d82. * Add HtmlSwitch and move Switch to components * Fix spacing and make selectors consistent * Fix shortcut tooltip * Place import button at the top with path * Fix meta column indices * Remove NotetypeForString * Fix queue and type of foreign cards * Support different dupe resolution strategies * Allow dupe resolution selection when importing CSV * Test import of unnormalized text Close #1863. * Fix logging of foreign notes * Implement CSV exports * Use db_scalar() in notes_table_len() * Rework CSV metadata - Notetypes and decks are either defined by a global id or by a column. - If a notetype id is provided, its field map must also be specified. - If a notetype column is provided, fields are now mapped by index instead of name at import time. So the first non-meta column is used for the first field of every note, regardless of notetype. This makes importing easier and should improve compatiblity with files without a notetype column. - Ensure first field can be mapped to a column. - Meta columns must be defined as `#[meta name]:[column index]` instead of in the `#columns` tag. - Column labels contain the raw names defined by the file and must be prettified by the frontend. * Adjust frontend to new backend column mapping * Add force flags for is_html and delimiter * Detect if CSV is HTML by field content * Update dupe resolution labels * Simplify selectors * Fix coalescence of oneofs in TS * Disable meta columns from selection Plus a lot of refactoring. * Make import button stick to the bottom * Write delimiter and html flag into csv * Refetch field map after notetype change * Fix log labels for csv import * Log notes whose deck/notetype was missing * Fix hiding of empty log queues * Implement adding tags to all notes of a csv * Fix dupe resolution not being set in log * Implement adding tags to updated notes of a csv * Check first note field is not empty * Temporary fix for build on Linux/Mac * Fix inverted html check (dae) * Remove unused ftl string * Delimiter → Separator * Remove commented-out line * Don't accept .json files * Tweak tag ftl strings * Remove redundant blur call * Strip sound and add spaces in csv export * Export HTML by default * Fix unset deck in Mnemosyne import Also accept both numbers and strings for notetypes and decks in JSON. * Make DupeResolution::Update the default * Fix missing dot in extension * Make column indices 1-based * Remove StickContainer from TagEditor Fixes line breaking, border and z index on ImportCsvPage. * Assign different key combos to tag editors * Log all updated duplicates Add a log field for the true number of found notes. * Show identical notes as skipped * Split tag-editor into separate ts module (dae) * Add progress for CSV export * Add progress for text import * Tidy-ups after tag-editor split (dae) - import-csv no longer depends on editor - remove some commented lines
2022-06-01 12:26:16 +02:00
"get_field_names",
"get_note",
# NotetypesService
"get_notetype_names",
"get_change_notetype_info",
# StatsService
"card_stats",
"graphs",
"get_graph_preferences",
"set_graph_preferences",
# TagsService
"complete_tag",
Feature image occlusion (#2367) * add note types with occlusions and image fields * generate image occlusion cloze div data - generate div element with data-* atrributes for canvas shape generate for reviewer * getting image data & deck id and adding notes the implementation added into backend - added service index in backend.proto for image occlusion request - created image_occlusion.proto with required message and service - implementation in backend for getting image and adding notes, also during editing return imagecloze note and update notes - add notes to selected deck, if no notetype then add image occlusion notetypes - reuse notetype from stock notetypes when not exist * script for generating shapes using canvas api in reviewer - the flash issues fixed by loading image and using image size to draw canvas, also when image get resized, calculate scale using natural width and canvas width to draw shape at right position - limit size of canvas for safari * init image occlusion page in ts and build page with - fabricjs for editing shapes - panzoom for drag and zoom - pickr for color picker - build page using web.rs * implement top toolbar for canvas shapes - undo & redo tools - zoom in, zoom out and zoom fit - group & ungroup - copy & paste - set transparency of shapes - align tools * implement side toolbar for drawing shapes add top toolbar and the side toolbar contains following tools - cursor for selecting shapes - zoom for drag and zoom shapes in mask editor - rectangle for creating it - ellipse for creating it - polygon for creating it using points - shape fill color - question mask color (currently only single color can be added for all shapes) * add maskeditor page for editing mask - add side toolbar and sidebar include toptoolbar - load maskeditor in two mode - for adding note using path to image - for editing note using note id * implement note editor page for adding notes - the note editor page have simple button (B/I/U) and option to toggle html view - option to select deck for adding notes into that deck - option to generate to hide all, guess one & hide one, guess one notes * add image occlusion page add side toolbar, top toolbar, mask editor and note editor - option to switch between mask editor and note editor * implement generates notes and save notes implemention to show toast components for messages * removed pickr & implemented color picker component - remove pickr - implemented using html5 canvas - range input for changing color - another range input for opacity changes - hex and rgba value support * rename methods name & rust unwrap safety - change plural names to singular - create respone message in proto and return response with imagecloze note or error if not found with note id - remove image_occlusion from post handler list - rename service name in mediasrv.py - rename methods name for image occlusion in backend and image_occlusion - update frontend also for update functions' names - handle error in frontend mask-editor.ts, when error getting notes then toast message shown to frontend * extract to function & add comments & remove global - extract function in mask-editor.ts to reduce duplicate - remove unused global from css - add comments to store.ts explaining usage - changes id to noteId in lib.ts - add comments for limitSize, becuase of duplicate implementation * remove image_occlusion notetype - remove from stock notetype, stdmodels - add implementation for notetype to image occlusion - add i18n for errors * update smooth scroll, always show cursor tools - change questionmask to qmask - make selectable for shape true in all tools to simplify edits and draw shapes - update image occlusion in reviewer ts to load image properly * add and get notetype else return errors * fix: not showing occlusion * Use a oneof for ImageClozeNoteResponse Makes it clearer that only one of them can be returned * Don't crash if image filename not provided The second unwrap should be ok, as the input is utf8 * Refactor get_image_cloze_note - fixes crash when note doesn't exist - Ok(None) case was not covered - decouples business logic from native error->proto error conversion - no need for original copy - field[x] is more idiomatic than field.get(x).unwrap() - don't need mutable access to fields * Fix crash if image file unreadable + Use our read_file helper for better error context * Add metadata() helper * Fix crash if file metadata can't be read * remove color picker, qmask and shape color - remove strings from ftl - remove color picker component - remove from cloze generation - remove icons for two buttons - use constant color for shapes * update color in reviewer and ftl strings * fix shape position in canvas & add border to shape - rename mask to inactive shape and active shape color - border witdth and border color - change decimal point deserializing string and toFixed(2) - add thin border in mask editor, may be image background was transparent * fix shape position in canvas after modified - do not draw fixed ratio shapes by turn of uniformScaling - fix rectangle width,height - fix ellipse rx,ry,width,height - fix polygon postion and points - draw outside of canvas also * fix border width and color in reviewer canvas - rename variable * refactor cloze div generate and remove angle * fix origin when drawn outside of canvas from right * fix shape at boundry & not include rx,ry rectangle - move shapes at boundry when pointer is outside of canvas - include rx, ry for ellipse only - include points for polygon only * fix lint errors & update image size in editor canvas based on height and width * remove unsupported layerX & layerX for touchscreen - fix shapes at edges * implemented undo redo with canvas state - implemented undo redo using fabric canvas events - polygon is special case and implemented only added and modified event - rectangle and ellipse have object:added, object:modified and object:removed case - change id to undo and redo * remove background image from canvas and used css to put image tag below canvas editor - set image width and height after adding image * fix for polygon points, add br in cloze strings, & toogle masks button - fix shapes at edges - toggle masks button to show/hide masks - hide clozes string, it contains <br> - set height for div container (used 'relative' in css) * refactor top toolbar, add space and border radius - rename cursor tools - add left and right border * fix undo after undo happen, use transparent color in draw mode
2023-03-29 04:33:19 +02:00
# ImageOcclusionService
"get_image_for_occlusion",
"add_image_occlusion_note",
"get_image_occlusion_note",
Feature image occlusion (#2367) * add note types with occlusions and image fields * generate image occlusion cloze div data - generate div element with data-* atrributes for canvas shape generate for reviewer * getting image data & deck id and adding notes the implementation added into backend - added service index in backend.proto for image occlusion request - created image_occlusion.proto with required message and service - implementation in backend for getting image and adding notes, also during editing return imagecloze note and update notes - add notes to selected deck, if no notetype then add image occlusion notetypes - reuse notetype from stock notetypes when not exist * script for generating shapes using canvas api in reviewer - the flash issues fixed by loading image and using image size to draw canvas, also when image get resized, calculate scale using natural width and canvas width to draw shape at right position - limit size of canvas for safari * init image occlusion page in ts and build page with - fabricjs for editing shapes - panzoom for drag and zoom - pickr for color picker - build page using web.rs * implement top toolbar for canvas shapes - undo & redo tools - zoom in, zoom out and zoom fit - group & ungroup - copy & paste - set transparency of shapes - align tools * implement side toolbar for drawing shapes add top toolbar and the side toolbar contains following tools - cursor for selecting shapes - zoom for drag and zoom shapes in mask editor - rectangle for creating it - ellipse for creating it - polygon for creating it using points - shape fill color - question mask color (currently only single color can be added for all shapes) * add maskeditor page for editing mask - add side toolbar and sidebar include toptoolbar - load maskeditor in two mode - for adding note using path to image - for editing note using note id * implement note editor page for adding notes - the note editor page have simple button (B/I/U) and option to toggle html view - option to select deck for adding notes into that deck - option to generate to hide all, guess one & hide one, guess one notes * add image occlusion page add side toolbar, top toolbar, mask editor and note editor - option to switch between mask editor and note editor * implement generates notes and save notes implemention to show toast components for messages * removed pickr & implemented color picker component - remove pickr - implemented using html5 canvas - range input for changing color - another range input for opacity changes - hex and rgba value support * rename methods name & rust unwrap safety - change plural names to singular - create respone message in proto and return response with imagecloze note or error if not found with note id - remove image_occlusion from post handler list - rename service name in mediasrv.py - rename methods name for image occlusion in backend and image_occlusion - update frontend also for update functions' names - handle error in frontend mask-editor.ts, when error getting notes then toast message shown to frontend * extract to function & add comments & remove global - extract function in mask-editor.ts to reduce duplicate - remove unused global from css - add comments to store.ts explaining usage - changes id to noteId in lib.ts - add comments for limitSize, becuase of duplicate implementation * remove image_occlusion notetype - remove from stock notetype, stdmodels - add implementation for notetype to image occlusion - add i18n for errors * update smooth scroll, always show cursor tools - change questionmask to qmask - make selectable for shape true in all tools to simplify edits and draw shapes - update image occlusion in reviewer ts to load image properly * add and get notetype else return errors * fix: not showing occlusion * Use a oneof for ImageClozeNoteResponse Makes it clearer that only one of them can be returned * Don't crash if image filename not provided The second unwrap should be ok, as the input is utf8 * Refactor get_image_cloze_note - fixes crash when note doesn't exist - Ok(None) case was not covered - decouples business logic from native error->proto error conversion - no need for original copy - field[x] is more idiomatic than field.get(x).unwrap() - don't need mutable access to fields * Fix crash if image file unreadable + Use our read_file helper for better error context * Add metadata() helper * Fix crash if file metadata can't be read * remove color picker, qmask and shape color - remove strings from ftl - remove color picker component - remove from cloze generation - remove icons for two buttons - use constant color for shapes * update color in reviewer and ftl strings * fix shape position in canvas & add border to shape - rename mask to inactive shape and active shape color - border witdth and border color - change decimal point deserializing string and toFixed(2) - add thin border in mask editor, may be image background was transparent * fix shape position in canvas after modified - do not draw fixed ratio shapes by turn of uniformScaling - fix rectangle width,height - fix ellipse rx,ry,width,height - fix polygon postion and points - draw outside of canvas also * fix border width and color in reviewer canvas - rename variable * refactor cloze div generate and remove angle * fix origin when drawn outside of canvas from right * fix shape at boundry & not include rx,ry rectangle - move shapes at boundry when pointer is outside of canvas - include rx, ry for ellipse only - include points for polygon only * fix lint errors & update image size in editor canvas based on height and width * remove unsupported layerX & layerX for touchscreen - fix shapes at edges * implemented undo redo with canvas state - implemented undo redo using fabric canvas events - polygon is special case and implemented only added and modified event - rectangle and ellipse have object:added, object:modified and object:removed case - change id to undo and redo * remove background image from canvas and used css to put image tag below canvas editor - set image width and height after adding image * fix for polygon points, add br in cloze strings, & toogle masks button - fix shapes at edges - toggle masks button to show/hide masks - hide clozes string, it contains <br> - set height for div container (used 'relative' in css) * refactor top toolbar, add space and border radius - rename cursor tools - add left and right border * fix undo after undo happen, use transparent color in draw mode
2023-03-29 04:33:19 +02:00
"update_image_occlusion_note",
"get_image_occlusion_fields",
# SchedulerService
"compute_fsrs_weights",
"compute_optimal_retention",
"set_wants_abort",
"evaluate_weights",
2023-09-17 04:58:13 +02:00
"get_optimal_retention_parameters",
]
def raw_backend_request(endpoint: str) -> Callable[[], bytes]:
# check for key at startup
from anki._backend import RustBackend
assert hasattr(RustBackend, f"{endpoint}_raw")
return lambda: getattr(aqt.mw.col._backend, f"{endpoint}_raw")(request.data)
# all methods in here require a collection
2021-01-22 14:37:24 +01:00
post_handlers = {
stringcase.camelcase(handler.__name__): handler for handler in post_handler_list
} | {
stringcase.camelcase(handler): raw_backend_request(handler)
for handler in exposed_backend_list
2021-01-22 14:37:24 +01:00
}
def _extract_collection_post_request(path: str) -> DynamicRequest | NotFound:
if not aqt.mw.col:
return NotFound(message=f"collection not open, ignore request for {path}")
if handler := post_handlers.get(path):
# convert bytes/None into response
def wrapped() -> Response:
try:
if data := handler():
response = flask.make_response(data)
response.headers["Content-Type"] = "application/binary"
else:
response = flask.make_response("", HTTPStatus.NO_CONTENT)
except Exception as exc:
print(traceback.format_exc())
response = flask.make_response(
str(exc), HTTPStatus.INTERNAL_SERVER_ERROR
)
return response
return wrapped
else:
return NotFound(message=f"{path} not found")
2021-01-22 14:37:24 +01:00
def _check_dynamic_request_permissions():
if request.method == "GET":
return
context = _extract_page_context()
def warn() -> None:
show_warning(
"Unexpected API access. Please report this message on the Anki forums."
)
# check content type header to ensure this isn't an opaque request from another origin
if request.headers["Content-type"] != "application/binary":
aqt.mw.taskman.run_on_main(warn)
abort(403)
if (
context == PageContext.NON_LEGACY_PAGE
or context == PageContext.EDITOR
or context == PageContext.ADDON_PAGE
):
pass
elif context == PageContext.REVIEWER and request.path in (
"/_anki/getSchedulingStatesWithContext",
"/_anki/setSchedulingStates",
):
# reviewer is only allowed to access custom study methods
pass
else:
# other legacy pages may contain third-party JS, so we do not
# allow them to access our API
aqt.mw.taskman.run_on_main(warn)
abort(403)
def _handle_dynamic_request(req: DynamicRequest) -> Response:
_check_dynamic_request_permissions()
try:
return req()
except Exception as e:
return flask.make_response(str(e), HTTPStatus.INTERNAL_SERVER_ERROR)
def legacy_page_data() -> Response:
id = int(request.args["id"])
if html := aqt.mw.mediaServer.get_page_html(id):
return Response(html, mimetype="text/html")
else:
return flask.make_response("page not found", HTTPStatus.NOT_FOUND)
def _extract_page_context() -> PageContext:
"Get context based on referer header."
from urllib.parse import parse_qs, urlparse
referer = urlparse(request.headers.get("Referer", ""))
if referer.path.startswith("/_anki/pages/"):
return PageContext.NON_LEGACY_PAGE
elif referer.path == "/_anki/legacyPageData":
query_params = parse_qs(referer.query)
id = int(query_params.get("id", [None])[0])
return aqt.mw.mediaServer.get_page_context(id)
else:
return PageContext.UNKNOWN
# this currently only handles a single method; in the future, idempotent
# requests like i18nResources should probably be moved here
def _extract_dynamic_get_request(path: str) -> DynamicRequest | None:
if path == "legacyPageData":
return legacy_page_data
else:
return None