File: downloader.py

package info (click to toggle)
anki 2.1.15%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,240 kB
  • sloc: python: 27,663; javascript: 589; xml: 67; sh: 51; makefile: 45
file content (73 lines) | stat: -rw-r--r-- 2,273 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# Copyright: Ankitects Pty Ltd and contributors
# -*- coding: utf-8 -*-
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html

import time, re
from aqt.qt import *
from anki.sync import AnkiRequestsClient
from anki.hooks import addHook, remHook
import aqt
from anki.lang import _

def download(mw, code):
    "Download addon from AnkiWeb. Caller must start & stop progress diag."
    # create downloading thread
    thread = Downloader(code)
    done = False
    def onRecv():
        if done:
            return
        mw.progress.update(label="%dKB downloaded" % (thread.recvTotal/1024))
    thread.recv.connect(onRecv)
    thread.start()
    while not thread.isFinished():
        mw.app.processEvents()
        thread.wait(100)

    # make sure any posted events don't fire after we return
    done = True

    if not thread.error:
        # success
        return thread.data, thread.fname
    else:
        return "error", thread.error

class Downloader(QThread):

    recv = pyqtSignal()

    def __init__(self, code):
        QThread.__init__(self)
        self.code = code
        self.error = None

    def run(self):
        # setup progress handler
        self.byteUpdate = time.time()
        self.recvTotal = 0
        def recvEvent(bytes):
            self.recvTotal += bytes
            self.recv.emit()
        addHook("httpRecv", recvEvent)
        client = AnkiRequestsClient()
        try:
            resp = client.get(
                aqt.appShared + "download/%s?v=2.1" % self.code)
            if resp.status_code == 200:
                data = client.streamContent(resp)
            elif resp.status_code in (403,404):
                self.error = _("Invalid code, or add-on not available for your version of Anki.")
                return
            else:
                self.error = _("Unexpected response code: %s" % resp.status_code)
                return
        except Exception as e:
            self.error = _("Please check your internet connection.") + "\n\n" + str(e)
            return
        finally:
            remHook("httpRecv", recvEvent)

        self.fname = re.match("attachment; filename=(.+)",
                              resp.headers['content-disposition']).group(1)
        self.data = data