1
1
"""Sphinx extension module."""
2
2
3
3
import logging
4
+ from datetime import datetime
5
+ from typing import Union , Tuple
4
6
5
7
try :
6
8
from docutils import nodes
7
9
from docutils .parsers .rst import Directive , directives
8
10
from sphinx .application import Sphinx
9
11
from sphinx .domains import Domain
10
12
from sphinx .environment import BuildEnvironment
11
-
12
- logger = logging .getLogger (__name__ )
13
13
except ModuleNotFoundError as err :
14
- logger = logging .getLogger (__name__ )
15
-
16
14
msg = "To use it, install with Sphinx."
17
15
logging .error (msg )
18
16
raise err
19
17
20
18
from oembedpy import __version__
21
19
from oembedpy .application import Oembed , Workspace
20
+ from oembedpy .types import Content
21
+ from sphinx .util .logging import getLogger
22
+
23
+ logger = getLogger (__name__ )
22
24
23
25
24
26
class OembedDomain (Domain ):
@@ -34,12 +36,34 @@ def __init__(self, env: BuildEnvironment):
34
36
)
35
37
self ._client .init ()
36
38
39
+ @property
40
+ def caches (self ) -> dict [Tuple [str , Union [int , None ], Union [int , None ]], Content ]:
41
+ return self .data .setdefault ("caches" , {})
42
+
37
43
def process_doc (
38
44
self , env : BuildEnvironment , docname : str , document : nodes .document
39
45
):
40
46
for node in document .findall (oembed ):
41
47
params = node ["params" ]
42
- node ["content" ] = self ._client .fetch (** params )
48
+ cache_key = (params ["url" ], params ["max_width" ], params ["max_height" ])
49
+ logger .debug (f"Target content for { cache_key } " )
50
+ if self .has_cache (cache_key ):
51
+ logger .debug ("Cache is found. Use this." )
52
+ content = self .caches [cache_key ]
53
+ else :
54
+ logger .debug ("Cache is not exists. Fetching content from service." )
55
+ content = self ._client .fetch (** node ["params" ])
56
+ self .caches [cache_key ] = content
57
+ node ["content" ] = content
58
+
59
+ def has_cache (self , key : Tuple [str , Union [int , None ], Union [int , None ]]) -> bool :
60
+ now = int (datetime .now ().timestamp ())
61
+ if key not in self .caches :
62
+ return False
63
+ content : Content = self .caches [key ]
64
+ if "cache_age" not in content ._extra :
65
+ return True
66
+ return now < content ._extra ["cache_age" ]
43
67
44
68
45
69
class oembed (nodes .General , nodes .Element ): # noqa: D101,E501
0 commit comments