Coverage for plugin/util.py: 91.5%

39 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-28 02:31 +0000

1# Copyright 2016-2026 Alex Yatskov 

2# 

3# This program is free software: you can redistribute it and/or modify 

4# it under the terms of the GNU General Public License as published by 

5# the Free Software Foundation, either version 3 of the License, or 

6# (at your option) any later version. 

7# 

8# This program is distributed in the hope that it will be useful, 

9# but WITHOUT ANY WARRANTY; without even the implied warranty of 

10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

11# GNU General Public License for more details. 

12# 

13# You should have received a copy of the GNU General Public License 

14# along with this program. If not, see <http://www.gnu.org/licenses/>. 

15 

16import functools 

17import os 

18 

19import aqt 

20 

21from . import compat 

22 

23 

24def api(): 

25 """Declare a legacy action; the signature defines its historical parameter binding.""" 

26 def decorator(func): 

27 @functools.wraps(func) 

28 def declaration(self, *args, **kwargs): 

29 try: 

30 func(self, *args, **kwargs) 

31 except TypeError as error: 

32 raise compat.binding_error(error, func) from None 

33 raise NotImplementedError('Legacy actions execute through AnkiConnect.handler_async.') 

34 declaration.api = True 

35 return declaration 

36 

37 return decorator 

38 

39 

40DEFAULT_CONFIG = { 

41 'apiKey': None, 

42 'apiLogPath': None, 

43 'apiPollInterval': 25, 

44 'apiVersion': 6, 

45 'webBacklog': 5, 

46 'webBindAddress': os.getenv('ANKICONNECT_BIND_ADDRESS', '127.0.0.1'), 

47 'webBindPort': 8765, 

48 'webCorsOrigin': os.getenv('ANKICONNECT_CORS_ORIGIN', None), 

49 'webCorsOriginList': ['http://localhost'], 

50 'ignoreOriginList': [], 

51 'webTimeout': 10000, 

52} 

53 

54def setting(key): 

55 if key not in DEFAULT_CONFIG: 55 ↛ 56line 55 didn't jump to line 56 because the condition on line 55 was never true

56 raise Exception('setting {} not found'.format(key)) 

57 config = aqt.mw.addonManager.getConfig(__name__) or {} 

58 return config.get(key, DEFAULT_CONFIG[key]) 

59 

60 

61def download(url, limit): 

62 """Fetch media with Anki's HTTP client, returning at most limit + 1 bytes.""" 

63 from .protocol import ApiError 

64 with compat.http_client() as client: 

65 client.timeout = setting('webTimeout') / 1000 

66 try: 

67 response = client.get(url) 

68 except Exception as error: 

69 raise ApiError('ioError', str(error)) from error 

70 with response: 

71 if response.status_code != 200: 

72 raise ApiError('ioError', '{} download failed with return code {}'.format(url, response.status_code)) 

73 data = bytearray() 

74 for chunk in response.iter_content(65536): 

75 data += chunk 

76 if len(data) > limit: 76 ↛ 77line 76 didn't jump to line 77 because the condition on line 76 was never true

77 break 

78 return bytes(data)