shade-plugins-notion 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- shade_plugins_notion/__init__.py +534 -0
- shade_plugins_notion/_cliente.py +289 -0
- shade_plugins_notion/erros.py +53 -0
- shade_plugins_notion-0.1.0.dist-info/METADATA +114 -0
- shade_plugins_notion-0.1.0.dist-info/RECORD +8 -0
- shade_plugins_notion-0.1.0.dist-info/WHEEL +4 -0
- shade_plugins_notion-0.1.0.dist-info/entry_points.txt +2 -0
- shade_plugins_notion-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
"""O plugin ``notion``: consultar uma base, criar uma página (sem duplicar) e atualizar uma página
|
|
2
|
+
no Notion, sob o contrato de plugin do shade-sdk, com o token OAuth da conexão da plataforma.
|
|
3
|
+
|
|
4
|
+
```toml
|
|
5
|
+
[hosts]
|
|
6
|
+
permitidos = ["api.notion.com"]
|
|
7
|
+
|
|
8
|
+
[conexoes]
|
|
9
|
+
nomes = ["notion"]
|
|
10
|
+
|
|
11
|
+
[plugins]
|
|
12
|
+
notion = "0.1.0"
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
import shade_plugins_notion as notion
|
|
17
|
+
|
|
18
|
+
pendentes = notion.consultar_base(BASE, filtro={"property": "Status", "select": {"equals": "Novo"}})
|
|
19
|
+
|
|
20
|
+
with item.efetivar("registrar o pedido"):
|
|
21
|
+
nova = notion.criar_pagina(BASE, {"Nome": notion.titulo(f"Pedido {item['numero']}")})
|
|
22
|
+
notion.atualizar_pagina(nova["id"], {"Observação": notion.texto(item["detalhe"])})
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
- **Conta:** a conexão ``notion`` da plataforma (Conectores). O robô nunca vê a senha nem o refresh
|
|
26
|
+
token: o token de acesso chega sob demanda e é renovado pela plataforma. No laptop, ponha um token
|
|
27
|
+
em ``SHADE_TOKEN_NOTION``. O Notion não tem escopos: a conexão vê o que a pessoa compartilhou com
|
|
28
|
+
ela, e o que não foi compartilhado responde ``404``.
|
|
29
|
+
- **Base:** o id da base (da URL dela). O plugin lê as fontes de dados da base; com mais de uma, passe
|
|
30
|
+
``fonte=`` (o nome ou o id); sem ele, é ``ErroDeNegocio`` (``FonteNaoEscolhida``) com os nomes.
|
|
31
|
+
- **Ler não muda nada:** ``consultar_base`` roda inclusive no ensaio.
|
|
32
|
+
- **Escrever só dentro de** ``item.efetivar()`` (no ensaio não roda). ``criar_pagina`` exige na base a
|
|
33
|
+
coluna de texto ``Chave Shade`` (sem ela, ``ColunaAusente`` antes de qualquer escrita), grava nela a
|
|
34
|
+
chave do item e consulta por ela antes de criar. Depois de despachado, o pedido de criação nunca é
|
|
35
|
+
repetido: sem confirmação, o plugin confere no Notion e, sem achar a página, o erro é
|
|
36
|
+
``NotionIncerto``. ``atualizar_pagina`` é idempotente por natureza: refazer grava os mesmos valores.
|
|
37
|
+
- **Propriedades** vão no formato da API do Notion, montadas como objeto e serializadas por
|
|
38
|
+
``json.dumps``; ``titulo()`` e ``texto()`` montam as de texto, com os limites do Notion.
|
|
39
|
+
- **Prazo:** ``timeout=`` (30 s) vale para a chamada inteira, retentativas incluídas.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
from __future__ import annotations
|
|
43
|
+
|
|
44
|
+
import json
|
|
45
|
+
import re
|
|
46
|
+
from collections.abc import Callable, Iterator, Mapping
|
|
47
|
+
from typing import Any
|
|
48
|
+
|
|
49
|
+
from shade_sdk import http
|
|
50
|
+
from shade_sdk.plugins import Plugin
|
|
51
|
+
|
|
52
|
+
from shade_plugins_notion import _cliente
|
|
53
|
+
from shade_plugins_notion._cliente import CONEXAO, NOTION, VERSAO_DA_API, Cliente, Prazo
|
|
54
|
+
from shade_plugins_notion.erros import (
|
|
55
|
+
ColunaAusente,
|
|
56
|
+
ErroDoNotion,
|
|
57
|
+
FonteNaoEscolhida,
|
|
58
|
+
NaoEncontrado,
|
|
59
|
+
NotionIncerto,
|
|
60
|
+
NotionNaoSaiu,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
__version__ = "0.1.0"
|
|
64
|
+
|
|
65
|
+
#: A coluna de texto que leva a chave do item: o que faz o refazer achar a página.
|
|
66
|
+
COLUNA_DA_CHAVE = "Chave Shade"
|
|
67
|
+
#: Quantas páginas a consulta devolve, no máximo, e quantas o Notion dá por pedido (o teto dele é
|
|
68
|
+
#: 100, e a resposta pode trazer menos que isso mesmo sem ter acabado).
|
|
69
|
+
LIMITE_MAX = 5_000
|
|
70
|
+
POR_PEDIDO = 100
|
|
71
|
+
PEDIDOS_MAX = 60
|
|
72
|
+
PROPRIEDADES_MAX = 100
|
|
73
|
+
#: Os limites do Notion para um valor de texto: partes de até 2.000 caracteres (em UTF-16), até 100.
|
|
74
|
+
PARTE_MAX = 2_000
|
|
75
|
+
PARTES_MAX = 100
|
|
76
|
+
|
|
77
|
+
_ID = re.compile(
|
|
78
|
+
r"^[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}$"
|
|
79
|
+
)
|
|
80
|
+
_CURSOR = re.compile(r"^[A-Za-z0-9_\-=+/.:]{1,2000}$")
|
|
81
|
+
_CHAVE_DO_ITEM = re.compile(r"^[A-Za-z0-9_\-]{1,128}$")
|
|
82
|
+
|
|
83
|
+
PLUGIN = Plugin(
|
|
84
|
+
"notion",
|
|
85
|
+
__version__,
|
|
86
|
+
shade_sdk=">=0.22.3,<0.23",
|
|
87
|
+
dono="Equipe de integrações da ShadeOne",
|
|
88
|
+
hosts=[NOTION],
|
|
89
|
+
conexoes=[CONEXAO],
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
__all__ = [
|
|
93
|
+
"COLUNA_DA_CHAVE",
|
|
94
|
+
"PLUGIN",
|
|
95
|
+
"VERSAO_DA_API",
|
|
96
|
+
"ColunaAusente",
|
|
97
|
+
"ErroDoNotion",
|
|
98
|
+
"FonteNaoEscolhida",
|
|
99
|
+
"NaoEncontrado",
|
|
100
|
+
"NotionIncerto",
|
|
101
|
+
"NotionNaoSaiu",
|
|
102
|
+
"atualizar_pagina",
|
|
103
|
+
"consultar_base",
|
|
104
|
+
"criar_pagina",
|
|
105
|
+
"texto",
|
|
106
|
+
"texto_de",
|
|
107
|
+
"titulo",
|
|
108
|
+
]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
# ── os valores de texto ──────────────────────────────────────────────────────────────────
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _partes(valor: Any, nome: str) -> list[dict[str, Any]]:
|
|
115
|
+
"""O texto em partes de ``rich_text``: cada parte é ``text.content``, literal (um ``**`` ou um
|
|
116
|
+
link do dado vai como texto)."""
|
|
117
|
+
if not isinstance(valor, str):
|
|
118
|
+
raise ValueError(f"{nome} é um texto")
|
|
119
|
+
if "\x00" in valor:
|
|
120
|
+
raise ValueError(f"{nome} não leva o caractere nulo")
|
|
121
|
+
partes: list[str] = []
|
|
122
|
+
atual: list[str] = []
|
|
123
|
+
unidades = 0
|
|
124
|
+
for caractere in valor:
|
|
125
|
+
tamanho = 2 if ord(caractere) > 0xFFFF else 1
|
|
126
|
+
if unidades + tamanho > PARTE_MAX:
|
|
127
|
+
partes.append("".join(atual))
|
|
128
|
+
atual, unidades = [], 0
|
|
129
|
+
atual.append(caractere)
|
|
130
|
+
unidades += tamanho
|
|
131
|
+
if atual:
|
|
132
|
+
partes.append("".join(atual))
|
|
133
|
+
if len(partes) > PARTES_MAX:
|
|
134
|
+
raise ValueError(f"{nome} passa do limite do Notion ({PARTES_MAX} partes de {PARTE_MAX})")
|
|
135
|
+
return [{"type": "text", "text": {"content": parte}} for parte in partes]
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def titulo(valor: str) -> dict[str, Any]:
|
|
139
|
+
"""O valor de uma propriedade de título: ``{"Nome": notion.titulo("Pedido 12")}``."""
|
|
140
|
+
return {"title": _partes(valor, "titulo")}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def texto(valor: str) -> dict[str, Any]:
|
|
144
|
+
"""O valor de uma propriedade de texto: ``{"Observação": notion.texto("conferido")}``."""
|
|
145
|
+
return {"rich_text": _partes(valor, "texto")}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def texto_de(propriedade: Any) -> str:
|
|
149
|
+
"""O texto de uma propriedade de título ou de texto lida do Notion (``""`` se não for uma)."""
|
|
150
|
+
if not isinstance(propriedade, Mapping):
|
|
151
|
+
return ""
|
|
152
|
+
partes = propriedade.get("title") or propriedade.get("rich_text") or []
|
|
153
|
+
if not isinstance(partes, list):
|
|
154
|
+
return ""
|
|
155
|
+
return "".join(str(p.get("plain_text", "")) for p in partes if isinstance(p, Mapping))
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# ── validação ────────────────────────────────────────────────────────────────────────────
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _porta(porta: Any) -> int | None:
|
|
162
|
+
if porta is not None and (
|
|
163
|
+
not isinstance(porta, int) or isinstance(porta, bool) or not 0 < porta < 65536
|
|
164
|
+
):
|
|
165
|
+
raise ValueError(f"porta é um número de 1 a 65535, não {porta!r}")
|
|
166
|
+
return porta
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _limite(valor: Any) -> int:
|
|
170
|
+
if not isinstance(valor, int) or isinstance(valor, bool) or not 0 < valor <= LIMITE_MAX:
|
|
171
|
+
raise ValueError(f"limite é um número de 1 a {LIMITE_MAX}")
|
|
172
|
+
return valor
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _id(valor: Any, nome: str) -> str:
|
|
176
|
+
if not isinstance(valor, str) or not _ID.fullmatch(valor):
|
|
177
|
+
raise ValueError(f"{nome} é o id do Notion (32 dígitos hexadecimais, da URL)")
|
|
178
|
+
return valor
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _fonte(valor: Any) -> str | None:
|
|
182
|
+
if valor is None:
|
|
183
|
+
return None
|
|
184
|
+
if not isinstance(valor, str) or not valor.strip() or len(valor) > 200:
|
|
185
|
+
raise ValueError("fonte é o nome ou o id de uma fonte de dados da base")
|
|
186
|
+
return valor.strip()
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _serializavel(valor: Any, nome: str) -> None:
|
|
190
|
+
try:
|
|
191
|
+
json.dumps(valor, allow_nan=False)
|
|
192
|
+
except (TypeError, ValueError):
|
|
193
|
+
raise ValueError(f"{nome} tem um valor que não vira JSON") from None
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _filtro(valor: Any) -> dict[str, Any] | None:
|
|
197
|
+
if valor is None:
|
|
198
|
+
return None
|
|
199
|
+
if not isinstance(valor, Mapping):
|
|
200
|
+
raise ValueError("filtro é o filtro da API do Notion, um dicionário")
|
|
201
|
+
saida = dict(valor)
|
|
202
|
+
_serializavel(saida, "filtro")
|
|
203
|
+
return saida
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _propriedades(valor: Any) -> dict[str, Any]:
|
|
207
|
+
"""As propriedades do robô. A coluna da chave é do plugin: o robô que a sobrescreve faria o
|
|
208
|
+
refazer não achar a página."""
|
|
209
|
+
if not isinstance(valor, Mapping) or not 0 < len(valor) <= PROPRIEDADES_MAX:
|
|
210
|
+
raise ValueError(f"propriedades é um dicionário de 1 a {PROPRIEDADES_MAX} propriedades")
|
|
211
|
+
saida: dict[str, Any] = {}
|
|
212
|
+
for nome, conteudo in valor.items():
|
|
213
|
+
if not isinstance(nome, str) or not nome.strip():
|
|
214
|
+
raise ValueError("o nome de uma propriedade é um texto não vazio")
|
|
215
|
+
if nome.strip().casefold() == COLUNA_DA_CHAVE.casefold():
|
|
216
|
+
raise ValueError(
|
|
217
|
+
f"{COLUNA_DA_CHAVE} é preenchida pelo plugin: não passe em propriedades"
|
|
218
|
+
)
|
|
219
|
+
if not isinstance(conteudo, Mapping):
|
|
220
|
+
raise ValueError(
|
|
221
|
+
f"o valor de {nome!r} é o da API do Notion, um dicionário "
|
|
222
|
+
'(notion.titulo("x"), notion.texto("x"), {"number": 1})'
|
|
223
|
+
)
|
|
224
|
+
saida[nome] = dict(conteudo)
|
|
225
|
+
_serializavel(saida, "propriedades")
|
|
226
|
+
return saida
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _chave_do_item(chamada: Any) -> str:
|
|
230
|
+
chave = chamada.idempotencia
|
|
231
|
+
if not isinstance(chave, str) or not _CHAVE_DO_ITEM.fullmatch(chave):
|
|
232
|
+
raise ValueError("a chave de idempotência do item não serve para a coluna da chave")
|
|
233
|
+
return chave
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
# ── a base ───────────────────────────────────────────────────────────────────────────────
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _cliente_da_chamada(chamada: Any, porta: Any) -> Cliente:
|
|
240
|
+
return Cliente(chamada=chamada, prazo=Prazo(chamada.timeout), porta=_porta(porta))
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _lendo(operacao: str, funcao: Callable[[], Any]) -> Any:
|
|
244
|
+
"""A falha de rede no meio da leitura vira ``ErroDoNotion``."""
|
|
245
|
+
try:
|
|
246
|
+
return funcao()
|
|
247
|
+
except ErroDoNotion:
|
|
248
|
+
raise
|
|
249
|
+
except OSError as exc:
|
|
250
|
+
raise _cliente.falha_de_leitura(operacao, exc) from exc
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _fonte_da_base(
|
|
254
|
+
cliente: Cliente, operacao: str, base: str, fonte: str | None, chave: str | None = None
|
|
255
|
+
) -> str:
|
|
256
|
+
"""O id da fonte de dados da base (a consulta e a página nova falam com ela). Com mais de uma e
|
|
257
|
+
sem ``fonte=``, ``FonteNaoEscolhida``."""
|
|
258
|
+
resposta = cliente.pedir("GET", f"/v1/databases/{base}", idempotencia=chave)
|
|
259
|
+
dados = _cliente.checar_leitura(operacao, resposta)
|
|
260
|
+
fontes = [
|
|
261
|
+
f
|
|
262
|
+
for f in dados.get("data_sources") or []
|
|
263
|
+
if isinstance(f, dict) and isinstance(f.get("id"), str) and _ID.fullmatch(f["id"])
|
|
264
|
+
]
|
|
265
|
+
nomes = ", ".join(sorted(str(f.get("name") or f["id"]) for f in fontes))
|
|
266
|
+
if not fontes:
|
|
267
|
+
raise FonteNaoEscolhida("Notion: a base não tem nenhuma fonte de dados que a conexão veja")
|
|
268
|
+
if fonte is None:
|
|
269
|
+
if len(fontes) > 1:
|
|
270
|
+
raise FonteNaoEscolhida(
|
|
271
|
+
f"Notion: a base tem mais de uma fonte de dados ({nomes}); passe fonte= com o nome "
|
|
272
|
+
"de uma delas"
|
|
273
|
+
)
|
|
274
|
+
return fontes[0]["id"]
|
|
275
|
+
pedido = fonte.casefold()
|
|
276
|
+
achadas = [
|
|
277
|
+
f for f in fontes if pedido in (str(f.get("name", "")).casefold(), f["id"].casefold())
|
|
278
|
+
]
|
|
279
|
+
if len(achadas) != 1:
|
|
280
|
+
raise FonteNaoEscolhida(f"Notion: a fonte {fonte!r} não é uma das da base ({nomes})")
|
|
281
|
+
return achadas[0]["id"]
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _exigir_a_coluna(cliente: Cliente, operacao: str, fonte_id: str, chave: str) -> None:
|
|
285
|
+
"""Sem a coluna de texto da chave, a página nova não teria como ser achada no refazer: a recusa
|
|
286
|
+
vem antes de qualquer escrita."""
|
|
287
|
+
resposta = cliente.pedir("GET", f"/v1/data_sources/{fonte_id}", idempotencia=chave)
|
|
288
|
+
dados = _cliente.checar_leitura(operacao, resposta)
|
|
289
|
+
colunas = dados.get("properties")
|
|
290
|
+
coluna = colunas.get(COLUNA_DA_CHAVE) if isinstance(colunas, dict) else None
|
|
291
|
+
if not isinstance(coluna, dict):
|
|
292
|
+
raise ColunaAusente(f"A base não tem a coluna '{COLUNA_DA_CHAVE}'")
|
|
293
|
+
if coluna.get("type") != "rich_text":
|
|
294
|
+
raise ColunaAusente(
|
|
295
|
+
f"A coluna '{COLUNA_DA_CHAVE}' da base não é de texto (é {coluna.get('type')!r})"
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
# ── consultar ────────────────────────────────────────────────────────────────────────────
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _paginas_da_consulta(
|
|
303
|
+
cliente: Cliente,
|
|
304
|
+
operacao: str,
|
|
305
|
+
fonte_id: str,
|
|
306
|
+
filtro: Mapping[str, Any] | None,
|
|
307
|
+
limite: int,
|
|
308
|
+
chave: str | None = None,
|
|
309
|
+
) -> Iterator[dict[str, Any]]:
|
|
310
|
+
"""As páginas da consulta, seguindo o ``next_cursor``. O Notion pode devolver menos que o pedido
|
|
311
|
+
(até nenhuma) sem ter acabado: quem decide é o ``has_more``. O que não dá para ler até o fim é
|
|
312
|
+
erro, nunca um resultado cortado em silêncio: "não achei" aqui decide se a página é criada."""
|
|
313
|
+
devolvidas = 0
|
|
314
|
+
cursor = ""
|
|
315
|
+
for _ in range(PEDIDOS_MAX):
|
|
316
|
+
corpo: dict[str, Any] = {"page_size": min(POR_PEDIDO, limite - devolvidas)}
|
|
317
|
+
if filtro is not None:
|
|
318
|
+
corpo["filter"] = filtro
|
|
319
|
+
if cursor:
|
|
320
|
+
corpo["start_cursor"] = cursor
|
|
321
|
+
resposta = cliente.pedir(
|
|
322
|
+
"POST", f"/v1/data_sources/{fonte_id}/query", corpo=corpo, idempotencia=chave
|
|
323
|
+
)
|
|
324
|
+
dados = _cliente.checar_leitura(operacao, resposta)
|
|
325
|
+
for pagina in dados.get("results") or []:
|
|
326
|
+
# Numa wiki, a consulta também devolve fontes de dados: só a página interessa.
|
|
327
|
+
if isinstance(pagina, dict) and pagina.get("object") == "page":
|
|
328
|
+
yield pagina
|
|
329
|
+
devolvidas += 1
|
|
330
|
+
if devolvidas >= limite:
|
|
331
|
+
return
|
|
332
|
+
if dados.get("has_more") is not True:
|
|
333
|
+
return
|
|
334
|
+
proximo = dados.get("next_cursor")
|
|
335
|
+
if not isinstance(proximo, str) or not _CURSOR.fullmatch(proximo) or proximo == cursor:
|
|
336
|
+
raise ErroDoNotion(f"Notion {operacao}: a resposta diz que há mais e não dá o cursor")
|
|
337
|
+
cursor = proximo
|
|
338
|
+
raise ErroDoNotion(f"Notion {operacao}: a consulta passou de {PEDIDOS_MAX} pedidos")
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _resumo(pagina: Mapping[str, Any]) -> dict[str, Any]:
|
|
342
|
+
propriedades = pagina.get("properties")
|
|
343
|
+
return {
|
|
344
|
+
"id": str(pagina.get("id", "")),
|
|
345
|
+
"url": str(pagina.get("url", "")),
|
|
346
|
+
"propriedades": propriedades if isinstance(propriedades, dict) else {},
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
@PLUGIN.operacao
|
|
351
|
+
def consultar_base(
|
|
352
|
+
chamada: Any,
|
|
353
|
+
base: str,
|
|
354
|
+
filtro: Mapping[str, Any] | None = None,
|
|
355
|
+
*,
|
|
356
|
+
limite: int = 100,
|
|
357
|
+
fonte: str | None = None,
|
|
358
|
+
porta: int | None = None,
|
|
359
|
+
) -> list[dict[str, Any]]:
|
|
360
|
+
"""As páginas da ``base`` (o id, da URL dela) que atendem ao ``filtro`` (o da API do Notion), até
|
|
361
|
+
``limite``, seguindo o ``next_cursor``. Cada uma: ``id``, ``url`` e ``propriedades`` (no formato
|
|
362
|
+
do Notion; ``texto_de`` lê as de texto). Nada muda no Notion. ``NaoEncontrado``: a base não existe
|
|
363
|
+
ou não foi compartilhada com a conexão. ``FonteNaoEscolhida``: a base tem mais de uma fonte de
|
|
364
|
+
dados e ``fonte=`` não foi dado."""
|
|
365
|
+
base = _id(base, "base")
|
|
366
|
+
pedido = _filtro(filtro)
|
|
367
|
+
limite = _limite(limite)
|
|
368
|
+
nome = _fonte(fonte)
|
|
369
|
+
cliente = _cliente_da_chamada(chamada, porta)
|
|
370
|
+
|
|
371
|
+
def ler() -> list[dict[str, Any]]:
|
|
372
|
+
fonte_id = _fonte_da_base(cliente, "consultar_base", base, nome)
|
|
373
|
+
paginas = _paginas_da_consulta(cliente, "consultar_base", fonte_id, pedido, limite)
|
|
374
|
+
return [_resumo(p) for p in paginas]
|
|
375
|
+
|
|
376
|
+
return _lendo("consultar_base", ler)
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
# ── criar ────────────────────────────────────────────────────────────────────────────────
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _pagina_com_a_chave(cliente: Cliente, fonte_id: str, chave: str) -> dict[str, Any] | None:
|
|
383
|
+
"""A página da fonte que leva a chave. Confere o valor além de filtrar por ele: quem responde
|
|
384
|
+
sem aplicar o filtro não faz outra página passar por esta."""
|
|
385
|
+
filtro = {"property": COLUNA_DA_CHAVE, "rich_text": {"equals": chave}}
|
|
386
|
+
# Sem teto de resultados: aqui, parar antes do fim seria "não achei" sem ter lido tudo. Quem
|
|
387
|
+
# encerra a leitura sem fim é o teto de pedidos, que é erro.
|
|
388
|
+
teto = PEDIDOS_MAX * POR_PEDIDO + 1
|
|
389
|
+
paginas = _paginas_da_consulta(cliente, "criar_pagina", fonte_id, filtro, teto, chave)
|
|
390
|
+
for pagina in paginas:
|
|
391
|
+
propriedades = pagina.get("properties")
|
|
392
|
+
if isinstance(propriedades, dict) and texto_de(propriedades.get(COLUNA_DA_CHAVE)) == chave:
|
|
393
|
+
return pagina
|
|
394
|
+
return None
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _resultado(pagina: Mapping[str, Any], *, reaproveitada: bool) -> dict[str, Any]:
|
|
398
|
+
return {
|
|
399
|
+
"id": str(pagina.get("id", "")),
|
|
400
|
+
"url": str(pagina.get("url", "")),
|
|
401
|
+
"reaproveitada": reaproveitada,
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _conferir_depois_da_duvida(
|
|
406
|
+
cliente: Cliente, fonte_id: str, chave: str, gravado: str | None
|
|
407
|
+
) -> dict[str, Any] | None:
|
|
408
|
+
"""A página pode ter sido criada: o que a confirma é a chave nela. Esta leitura não prova que
|
|
409
|
+
nada saiu, então nenhuma falha dela vira "não saiu"."""
|
|
410
|
+
try:
|
|
411
|
+
achada = _pagina_com_a_chave(cliente, fonte_id, chave)
|
|
412
|
+
if achada is not None or gravado is None or not _ID.fullmatch(gravado):
|
|
413
|
+
return achada
|
|
414
|
+
# O Notion disse qual página gravou e a consulta ainda não a enxerga.
|
|
415
|
+
resposta = cliente.pedir("GET", f"/v1/pages/{gravado}", idempotencia=chave)
|
|
416
|
+
pagina = _cliente.checar_leitura("criar_pagina", resposta)
|
|
417
|
+
except (ErroDoNotion, OSError, http.NadaSaiu):
|
|
418
|
+
return None
|
|
419
|
+
propriedades = pagina.get("properties")
|
|
420
|
+
if isinstance(propriedades, dict) and texto_de(propriedades.get(COLUNA_DA_CHAVE)) == chave:
|
|
421
|
+
return pagina
|
|
422
|
+
return None
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
@PLUGIN.efeito
|
|
426
|
+
def criar_pagina(
|
|
427
|
+
chamada: Any,
|
|
428
|
+
base: str,
|
|
429
|
+
propriedades: Mapping[str, Any],
|
|
430
|
+
*,
|
|
431
|
+
fonte: str | None = None,
|
|
432
|
+
porta: int | None = None,
|
|
433
|
+
) -> dict[str, Any]:
|
|
434
|
+
"""Cria a página na ``base`` (o id), só dentro de ``item.efetivar()``. ``propriedades`` vão no
|
|
435
|
+
formato do Notion (``{"Nome": notion.titulo("x"), "Valor": {"number": 1}}``). Devolve ``id``,
|
|
436
|
+
``url`` e ``reaproveitada`` (``True`` quando a página desta mesma chamada já existia).
|
|
437
|
+
|
|
438
|
+
Não duplica: a base precisa da coluna de texto ``Chave Shade``, o plugin a preenche com a chave
|
|
439
|
+
do item e consulta por ela antes de criar. ``ColunaAusente``: a base não tem a coluna, e nada foi
|
|
440
|
+
escrito. ``NaoEncontrado``: a base não existe ou não foi compartilhada com a conexão.
|
|
441
|
+
``NotionNaoSaiu``: nada foi criado (o Notion recusou, a rede não abriu, a consulta não foi
|
|
442
|
+
feita). ``NotionIncerto``: o pedido saiu sem confirmação e a página não aparece na consulta; o
|
|
443
|
+
plugin não cria de novo."""
|
|
444
|
+
base = _id(base, "base")
|
|
445
|
+
pedidas = _propriedades(propriedades)
|
|
446
|
+
nome = _fonte(fonte)
|
|
447
|
+
chave = _chave_do_item(chamada)
|
|
448
|
+
cliente = _cliente_da_chamada(chamada, porta)
|
|
449
|
+
try:
|
|
450
|
+
fonte_id = _fonte_da_base(cliente, "criar_pagina", base, nome, chave)
|
|
451
|
+
_exigir_a_coluna(cliente, "criar_pagina", fonte_id, chave)
|
|
452
|
+
existente = _pagina_com_a_chave(cliente, fonte_id, chave)
|
|
453
|
+
except NaoEncontrado:
|
|
454
|
+
raise
|
|
455
|
+
except (ErroDoNotion, OSError) as exc:
|
|
456
|
+
raise NotionNaoSaiu(
|
|
457
|
+
f"Notion criar_pagina: a base não foi lida ({type(exc).__name__}); nada foi criado"
|
|
458
|
+
) from exc
|
|
459
|
+
if existente is not None:
|
|
460
|
+
return _resultado(existente, reaproveitada=True)
|
|
461
|
+
corpo = {
|
|
462
|
+
"parent": {"type": "data_source_id", "data_source_id": fonte_id},
|
|
463
|
+
"properties": {**pedidas, COLUNA_DA_CHAVE: texto(chave)},
|
|
464
|
+
}
|
|
465
|
+
gravado: str | None = None
|
|
466
|
+
try:
|
|
467
|
+
resposta = cliente.pedir(
|
|
468
|
+
"POST", "/v1/pages", corpo=corpo, idempotencia=chave, repetir_depois_do_envio=False
|
|
469
|
+
)
|
|
470
|
+
gravado = _cliente.id_gravado(resposta)
|
|
471
|
+
_cliente.checar_escrita("criar_pagina", resposta)
|
|
472
|
+
dados = resposta.dados()
|
|
473
|
+
if not dados.get("id"):
|
|
474
|
+
raise NotionIncerto(
|
|
475
|
+
"Notion criar_pagina: a resposta não confirma a página", status=resposta.status
|
|
476
|
+
)
|
|
477
|
+
return _resultado(dados, reaproveitada=False)
|
|
478
|
+
except NotionIncerto as incerto:
|
|
479
|
+
duvida: Exception = incerto
|
|
480
|
+
except ErroDoNotion as exc:
|
|
481
|
+
duvida = NotionIncerto(f"Notion criar_pagina: a resposta não confirma a página ({exc})")
|
|
482
|
+
except OSError as exc:
|
|
483
|
+
duvida = _cliente.falha_de_escrita("criar_pagina", exc)
|
|
484
|
+
if isinstance(duvida, NotionNaoSaiu):
|
|
485
|
+
raise duvida from exc
|
|
486
|
+
achada = _conferir_depois_da_duvida(cliente, fonte_id, chave, gravado)
|
|
487
|
+
if achada is None:
|
|
488
|
+
raise duvida
|
|
489
|
+
return _resultado(achada, reaproveitada=True)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
# ── atualizar ────────────────────────────────────────────────────────────────────────────
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
@PLUGIN.efeito
|
|
496
|
+
def atualizar_pagina(
|
|
497
|
+
chamada: Any,
|
|
498
|
+
pagina: str,
|
|
499
|
+
propriedades: Mapping[str, Any],
|
|
500
|
+
*,
|
|
501
|
+
porta: int | None = None,
|
|
502
|
+
) -> dict[str, Any]:
|
|
503
|
+
"""Grava as ``propriedades`` na ``pagina`` (o id), só dentro de ``item.efetivar()``; as outras
|
|
504
|
+
ficam como estão. Devolve ``id`` e ``url``. Refazer grava os mesmos valores: é idempotente por
|
|
505
|
+
natureza, sem consulta antes. ``NotionNaoSaiu``: nada mudou (o Notion recusou, a página não existe
|
|
506
|
+
ou não foi compartilhada, a rede não abriu). ``NotionIncerto``: o pedido saiu sem confirmação;
|
|
507
|
+
refazer é seguro."""
|
|
508
|
+
pagina = _id(pagina, "pagina")
|
|
509
|
+
pedidas = _propriedades(propriedades)
|
|
510
|
+
cliente = _cliente_da_chamada(chamada, porta)
|
|
511
|
+
try:
|
|
512
|
+
# O Notion manda não repetir a escrita que deu 503 (ela pode ter gravado): quem refaz é
|
|
513
|
+
# quem conferiu.
|
|
514
|
+
resposta = cliente.pedir(
|
|
515
|
+
"PATCH",
|
|
516
|
+
f"/v1/pages/{pagina}",
|
|
517
|
+
corpo={"properties": pedidas},
|
|
518
|
+
idempotencia=chamada.idempotencia,
|
|
519
|
+
repetir_depois_do_envio=False,
|
|
520
|
+
)
|
|
521
|
+
except OSError as exc:
|
|
522
|
+
raise _cliente.falha_de_escrita("atualizar_pagina", exc) from exc
|
|
523
|
+
except ErroDoNotion as exc:
|
|
524
|
+
raise NotionIncerto(
|
|
525
|
+
f"Notion atualizar_pagina: a resposta não confirma a página ({exc})"
|
|
526
|
+
) from exc
|
|
527
|
+
_cliente.checar_escrita("atualizar_pagina", resposta)
|
|
528
|
+
try:
|
|
529
|
+
dados = resposta.dados()
|
|
530
|
+
except ErroDoNotion as exc:
|
|
531
|
+
raise NotionIncerto(
|
|
532
|
+
f"Notion atualizar_pagina: a resposta não confirma a página ({exc})"
|
|
533
|
+
) from exc
|
|
534
|
+
return {"id": str(dados.get("id", pagina)), "url": str(dados.get("url", ""))}
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
"""O cliente HTTP da API do Notion: o token da conexão, a versão fixa, o prazo da chamada e a
|
|
2
|
+
retentativa.
|
|
3
|
+
|
|
4
|
+
Fala só com ``api.notion.com`` (o host que o plugin declara), sempre com ``chamada.destino(host)``
|
|
5
|
+
antes de conectar. O certificado é verificado; o ``HTTPS_PROXY`` do ambiente é respeitado (no
|
|
6
|
+
sandbox, o proxy da allowlist). Não segue redirecionamento: o token não vai a outro host.
|
|
7
|
+
|
|
8
|
+
O token vem de ``chamada.token(CONEXAO)``; o ``401`` (o token venceu antes da hora ou foi revogado)
|
|
9
|
+
troca o token uma vez (``renovar=True``) e repete: o pedido recusado não teve efeito.
|
|
10
|
+
|
|
11
|
+
A leitura repete a falha transitória, o ``429``, o ``529`` e o ``5xx`` mesmo depois do envio. A
|
|
12
|
+
escrita (criar e atualizar página) só repete o que certamente não saiu: o ``429``, o ``529`` e a
|
|
13
|
+
rede que recusou antes do envio. Depois do envio, a dúvida é do plugin, que confere no Notion: um
|
|
14
|
+
``503`` de escrita pode ter gravado, e o próprio Notion manda não repetir.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import ssl
|
|
21
|
+
import time
|
|
22
|
+
import urllib.error
|
|
23
|
+
import urllib.parse
|
|
24
|
+
import urllib.request
|
|
25
|
+
from collections.abc import Callable, Mapping
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
from shade_sdk import http
|
|
30
|
+
|
|
31
|
+
from shade_plugins_notion.erros import ErroDoNotion, NaoEncontrado, NotionIncerto, NotionNaoSaiu
|
|
32
|
+
|
|
33
|
+
#: A conexão OAuth da plataforma de que o plugin pede o token (o provedor do catálogo).
|
|
34
|
+
CONEXAO = "notion"
|
|
35
|
+
NOTION = "api.notion.com"
|
|
36
|
+
#: A versão fixa da API. Versão nova é minor nova do plugin, com a suíte.
|
|
37
|
+
VERSAO_DA_API = "2026-03-11"
|
|
38
|
+
#: Quantas vezes o pedido é tentado quando a rede ou o Notion falham de forma transitória.
|
|
39
|
+
TENTATIVAS = 3
|
|
40
|
+
#: A espera antes da 2ª e da 3ª tentativa (a régua do ``shade_sdk.http``).
|
|
41
|
+
ESPERAS = (0.5, 1.0)
|
|
42
|
+
#: O maior ``Retry-After`` que o plugin honra; acima disso, devolve o que recebeu.
|
|
43
|
+
ESPERA_MAX = 10.0
|
|
44
|
+
#: O teto do corpo de uma resposta lida na memória.
|
|
45
|
+
RESPOSTA_MAX = 8 * 1024 * 1024
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Prazo:
|
|
49
|
+
"""O ``timeout`` da chamada como um prazo só: cada etapa usa o que sobrou."""
|
|
50
|
+
|
|
51
|
+
def __init__(self, segundos: float) -> None:
|
|
52
|
+
self.fim = time.monotonic() + segundos
|
|
53
|
+
|
|
54
|
+
def restante(self) -> float:
|
|
55
|
+
sobra = self.fim - time.monotonic()
|
|
56
|
+
if sobra <= 0:
|
|
57
|
+
raise TimeoutError("o prazo da chamada acabou")
|
|
58
|
+
return sobra
|
|
59
|
+
|
|
60
|
+
def cabe(self, espera: float) -> bool:
|
|
61
|
+
return self.fim - time.monotonic() > espera
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class _SemRedirecionamento(urllib.request.HTTPRedirectHandler):
|
|
65
|
+
def redirect_request(self, *args: Any, **kwargs: Any) -> None:
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _abridor() -> Callable[..., Any]:
|
|
70
|
+
contexto = ssl.create_default_context()
|
|
71
|
+
contexto.minimum_version = ssl.TLSVersion.TLSv1_2
|
|
72
|
+
return urllib.request.build_opener(
|
|
73
|
+
urllib.request.ProxyHandler(),
|
|
74
|
+
urllib.request.HTTPSHandler(context=contexto),
|
|
75
|
+
_SemRedirecionamento(),
|
|
76
|
+
).open
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class Resposta:
|
|
81
|
+
status: int
|
|
82
|
+
cabecalhos: Mapping[str, str]
|
|
83
|
+
corpo: bytes = b""
|
|
84
|
+
|
|
85
|
+
def cabecalho(self, nome: str) -> str:
|
|
86
|
+
for chave, valor in self.cabecalhos.items():
|
|
87
|
+
if chave.lower() == nome.lower():
|
|
88
|
+
return valor
|
|
89
|
+
return ""
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def ok(self) -> bool:
|
|
93
|
+
return 200 <= self.status < 300
|
|
94
|
+
|
|
95
|
+
def json(self) -> Any:
|
|
96
|
+
try:
|
|
97
|
+
return json.loads(self.corpo)
|
|
98
|
+
except ValueError as exc:
|
|
99
|
+
raise ErroDoNotion("Notion: a resposta não é JSON", status=self.status) from exc
|
|
100
|
+
|
|
101
|
+
def dados(self) -> dict[str, Any]:
|
|
102
|
+
dados = self.json()
|
|
103
|
+
if not isinstance(dados, dict):
|
|
104
|
+
raise ErroDoNotion("Notion: a resposta não é um objeto JSON", status=self.status)
|
|
105
|
+
return dados
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def transitorio(exc: BaseException) -> bool:
|
|
109
|
+
"""Falha de rede em que repetir pode dar certo. O certificado inválido e o prazo esgotado,
|
|
110
|
+
não."""
|
|
111
|
+
if isinstance(exc, TimeoutError):
|
|
112
|
+
return False
|
|
113
|
+
return isinstance(exc, urllib.error.URLError | ConnectionError | ssl.SSLError) and not (
|
|
114
|
+
isinstance(exc, urllib.error.URLError)
|
|
115
|
+
and isinstance(exc.reason, ssl.SSLCertVerificationError)
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _retry_after(resposta: Resposta) -> float:
|
|
120
|
+
"""O ``Retry-After`` em segundos, limitado a ``ESPERA_MAX``."""
|
|
121
|
+
texto = resposta.cabecalho("Retry-After").strip()
|
|
122
|
+
if not texto.isdigit():
|
|
123
|
+
return 0.0
|
|
124
|
+
return min(float(texto), ESPERA_MAX)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@dataclass
|
|
128
|
+
class Cliente:
|
|
129
|
+
chamada: Any
|
|
130
|
+
prazo: Prazo
|
|
131
|
+
porta: int | None = None
|
|
132
|
+
_token: str | None = None
|
|
133
|
+
_renovou: bool = False
|
|
134
|
+
|
|
135
|
+
def url(self, caminho: str) -> str:
|
|
136
|
+
endereco = NOTION if self.porta in (None, 443) else f"{NOTION}:{self.porta}"
|
|
137
|
+
return f"https://{endereco}{caminho}"
|
|
138
|
+
|
|
139
|
+
def _bearer(self, *, renovar: bool = False) -> str:
|
|
140
|
+
if self._token is None or renovar:
|
|
141
|
+
self._token = self.chamada.token(CONEXAO, renovar=renovar)
|
|
142
|
+
return self._token
|
|
143
|
+
|
|
144
|
+
def pedir(
|
|
145
|
+
self,
|
|
146
|
+
metodo: str,
|
|
147
|
+
caminho: str,
|
|
148
|
+
*,
|
|
149
|
+
parametros: Mapping[str, str] | None = None,
|
|
150
|
+
corpo: Mapping[str, Any] | None = None,
|
|
151
|
+
idempotencia: str | None = None,
|
|
152
|
+
repetir_depois_do_envio: bool = True,
|
|
153
|
+
) -> Resposta:
|
|
154
|
+
"""Um pedido da API com o token da conexão, dentro do prazo: o ``corpo`` vai em JSON (o
|
|
155
|
+
``json.dumps`` escapa o valor) e os ``parametros`` na consulta. Repete a falha transitória
|
|
156
|
+
de rede, o ``429``, o ``529`` e o ``5xx`` quando ``repetir_depois_do_envio`` (a leitura);
|
|
157
|
+
senão, só o que certamente não saiu (a rede que recusou antes do envio, o ``429``, o
|
|
158
|
+
``529``). A autenticação vencida troca o token uma vez e repete. ``idempotencia`` vai no
|
|
159
|
+
``Idempotency-Key``: o Notion não o usa, e quem observa o tráfego (o proxy, o servidor
|
|
160
|
+
falso) distingue a execução."""
|
|
161
|
+
self.chamada.destino(NOTION)
|
|
162
|
+
url = self.url(caminho)
|
|
163
|
+
if parametros:
|
|
164
|
+
url += "?" + urllib.parse.urlencode(dict(parametros))
|
|
165
|
+
dados = None if corpo is None else json.dumps(corpo, ensure_ascii=False).encode("utf-8")
|
|
166
|
+
abrir = _abridor()
|
|
167
|
+
ultima_falha: BaseException | None = None
|
|
168
|
+
ultima_resposta: Resposta | None = None
|
|
169
|
+
tentativa = 0
|
|
170
|
+
while tentativa < TENTATIVAS:
|
|
171
|
+
if tentativa:
|
|
172
|
+
espera = ESPERAS[min(tentativa - 1, len(ESPERAS) - 1)]
|
|
173
|
+
if ultima_resposta is not None:
|
|
174
|
+
espera = max(espera, _retry_after(ultima_resposta))
|
|
175
|
+
if not self.prazo.cabe(espera):
|
|
176
|
+
break
|
|
177
|
+
time.sleep(espera)
|
|
178
|
+
tentativa += 1
|
|
179
|
+
enviados = {
|
|
180
|
+
"Accept": "application/json",
|
|
181
|
+
"Authorization": f"Bearer {self._bearer()}",
|
|
182
|
+
"Notion-Version": VERSAO_DA_API,
|
|
183
|
+
}
|
|
184
|
+
if dados is not None:
|
|
185
|
+
enviados["Content-Type"] = "application/json; charset=utf-8"
|
|
186
|
+
if idempotencia:
|
|
187
|
+
enviados["Idempotency-Key"] = idempotencia
|
|
188
|
+
pedido = urllib.request.Request(url, data=dados, headers=enviados, method=metodo)
|
|
189
|
+
try:
|
|
190
|
+
resposta = self._despachar(abrir, pedido)
|
|
191
|
+
except Exception as exc:
|
|
192
|
+
if not transitorio(exc) or not (repetir_depois_do_envio or http.nada_saiu(exc)):
|
|
193
|
+
raise
|
|
194
|
+
ultima_falha, ultima_resposta = exc, None
|
|
195
|
+
continue
|
|
196
|
+
if not self._renovou and resposta.status == 401:
|
|
197
|
+
# O token venceu antes da hora ou foi revogado: o pedido não teve efeito.
|
|
198
|
+
self._renovou = True
|
|
199
|
+
self._bearer(renovar=True)
|
|
200
|
+
tentativa -= 1
|
|
201
|
+
continue
|
|
202
|
+
if resposta.status in (429, 529) or (
|
|
203
|
+
resposta.status >= 500 and repetir_depois_do_envio
|
|
204
|
+
):
|
|
205
|
+
ultima_falha, ultima_resposta = None, resposta
|
|
206
|
+
continue
|
|
207
|
+
return resposta
|
|
208
|
+
if ultima_resposta is not None:
|
|
209
|
+
return ultima_resposta
|
|
210
|
+
if ultima_falha is None:
|
|
211
|
+
raise TimeoutError("o prazo da chamada acabou")
|
|
212
|
+
raise ultima_falha
|
|
213
|
+
|
|
214
|
+
def _despachar(self, abrir: Callable[..., Any], pedido: Any) -> Resposta:
|
|
215
|
+
try:
|
|
216
|
+
with abrir(pedido, timeout=self.prazo.restante()) as resposta:
|
|
217
|
+
corpo = resposta.read(RESPOSTA_MAX + 1)
|
|
218
|
+
if len(corpo) > RESPOSTA_MAX:
|
|
219
|
+
raise ErroDoNotion("Notion: a resposta passa do teto de leitura")
|
|
220
|
+
return Resposta(resposta.status, dict(resposta.headers.items()), corpo)
|
|
221
|
+
except urllib.error.HTTPError as exc:
|
|
222
|
+
corpo = exc.read(65536) if exc.fp else b""
|
|
223
|
+
return Resposta(exc.code, dict(exc.headers.items()), corpo)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def checar_leitura(operacao: str, resposta: Resposta) -> dict[str, Any]:
|
|
227
|
+
"""Os dados da resposta de uma leitura; o erro vira ``ErroDoNotion`` só com o status."""
|
|
228
|
+
if resposta.ok:
|
|
229
|
+
return resposta.dados()
|
|
230
|
+
if resposta.status == 404:
|
|
231
|
+
raise NaoEncontrado(
|
|
232
|
+
f"Notion {operacao}: o registro não existe, ou não foi compartilhado com a conexão (404)",
|
|
233
|
+
status=404,
|
|
234
|
+
)
|
|
235
|
+
if resposta.status in (401, 403):
|
|
236
|
+
raise ErroDoNotion(
|
|
237
|
+
f"Notion {operacao}: a conexão não tem permissão ({resposta.status}); "
|
|
238
|
+
"reconecte o Notion e compartilhe a página ou a base com ela",
|
|
239
|
+
status=resposta.status,
|
|
240
|
+
)
|
|
241
|
+
raise ErroDoNotion(
|
|
242
|
+
f"Notion {operacao}: o Notion devolveu {resposta.status}", status=resposta.status
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def checar_escrita(operacao: str, resposta: Resposta) -> Resposta:
|
|
247
|
+
"""O 2xx passa; o 4xx (e o 429 e o 529 que sobraram das tentativas) é ``NotionNaoSaiu``; o erro
|
|
248
|
+
do servidor é dúvida (``NotionIncerto``)."""
|
|
249
|
+
if resposta.status >= 500 and resposta.status != 529:
|
|
250
|
+
raise NotionIncerto(
|
|
251
|
+
f"Notion {operacao}: o Notion devolveu {resposta.status}", status=resposta.status
|
|
252
|
+
)
|
|
253
|
+
if resposta.ok:
|
|
254
|
+
return resposta
|
|
255
|
+
dica = (
|
|
256
|
+
"; reconecte o Notion e compartilhe a página ou a base com ela"
|
|
257
|
+
if resposta.status in (401, 403, 404)
|
|
258
|
+
else ""
|
|
259
|
+
)
|
|
260
|
+
raise NotionNaoSaiu(
|
|
261
|
+
f"Notion {operacao}: o Notion recusou o pedido ({resposta.status}){dica}",
|
|
262
|
+
status=resposta.status,
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def id_gravado(resposta: Resposta) -> str | None:
|
|
267
|
+
"""O id da página que um ``5xx`` diz ter gravado (``additional_data.committed_resource_id``:
|
|
268
|
+
o Notion salvou e não conseguiu montar a resposta)."""
|
|
269
|
+
if resposta.status < 500:
|
|
270
|
+
return None
|
|
271
|
+
try:
|
|
272
|
+
adicional = resposta.dados().get("additional_data")
|
|
273
|
+
except ErroDoNotion:
|
|
274
|
+
return None
|
|
275
|
+
gravado = adicional.get("committed_resource_id") if isinstance(adicional, dict) else None
|
|
276
|
+
return gravado if isinstance(gravado, str) else None
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def falha_de_leitura(operacao: str, exc: BaseException) -> ErroDoNotion:
|
|
280
|
+
return ErroDoNotion(f"Notion {operacao}: a conexão falhou ({type(exc).__name__})")
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def falha_de_escrita(operacao: str, exc: BaseException) -> Exception:
|
|
284
|
+
if http.nada_saiu(exc):
|
|
285
|
+
return NotionNaoSaiu(f"Notion {operacao}: a conexão não abriu ({type(exc).__name__})")
|
|
286
|
+
return NotionIncerto(
|
|
287
|
+
f"Notion {operacao}: a conexão falhou depois do envio ({type(exc).__name__}); "
|
|
288
|
+
"a alteração pode ter chegado"
|
|
289
|
+
)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Os erros do plugin ``notion``.
|
|
2
|
+
|
|
3
|
+
Separam o que **certamente não chegou** ao Notion (``NotionNaoSaiu``, um ``http.NadaSaiu``) do que
|
|
4
|
+
**pode ter chegado** (``NotionIncerto``, um ``http.ResultadoIncerto``). O token que não veio é o
|
|
5
|
+
``TokenIndisponivel`` do ``shade_sdk.plugins`` (também um ``http.NadaSaiu``).
|
|
6
|
+
|
|
7
|
+
As mensagens dizem a operação e o status HTTP, nunca o corpo, as propriedades nem o token.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from shade_sdk import http
|
|
13
|
+
from shade_sdk.erros import ErroDeNegocio
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ErroDoNotion(Exception):
|
|
17
|
+
"""A leitura não deu certo: conexão, TLS, permissão ou o Notion recusou o pedido."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, mensagem: str, *, status: int | None = None) -> None:
|
|
20
|
+
super().__init__(mensagem)
|
|
21
|
+
self.status = status
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class NaoEncontrado(ErroDoNotion):
|
|
25
|
+
"""A base ou a página não existe, ou não foi compartilhada com a conexão (``404``)."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ColunaAusente(ErroDeNegocio):
|
|
29
|
+
"""A base não tem a coluna de texto ``Chave Shade``, sem a qual ``criar_pagina`` não sabe se a
|
|
30
|
+
página já existe. Nada foi escrito."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class FonteNaoEscolhida(ErroDeNegocio):
|
|
34
|
+
"""A base tem mais de uma fonte de dados e a chamada não disse qual (``fonte=``), ou a fonte
|
|
35
|
+
pedida não é uma delas. A mensagem lista os nomes."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class NotionNaoSaiu(http.NadaSaiu):
|
|
39
|
+
"""Certamente sem efeito: o Notion recusou o pedido (4xx, inclusive o 429 que sobrou das
|
|
40
|
+
retentativas), estava sobrecarregado (529) ou a rede falhou antes do envio."""
|
|
41
|
+
|
|
42
|
+
def __init__(self, mensagem: str, *, status: int | None = None) -> None:
|
|
43
|
+
super().__init__(mensagem)
|
|
44
|
+
self.status = status
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class NotionIncerto(http.ResultadoIncerto):
|
|
48
|
+
"""Pode ter tido efeito: o pedido foi enviado e a resposta não veio, veio com erro do servidor
|
|
49
|
+
ou não se leu. Conferir no Notion antes de concluir que não chegou."""
|
|
50
|
+
|
|
51
|
+
def __init__(self, mensagem: str, *, status: int | None = None) -> None:
|
|
52
|
+
super().__init__(mensagem)
|
|
53
|
+
self.status = status
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: shade-plugins-notion
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Consultar uma base, criar página (sem duplicar, pela coluna "Chave Shade") e atualizar página no Notion, com o token OAuth da conexão da plataforma.
|
|
5
|
+
Author: ShadeOne
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Python: >=3.11
|
|
9
|
+
Requires-Dist: shade-sdk<0.23,>=0.22.3
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
|
|
12
|
+
# shade-plugins-notion
|
|
13
|
+
|
|
14
|
+
Consulta uma base, cria uma página (sem duplicar) e atualiza uma página no
|
|
15
|
+
[Notion](https://developers.notion.com/), de dentro de um robô do
|
|
16
|
+
[`shade-sdk`](https://pypi.org/project/shade-sdk/), com o token OAuth da conexão do Notion na
|
|
17
|
+
plataforma. Só a biblioteca padrão do Python: nenhuma dependência além do `shade-sdk`.
|
|
18
|
+
|
|
19
|
+
No `shade.toml` do robô, o host da API vai em `[hosts] permitidos` e a conexão em `[conexoes]`:
|
|
20
|
+
|
|
21
|
+
```toml
|
|
22
|
+
[hosts]
|
|
23
|
+
permitidos = ["api.notion.com"]
|
|
24
|
+
|
|
25
|
+
[conexoes]
|
|
26
|
+
nomes = ["notion"]
|
|
27
|
+
|
|
28
|
+
[plugins]
|
|
29
|
+
notion = "0.1.0"
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
import shade_plugins_notion as notion
|
|
34
|
+
|
|
35
|
+
BASE = "0f1e2d3c4b5a69788796a5b4c3d2e1f0" # o id, da URL da base
|
|
36
|
+
|
|
37
|
+
# Leitura: roda inclusive no ensaio.
|
|
38
|
+
novos = notion.consultar_base(BASE, filtro={"property": "Status", "select": {"equals": "Novo"}})
|
|
39
|
+
nomes = [notion.texto_de(p["propriedades"]["Nome"]) for p in novos]
|
|
40
|
+
|
|
41
|
+
# Escrita: só dentro de item.efetivar() (no ensaio não roda).
|
|
42
|
+
with item.efetivar("registrar o pedido"):
|
|
43
|
+
nova = notion.criar_pagina(
|
|
44
|
+
BASE,
|
|
45
|
+
{"Nome": notion.titulo(f"Pedido {item['numero']}"), "Valor": {"number": item["valor"]}},
|
|
46
|
+
)
|
|
47
|
+
notion.atualizar_pagina(nova["id"], {"Observação": notion.texto(item["detalhe"])})
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Antes de usar
|
|
51
|
+
|
|
52
|
+
- **Crie na base a coluna de texto `Chave Shade`.** É o que faz `criar_pagina` não duplicar. Sem ela,
|
|
53
|
+
a operação recusa com `ColunaAusente` (um `ErroDeNegocio`) antes de qualquer escrita. A coluna é do
|
|
54
|
+
plugin: não a edite, e o robô não pode passá-la em `propriedades`.
|
|
55
|
+
- **Compartilhe a base com a conexão.** O Notion não tem escopos: a conexão só vê o que a pessoa
|
|
56
|
+
escolheu ao conectar ou adicionou depois no menu da página. O que não foi compartilhado responde
|
|
57
|
+
`404`, igual ao que não existe.
|
|
58
|
+
|
|
59
|
+
## A conta
|
|
60
|
+
|
|
61
|
+
- **Conexão:** o robô nunca vê a senha nem o refresh token. O token de acesso chega sob demanda da
|
|
62
|
+
conexão `notion` da plataforma e é renovado por ela. Fora da plataforma (no laptop), ponha um token
|
|
63
|
+
em `SHADE_TOKEN_NOTION`.
|
|
64
|
+
- **Fonte de dados:** uma base do Notion pode ter mais de uma. O plugin lê as da base a cada chamada;
|
|
65
|
+
com mais de uma, passe `fonte=` (o nome ou o id); sem ele, o erro é `FonteNaoEscolhida` (um
|
|
66
|
+
`ErroDeNegocio`) e a mensagem lista os nomes.
|
|
67
|
+
- **Versão da API:** `Notion-Version: 2026-03-11`, fixa. Versão nova da API é versão nova do plugin.
|
|
68
|
+
|
|
69
|
+
## O que o plugin garante
|
|
70
|
+
|
|
71
|
+
- **Página sem duplicar.** `criar_pagina` grava a chave do item na coluna `Chave Shade` e, antes de
|
|
72
|
+
criar, consulta a base por ela; achando, devolve a página (`reaproveitada=True`). Depois de
|
|
73
|
+
despachado, o pedido de criação nunca é repetido: se a resposta se perde, o plugin consulta de novo
|
|
74
|
+
e, sem achar, o erro é `NotionIncerto` (a página pode existir: confira no Notion antes de refazer).
|
|
75
|
+
- **Atualização idempotente por natureza.** `atualizar_pagina` grava os valores pedidos, e refazer
|
|
76
|
+
grava os mesmos. Ela também não se repete sozinha depois do envio: o Notion avisa que a escrita que
|
|
77
|
+
respondeu `503` pode ter gravado. Sem confirmação, é `NotionIncerto`, e refazer é seguro.
|
|
78
|
+
- **Só dentro de `item.efetivar()`.** Fora dele, a operação é um erro de contrato antes de qualquer
|
|
79
|
+
byte; no ensaio, o bloco é pulado e nada é enviado.
|
|
80
|
+
- **Valores literais.** As propriedades são objetos serializados por `json.dumps`, e `titulo()` e
|
|
81
|
+
`texto()` põem o dado em `text.content`: um `**` ou um link do dado vai como texto. Os ids são
|
|
82
|
+
validados antes de qualquer pedido.
|
|
83
|
+
- **Host e prazo:** só `api.notion.com`, com o certificado verificado, sem seguir redirecionamento;
|
|
84
|
+
toda chamada aceita `timeout=` (30 s por padrão), que vale para a chamada inteira.
|
|
85
|
+
- **Sem conteúdo em evento nem em erro:** cada chamada emite um evento com a operação, o host, a
|
|
86
|
+
duração e o status. Nunca as propriedades, o token nem o corpo da resposta.
|
|
87
|
+
|
|
88
|
+
## Operações
|
|
89
|
+
|
|
90
|
+
| Operação | Efeito | O que faz |
|
|
91
|
+
|---|---|---|
|
|
92
|
+
| `consultar_base(base, filtro=None, *, limite=100, fonte=None)` | não | Páginas da base: `id`, `url` e `propriedades`. `filtro` é o da API do Notion. Segue o `next_cursor`. |
|
|
93
|
+
| `criar_pagina(base, propriedades, *, fonte=None)` | sim | Cria a página na base. Devolve `id`, `url` e `reaproveitada`. |
|
|
94
|
+
| `atualizar_pagina(pagina, propriedades)` | sim | Grava as propriedades pedidas. Devolve `id` e `url`. |
|
|
95
|
+
|
|
96
|
+
`propriedades` vão no formato da API do Notion, pelo nome da coluna: `{"Valor": {"number": 1}}`,
|
|
97
|
+
`{"Status": {"select": {"name": "Feito"}}}`. Para as de texto, `notion.titulo("x")` e
|
|
98
|
+
`notion.texto("x")` montam o valor e dividem o texto longo nas partes que o Notion aceita. Na leitura,
|
|
99
|
+
`notion.texto_de(propriedade)` devolve o texto.
|
|
100
|
+
|
|
101
|
+
## Limites
|
|
102
|
+
|
|
103
|
+
- Se alguém mover para a lixeira ou arquivar a página antes de um refazer, a consulta não a enxerga, e
|
|
104
|
+
o refazer cria outra.
|
|
105
|
+
- A consulta pode demorar a enxergar a página recém-criada. Por isso, a dúvida depois de uma resposta
|
|
106
|
+
perdida pode ficar `NotionIncerto`.
|
|
107
|
+
- `consultar_base` devolve até 5.000 páginas por chamada.
|
|
108
|
+
- Conteúdo da página (blocos), arquivo e criação de base ficam fora do plugin.
|
|
109
|
+
|
|
110
|
+
## Testes
|
|
111
|
+
|
|
112
|
+
A suíte de contrato do `shade_sdk.testing.plugins` e um servidor falso da API (TLS de uma CA de
|
|
113
|
+
teste, que recusa propriedade desconhecida, de outro tipo ou acima dos limites de texto, como a de
|
|
114
|
+
verdade) acompanham o código-fonte em `tests/`.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
shade_plugins_notion/__init__.py,sha256=9rYmrP3MC7ErhisYJ_gznpgV8OwoS1Qia8ereg74Bts,22412
|
|
2
|
+
shade_plugins_notion/_cliente.py,sha256=2915Q-rFva2G5ifuUSgWr704FDpd_vIHQ97hQF33P_E,11402
|
|
3
|
+
shade_plugins_notion/erros.py,sha256=i0kZobH5crFnUU5OPwoHj0qfpcJB7_BxACiwrmJLZyM,2021
|
|
4
|
+
shade_plugins_notion-0.1.0.dist-info/METADATA,sha256=9WcUAu8KUcJBGqqzWAk889sKlPiY61vdLIG38HrRlGI,5764
|
|
5
|
+
shade_plugins_notion-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
6
|
+
shade_plugins_notion-0.1.0.dist-info/entry_points.txt,sha256=DGmLpwUsEEfDmVaMe-uJXT3GXBrG36uQxZXK9xY096g,57
|
|
7
|
+
shade_plugins_notion-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
8
|
+
shade_plugins_notion-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|