shade-plugins-google 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_google/__init__.py +513 -0
- shade_plugins_google/_cliente.py +288 -0
- shade_plugins_google/erros.py +36 -0
- shade_plugins_google-0.1.0.dist-info/METADATA +86 -0
- shade_plugins_google-0.1.0.dist-info/RECORD +8 -0
- shade_plugins_google-0.1.0.dist-info/WHEEL +4 -0
- shade_plugins_google-0.1.0.dist-info/entry_points.txt +2 -0
- shade_plugins_google-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
"""O plugin ``google``: ler e escrever no Google Sheets e listar, baixar e enviar no Google Drive
|
|
2
|
+
sob o contrato de plugin do shade-sdk, com o token OAuth da conexão da plataforma.
|
|
3
|
+
|
|
4
|
+
```toml
|
|
5
|
+
[hosts]
|
|
6
|
+
permitidos = ["sheets.googleapis.com", "www.googleapis.com"]
|
|
7
|
+
|
|
8
|
+
[conexoes]
|
|
9
|
+
nomes = ["google-drive"]
|
|
10
|
+
|
|
11
|
+
[plugins]
|
|
12
|
+
google = "0.1.0"
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
import shade_plugins_google as google
|
|
17
|
+
|
|
18
|
+
for pedido in google.ler_planilha("1AbC...", "Pedidos!A1:D"):
|
|
19
|
+
...
|
|
20
|
+
|
|
21
|
+
with item.efetivar("registrar na planilha"):
|
|
22
|
+
google.escrever_linha("1AbC...", "Pedidos!A1", [item["pedido"], item["cliente"], "ok"])
|
|
23
|
+
|
|
24
|
+
with item.efetivar("guardar o comprovante"):
|
|
25
|
+
google.enviar_arquivo("comprovante.pdf", pasta="1XyZ...")
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
- **Conta:** a conexão ``google-drive`` da plataforma (Conectores). O robô nunca vê a senha nem
|
|
29
|
+
o refresh token: o token de acesso chega sob demanda e é renovado pela plataforma. No laptop,
|
|
30
|
+
ponha um token de acesso em ``SHADE_TOKEN_GOOGLE_DRIVE``.
|
|
31
|
+
- **Escopo:** a conexão pede ``spreadsheets`` e ``drive.file``. Planilha: qualquer uma que a
|
|
32
|
+
conta veja. Drive: só o que o próprio app enviou (``enviar_arquivo``) ou que a conta abriu
|
|
33
|
+
com ele; o resto do Drive não aparece em ``listar_arquivos`` (devolve 404 em
|
|
34
|
+
``baixar_arquivo``).
|
|
35
|
+
- **Ler não muda nada:** ``ler_planilha``, ``listar_arquivos`` e ``baixar_arquivo`` rodam
|
|
36
|
+
inclusive no ensaio.
|
|
37
|
+
- **Escrever só dentro de** ``item.efetivar()`` (no ensaio não roda):
|
|
38
|
+
- ``enviar_arquivo`` não duplica: o arquivo leva uma marca derivada da chave do item, do nome
|
|
39
|
+
da efetivação e da ordem do envio, e antes de criar o plugin procura a marca. A
|
|
40
|
+
retentativa e o "refazer" acham o que já subiu, enquanto a busca do Drive o enxergar (logo
|
|
41
|
+
depois de um envio sem confirmação ela pode atrasar: por isso a dúvida é ``GoogleIncerto``).
|
|
42
|
+
- ``escrever_linha`` acrescenta uma linha (``values.append``): o Sheets não reconhece
|
|
43
|
+
repetição, então o plugin só repete o que certamente não chegou (a rede que recusou, o
|
|
44
|
+
``429``). Depois do envio, a dúvida vira ``GoogleIncerto`` e o item fica retido para
|
|
45
|
+
conferência. O texto vai cru (``RAW``): ``=HYPERLINK(...)`` entra como texto, nunca como
|
|
46
|
+
fórmula.
|
|
47
|
+
- **Prazo:** ``timeout=`` (30 s) vale para a chamada inteira, retentativas incluídas.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
from __future__ import annotations
|
|
51
|
+
|
|
52
|
+
import mimetypes
|
|
53
|
+
import os
|
|
54
|
+
import re
|
|
55
|
+
import secrets
|
|
56
|
+
import urllib.parse
|
|
57
|
+
from pathlib import Path
|
|
58
|
+
from typing import Any
|
|
59
|
+
|
|
60
|
+
from shade_sdk import http
|
|
61
|
+
from shade_sdk.plugins import Plugin
|
|
62
|
+
|
|
63
|
+
from shade_plugins_google import _cliente
|
|
64
|
+
from shade_plugins_google._cliente import CONEXAO, DRIVE, SHEETS, Cliente, Prazo
|
|
65
|
+
from shade_plugins_google.erros import ErroDoGoogle, GoogleIncerto, GoogleNaoSaiu, NaoEncontrado
|
|
66
|
+
|
|
67
|
+
__version__ = "0.1.0"
|
|
68
|
+
|
|
69
|
+
#: Quantos arquivos ``listar_arquivos`` devolve, no máximo, e quantos o Drive dá por página.
|
|
70
|
+
LIMITE_MAX = 10_000
|
|
71
|
+
POR_PAGINA = 100
|
|
72
|
+
#: O teto de um download.
|
|
73
|
+
ARQUIVO_MAX = 1024 * 1024 * 1024
|
|
74
|
+
#: O teto de um envio: o upload ``multipart`` do Drive é para arquivos de até 5 MB.
|
|
75
|
+
ENVIO_MAX = 5 * 1024 * 1024
|
|
76
|
+
#: A propriedade privada do app que marca o arquivo enviado com a chave da chamada.
|
|
77
|
+
MARCA = "shade_idempotencia"
|
|
78
|
+
#: O id de planilha, arquivo e pasta do Google: letras, dígitos, ``-`` e ``_``.
|
|
79
|
+
_ID = re.compile(r"^[A-Za-z0-9_-]{1,200}$")
|
|
80
|
+
_CONTROLE = re.compile(r"[\x00-\x1f\x7f]")
|
|
81
|
+
#: O tipo MIME (``application/pdf``): vai num cabeçalho da parte do upload.
|
|
82
|
+
_MIME = re.compile(
|
|
83
|
+
r"^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,63}/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}$"
|
|
84
|
+
)
|
|
85
|
+
#: O prefixo dos arquivos nativos do Google (Docs, Sheets, Slides), que não se baixam como são.
|
|
86
|
+
_NATIVO = "application/vnd.google-apps."
|
|
87
|
+
_CAMPOS_DO_ARQUIVO = "id,name,mimeType,size,modifiedTime,parents"
|
|
88
|
+
|
|
89
|
+
PLUGIN = Plugin(
|
|
90
|
+
"google",
|
|
91
|
+
__version__,
|
|
92
|
+
shade_sdk=">=0.22.3,<0.23",
|
|
93
|
+
dono="Equipe de integrações da ShadeOne",
|
|
94
|
+
hosts=[SHEETS, DRIVE],
|
|
95
|
+
conexoes=[CONEXAO],
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
__all__ = [
|
|
99
|
+
"PLUGIN",
|
|
100
|
+
"ErroDoGoogle",
|
|
101
|
+
"GoogleIncerto",
|
|
102
|
+
"GoogleNaoSaiu",
|
|
103
|
+
"NaoEncontrado",
|
|
104
|
+
"baixar_arquivo",
|
|
105
|
+
"enviar_arquivo",
|
|
106
|
+
"escrever_linha",
|
|
107
|
+
"ler_planilha",
|
|
108
|
+
"listar_arquivos",
|
|
109
|
+
]
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# ── as réguas ─────────────────────────────────────────────────────────────────────────────
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _id(valor: Any, campo: str) -> str:
|
|
116
|
+
if not isinstance(valor, str) or not _ID.fullmatch(valor):
|
|
117
|
+
raise ValueError(f"{campo} é o id do Google (letras, dígitos, '-' e '_'), como na URL")
|
|
118
|
+
return valor
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _intervalo(valor: Any) -> str:
|
|
122
|
+
"""O intervalo em notação A1 (``Pedidos!A1:D``): vai codificado no caminho, inteiro."""
|
|
123
|
+
if not isinstance(valor, str) or not valor.strip() or len(valor) > 500:
|
|
124
|
+
raise ValueError("intervalo é a notação A1, como 'Pedidos!A1:D' (até 500 caracteres)")
|
|
125
|
+
if _CONTROLE.search(valor):
|
|
126
|
+
raise ValueError("intervalo não pode ter quebra de linha nem caractere de controle")
|
|
127
|
+
return urllib.parse.quote(valor, safe="")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _porta(porta: Any) -> int | None:
|
|
131
|
+
if porta is not None and (
|
|
132
|
+
not isinstance(porta, int) or isinstance(porta, bool) or not 0 < porta < 65536
|
|
133
|
+
):
|
|
134
|
+
raise ValueError(f"porta é um número de 1 a 65535, não {porta!r}")
|
|
135
|
+
return porta
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def literal_do_drive(valor: str) -> str:
|
|
139
|
+
"""O texto como literal da consulta do Drive (``q``): entre aspas simples, com ``\\`` e
|
|
140
|
+
``'`` escapados por ``\\`` (a regra da API). A barra vem primeiro, para a barra que o valor
|
|
141
|
+
traz não escapar a aspa que a regra acrescenta."""
|
|
142
|
+
if not isinstance(valor, str) or _CONTROLE.search(valor):
|
|
143
|
+
raise ValueError("o texto da busca não pode ter quebra de linha nem caractere de controle")
|
|
144
|
+
return "'" + valor.replace("\\", "\\\\").replace("'", "\\'") + "'"
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _celula(valor: Any) -> Any:
|
|
148
|
+
if valor is None:
|
|
149
|
+
return ""
|
|
150
|
+
if isinstance(valor, bool | int | float | str):
|
|
151
|
+
return valor
|
|
152
|
+
raise TypeError(f"a célula é texto, número, booleano ou None, não {type(valor).__name__}")
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _arquivo_do_workdir(caminho: Any) -> Path:
|
|
156
|
+
if not isinstance(caminho, str | os.PathLike):
|
|
157
|
+
raise TypeError("arquivo é o caminho de um arquivo do diretório de trabalho")
|
|
158
|
+
relativo = Path(caminho)
|
|
159
|
+
raiz = Path.cwd().resolve()
|
|
160
|
+
completo = (raiz / relativo).resolve()
|
|
161
|
+
if relativo.is_absolute() or completo != raiz and raiz not in completo.parents:
|
|
162
|
+
raise ValueError("arquivo é um caminho dentro do diretório de trabalho")
|
|
163
|
+
if not completo.is_file():
|
|
164
|
+
raise FileNotFoundError("arquivo: não existe no diretório de trabalho")
|
|
165
|
+
return completo
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _pasta_relativa(pasta: Any) -> Path:
|
|
169
|
+
if not isinstance(pasta, str) or not pasta or _CONTROLE.search(pasta):
|
|
170
|
+
raise ValueError("pasta é um caminho relativo do diretório de trabalho")
|
|
171
|
+
partes = pasta.split("/")
|
|
172
|
+
if pasta.startswith("/") or any(p in ("", ".", "..") for p in partes):
|
|
173
|
+
raise ValueError("pasta é um caminho relativo, sem '..' nem segmento vazio")
|
|
174
|
+
return Path(pasta)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _nome_de_arquivo(nome: str) -> str:
|
|
178
|
+
limpo = _CONTROLE.sub("_", nome.replace("/", "_").replace("\\", "_")).strip(". ")
|
|
179
|
+
return (limpo or "arquivo")[:200]
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _arquivo(dados: dict[str, Any]) -> dict[str, Any]:
|
|
183
|
+
tamanho = dados.get("size")
|
|
184
|
+
return {
|
|
185
|
+
"id": dados.get("id", ""),
|
|
186
|
+
"nome": dados.get("name", ""),
|
|
187
|
+
"tipo": dados.get("mimeType", ""),
|
|
188
|
+
"tamanho": int(tamanho) if isinstance(tamanho, str) and tamanho.isdigit() else None,
|
|
189
|
+
"modificado": dados.get("modifiedTime", ""),
|
|
190
|
+
"pastas": list(dados.get("parents") or []),
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _lendo(operacao: str, funcao: Any) -> Any:
|
|
195
|
+
"""A falha de rede no meio da leitura vira ``ErroDoGoogle``."""
|
|
196
|
+
try:
|
|
197
|
+
return funcao()
|
|
198
|
+
except ErroDoGoogle:
|
|
199
|
+
raise
|
|
200
|
+
except OSError as exc:
|
|
201
|
+
raise _cliente.falha_de_leitura(operacao, exc) from exc
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _cliente_da_chamada(chamada: Any, porta: Any) -> Cliente:
|
|
205
|
+
return Cliente(chamada=chamada, prazo=Prazo(chamada.timeout), porta=_porta(porta))
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
# ── Sheets ────────────────────────────────────────────────────────────────────────────────
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
@PLUGIN.operacao
|
|
212
|
+
def ler_planilha(
|
|
213
|
+
chamada: Any,
|
|
214
|
+
planilha: str,
|
|
215
|
+
intervalo: str,
|
|
216
|
+
*,
|
|
217
|
+
cabecalho: bool = True,
|
|
218
|
+
porta: int | None = None,
|
|
219
|
+
) -> list[Any]:
|
|
220
|
+
"""As linhas de ``intervalo`` (``Pedidos!A1:D``) da planilha ``planilha`` (o id da URL),
|
|
221
|
+
como a planilha as mostra (o valor formatado). Com ``cabecalho`` (o padrão), a primeira linha
|
|
222
|
+
dá os nomes e cada linha seguinte vira um ``dict`` (célula vazia no fim da linha vira
|
|
223
|
+
``""``); sem ele, cada linha é uma lista. ``NaoEncontrado`` se a planilha ou a aba não
|
|
224
|
+
existe ou a conta não a vê."""
|
|
225
|
+
caminho = f"/v4/spreadsheets/{_id(planilha, 'planilha')}/values/{_intervalo(intervalo)}"
|
|
226
|
+
cliente = _cliente_da_chamada(chamada, porta)
|
|
227
|
+
|
|
228
|
+
def ler() -> list[Any]:
|
|
229
|
+
resposta = cliente.pedir("GET", SHEETS, caminho, parametros={"majorDimension": "ROWS"})
|
|
230
|
+
_cliente.checar_leitura("ler_planilha", resposta)
|
|
231
|
+
linhas = resposta.json().get("values") or []
|
|
232
|
+
if not cabecalho:
|
|
233
|
+
return [list(linha) for linha in linhas]
|
|
234
|
+
if not linhas:
|
|
235
|
+
return []
|
|
236
|
+
nomes = [str(n).strip() or f"coluna_{i + 1}" for i, n in enumerate(linhas[0])]
|
|
237
|
+
repetidos = sorted({n for n in nomes if nomes.count(n) > 1})
|
|
238
|
+
if repetidos:
|
|
239
|
+
raise ErroDoGoogle(f"Google ler_planilha: o cabeçalho repete {repetidos}")
|
|
240
|
+
return [
|
|
241
|
+
{nome: (linha[i] if i < len(linha) else "") for i, nome in enumerate(nomes)}
|
|
242
|
+
for linha in linhas[1:]
|
|
243
|
+
]
|
|
244
|
+
|
|
245
|
+
return _lendo("ler_planilha", ler)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
@PLUGIN.efeito
|
|
249
|
+
def escrever_linha(
|
|
250
|
+
chamada: Any,
|
|
251
|
+
planilha: str,
|
|
252
|
+
intervalo: str,
|
|
253
|
+
valores: list[Any] | tuple[Any, ...],
|
|
254
|
+
*,
|
|
255
|
+
porta: int | None = None,
|
|
256
|
+
) -> dict[str, Any]:
|
|
257
|
+
"""Acrescenta uma linha depois da tabela de ``intervalo`` (``Pedidos!A1``), só dentro de
|
|
258
|
+
``item.efetivar()``. Cada valor é texto, número, booleano ou ``None`` (célula vazia), e vai
|
|
259
|
+
cru: o texto ``=SOMA(A1:A9)`` entra como texto, nunca como fórmula. Devolve ``intervalo`` (o
|
|
260
|
+
que foi escrito, como ``Pedidos!A7:C7``).
|
|
261
|
+
|
|
262
|
+
O Sheets não reconhece repetição: o plugin só repete o que certamente não chegou.
|
|
263
|
+
``GoogleNaoSaiu`` (um ``http.NadaSaiu``): o Google recusou ou a rede não abriu.
|
|
264
|
+
``GoogleIncerto``: o pedido foi e a confirmação não veio; a linha pode ter entrado."""
|
|
265
|
+
if not isinstance(valores, list | tuple) or not valores:
|
|
266
|
+
raise ValueError("valores é a lista das células da linha")
|
|
267
|
+
linha = [_celula(v) for v in valores]
|
|
268
|
+
caminho = f"/v4/spreadsheets/{_id(planilha, 'planilha')}/values/{_intervalo(intervalo)}:append"
|
|
269
|
+
cliente = _cliente_da_chamada(chamada, porta)
|
|
270
|
+
try:
|
|
271
|
+
resposta = cliente.pedir(
|
|
272
|
+
"POST",
|
|
273
|
+
SHEETS,
|
|
274
|
+
caminho,
|
|
275
|
+
parametros={"valueInputOption": "RAW", "insertDataOption": "INSERT_ROWS"},
|
|
276
|
+
corpo=_json({"majorDimension": "ROWS", "values": [linha]}),
|
|
277
|
+
tipo="application/json",
|
|
278
|
+
idempotencia=chamada.idempotencia,
|
|
279
|
+
repetir_depois_do_envio=False,
|
|
280
|
+
)
|
|
281
|
+
except OSError as exc:
|
|
282
|
+
raise _cliente.falha_de_escrita("escrever_linha", exc) from exc
|
|
283
|
+
_cliente.checar_escrita("escrever_linha", resposta)
|
|
284
|
+
atualizado = (resposta.json().get("updates") or {}).get("updatedRange", "")
|
|
285
|
+
return {"intervalo": atualizado if isinstance(atualizado, str) else ""}
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
# ── Drive ─────────────────────────────────────────────────────────────────────────────────
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
@PLUGIN.operacao
|
|
292
|
+
def listar_arquivos(
|
|
293
|
+
chamada: Any,
|
|
294
|
+
*,
|
|
295
|
+
pasta: str | None = None,
|
|
296
|
+
nome: str | None = None,
|
|
297
|
+
tipo: str | None = None,
|
|
298
|
+
limite: int = POR_PAGINA,
|
|
299
|
+
porta: int | None = None,
|
|
300
|
+
) -> list[dict[str, Any]]:
|
|
301
|
+
"""Os arquivos do Drive que a conexão vê (fora da lixeira), até ``limite``: os de dentro de
|
|
302
|
+
``pasta`` (o id), com ``nome`` no nome e do ``tipo`` (o MIME, como ``application/pdf``).
|
|
303
|
+
Cada um: ``id``, ``nome``, ``tipo``, ``tamanho`` (``None`` nos nativos do Google),
|
|
304
|
+
``modificado`` e ``pastas``."""
|
|
305
|
+
if not isinstance(limite, int) or isinstance(limite, bool) or not 0 < limite <= LIMITE_MAX:
|
|
306
|
+
raise ValueError(f"limite é um número de 1 a {LIMITE_MAX}")
|
|
307
|
+
filtros = ["trashed = false"]
|
|
308
|
+
if pasta is not None:
|
|
309
|
+
filtros.append(f"{literal_do_drive(_id(pasta, 'pasta'))} in parents")
|
|
310
|
+
if nome is not None:
|
|
311
|
+
filtros.append(f"name contains {literal_do_drive(nome)}")
|
|
312
|
+
if tipo is not None:
|
|
313
|
+
filtros.append(f"mimeType = {literal_do_drive(tipo)}")
|
|
314
|
+
cliente = _cliente_da_chamada(chamada, porta)
|
|
315
|
+
return _lendo("listar_arquivos", lambda: _buscar(cliente, " and ".join(filtros), limite))
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _buscar(cliente: Cliente, consulta: str, limite: int, **pedido: Any) -> list[dict[str, Any]]:
|
|
319
|
+
arquivos: list[dict[str, Any]] = []
|
|
320
|
+
pagina: str | None = None
|
|
321
|
+
while len(arquivos) < limite:
|
|
322
|
+
parametros = {
|
|
323
|
+
"q": consulta,
|
|
324
|
+
"fields": f"nextPageToken,files({_CAMPOS_DO_ARQUIVO})",
|
|
325
|
+
"pageSize": str(min(POR_PAGINA, limite - len(arquivos))),
|
|
326
|
+
"spaces": "drive",
|
|
327
|
+
}
|
|
328
|
+
if pagina:
|
|
329
|
+
parametros["pageToken"] = pagina
|
|
330
|
+
resposta = cliente.pedir("GET", DRIVE, "/drive/v3/files", parametros=parametros, **pedido)
|
|
331
|
+
_cliente.checar_leitura("listar_arquivos", resposta)
|
|
332
|
+
dados = resposta.json()
|
|
333
|
+
arquivos += [_arquivo(f) for f in dados.get("files") or [] if isinstance(f, dict)]
|
|
334
|
+
pagina = dados.get("nextPageToken")
|
|
335
|
+
if not isinstance(pagina, str) or not pagina:
|
|
336
|
+
break
|
|
337
|
+
return arquivos[:limite]
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
@PLUGIN.operacao
|
|
341
|
+
def baixar_arquivo(
|
|
342
|
+
chamada: Any,
|
|
343
|
+
arquivo: str,
|
|
344
|
+
*,
|
|
345
|
+
pasta: str = "google",
|
|
346
|
+
porta: int | None = None,
|
|
347
|
+
) -> dict[str, Any]:
|
|
348
|
+
"""Grava o arquivo ``arquivo`` (o id) em ``<pasta>/<nome>`` no diretório de trabalho (o nome
|
|
349
|
+
do Drive, limpo de separador e controle) e devolve ``id``, ``arquivo`` (o caminho gravado),
|
|
350
|
+
``tamanho`` e ``tipo``. O arquivo só aparece inteiro: o download que cai no meio não deixa
|
|
351
|
+
arquivo. Os nativos do Google (Docs, Planilhas) não se baixam: leia a planilha com
|
|
352
|
+
``ler_planilha``."""
|
|
353
|
+
identificador = _id(arquivo, "arquivo")
|
|
354
|
+
destino = _pasta_relativa(pasta)
|
|
355
|
+
cliente = _cliente_da_chamada(chamada, porta)
|
|
356
|
+
caminho = f"/drive/v3/files/{identificador}"
|
|
357
|
+
raiz = Path.cwd().resolve()
|
|
358
|
+
|
|
359
|
+
def ler() -> dict[str, Any]:
|
|
360
|
+
resposta = cliente.pedir("GET", DRIVE, caminho, parametros={"fields": _CAMPOS_DO_ARQUIVO})
|
|
361
|
+
_cliente.checar_leitura("baixar_arquivo", resposta)
|
|
362
|
+
dados = _arquivo(resposta.json())
|
|
363
|
+
if dados["tipo"].startswith(_NATIVO):
|
|
364
|
+
raise ErroDoGoogle(
|
|
365
|
+
"Google baixar_arquivo: é um arquivo nativo do Google (Docs, Planilhas), que não "
|
|
366
|
+
"se baixa como é; a planilha se lê com ler_planilha"
|
|
367
|
+
)
|
|
368
|
+
pasta_completa = raiz / destino
|
|
369
|
+
pasta_completa.mkdir(parents=True, exist_ok=True)
|
|
370
|
+
gravado = pasta_completa / _nome_de_arquivo(str(dados["nome"]))
|
|
371
|
+
parcial = pasta_completa / (gravado.name + ".parcial")
|
|
372
|
+
try:
|
|
373
|
+
conteudo = cliente.pedir(
|
|
374
|
+
"GET",
|
|
375
|
+
DRIVE,
|
|
376
|
+
caminho,
|
|
377
|
+
parametros={"alt": "media"},
|
|
378
|
+
para_arquivo=parcial,
|
|
379
|
+
tamanho_max=ARQUIVO_MAX,
|
|
380
|
+
)
|
|
381
|
+
if not 200 <= conteudo.status < 300:
|
|
382
|
+
_cliente.checar_leitura("baixar_arquivo", conteudo)
|
|
383
|
+
parcial.replace(gravado)
|
|
384
|
+
finally:
|
|
385
|
+
parcial.unlink(missing_ok=True)
|
|
386
|
+
return {
|
|
387
|
+
"id": identificador,
|
|
388
|
+
"arquivo": str(gravado.relative_to(raiz)),
|
|
389
|
+
"tamanho": conteudo.tamanho,
|
|
390
|
+
"tipo": dados["tipo"],
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
return _lendo("baixar_arquivo", ler)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
@PLUGIN.efeito
|
|
397
|
+
def enviar_arquivo(
|
|
398
|
+
chamada: Any,
|
|
399
|
+
arquivo: str | os.PathLike[str],
|
|
400
|
+
*,
|
|
401
|
+
nome: str | None = None,
|
|
402
|
+
pasta: str | None = None,
|
|
403
|
+
tipo: str | None = None,
|
|
404
|
+
porta: int | None = None,
|
|
405
|
+
) -> dict[str, Any]:
|
|
406
|
+
"""Envia um arquivo do diretório de trabalho (até 5 MB) para o Drive, só dentro de
|
|
407
|
+
``item.efetivar()``: na ``pasta`` (o id; sem ela, na raiz do Drive da conta), com ``nome``
|
|
408
|
+
(o do arquivo, se omitido) e o ``tipo`` (o MIME, adivinhado pelo nome). Devolve ``id``,
|
|
409
|
+
``nome`` e ``reaproveitado`` (``True`` quando o arquivo desta mesma chamada já estava lá).
|
|
410
|
+
|
|
411
|
+
Não duplica: o arquivo leva a marca da chamada (a chave do item, o nome da efetivação e a
|
|
412
|
+
ordem do envio no bloco), e antes de criar o plugin procura a marca. ``GoogleNaoSaiu``: nada
|
|
413
|
+
foi enviado (o Google recusou, a rede não abriu, a busca não respondeu). ``GoogleIncerto``:
|
|
414
|
+
um envio saiu sem confirmação e as tentativas acabaram sem achar o arquivo; depois dele,
|
|
415
|
+
nenhuma falha seguinte vira ``GoogleNaoSaiu``."""
|
|
416
|
+
caminho = _arquivo_do_workdir(arquivo)
|
|
417
|
+
nome_final = nome if nome is not None else caminho.name
|
|
418
|
+
if not isinstance(nome_final, str) or not nome_final.strip() or _CONTROLE.search(nome_final):
|
|
419
|
+
raise ValueError("nome é o nome do arquivo no Drive, sem quebra de linha nem controle")
|
|
420
|
+
if pasta is not None:
|
|
421
|
+
_id(pasta, "pasta")
|
|
422
|
+
if tipo is not None and (not isinstance(tipo, str) or not _MIME.fullmatch(tipo)):
|
|
423
|
+
raise ValueError("tipo é o MIME, como 'application/pdf'")
|
|
424
|
+
tipo = tipo or mimetypes.guess_type(nome_final)[0] or "application/octet-stream"
|
|
425
|
+
dados = caminho.read_bytes()
|
|
426
|
+
if len(dados) > ENVIO_MAX:
|
|
427
|
+
raise ValueError("arquivo passa de 5 MB: o envio desta versão é de um pedido só")
|
|
428
|
+
marca = chamada.idempotencia
|
|
429
|
+
cliente = _cliente_da_chamada(chamada, porta)
|
|
430
|
+
consulta = (
|
|
431
|
+
f"appProperties has {{ key={literal_do_drive(MARCA)} and "
|
|
432
|
+
f"value={literal_do_drive(marca)} }} and trashed = false"
|
|
433
|
+
)
|
|
434
|
+
metadados: dict[str, Any] = {
|
|
435
|
+
"name": nome_final,
|
|
436
|
+
"mimeType": tipo,
|
|
437
|
+
"appProperties": {MARCA: marca},
|
|
438
|
+
}
|
|
439
|
+
if pasta is not None:
|
|
440
|
+
metadados["parents"] = [pasta]
|
|
441
|
+
fronteira = "shade-" + secrets.token_hex(16)
|
|
442
|
+
corpo = _multipart(fronteira, metadados, tipo, dados)
|
|
443
|
+
incerto: GoogleIncerto | None = None
|
|
444
|
+
for _ in range(_cliente.TENTATIVAS):
|
|
445
|
+
try:
|
|
446
|
+
return _enviar_uma_vez(cliente, consulta, marca, corpo, fronteira)
|
|
447
|
+
except GoogleIncerto as exc:
|
|
448
|
+
# O pedido pode ter criado: a volta seguinte procura a marca antes de criar de novo.
|
|
449
|
+
incerto = exc
|
|
450
|
+
if not cliente.prazo.cabe(0):
|
|
451
|
+
break
|
|
452
|
+
except Exception as exc:
|
|
453
|
+
# Depois de um envio sem confirmação, nenhuma falha seguinte (a busca que não abriu,
|
|
454
|
+
# o 4xx, o token que não veio) diz que nada saiu: a dúvida da volta anterior segue.
|
|
455
|
+
if incerto is not None:
|
|
456
|
+
raise incerto from exc
|
|
457
|
+
raise
|
|
458
|
+
assert incerto is not None
|
|
459
|
+
raise incerto
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def _enviar_uma_vez(
|
|
463
|
+
cliente: Cliente, consulta: str, marca: str, corpo: bytes, fronteira: str
|
|
464
|
+
) -> dict[str, Any]:
|
|
465
|
+
"""Uma volta do envio: procura a marca e, sem ela, cria. ``GoogleNaoSaiu`` quando esta volta
|
|
466
|
+
certamente não criou nada; ``GoogleIncerto`` quando pode ter criado."""
|
|
467
|
+
try:
|
|
468
|
+
achados = _buscar(cliente, consulta, 1, idempotencia=marca)
|
|
469
|
+
except (ErroDoGoogle, OSError) as exc:
|
|
470
|
+
# Sem a busca, não se cria (o token que não veio já é um ``http.NadaSaiu``).
|
|
471
|
+
raise GoogleNaoSaiu(f"Google enviar_arquivo: a busca da marca falhou: {exc}") from exc
|
|
472
|
+
if achados:
|
|
473
|
+
return {"id": achados[0]["id"], "nome": achados[0]["nome"], "reaproveitado": True}
|
|
474
|
+
try:
|
|
475
|
+
resposta = cliente.pedir(
|
|
476
|
+
"POST",
|
|
477
|
+
DRIVE,
|
|
478
|
+
"/upload/drive/v3/files",
|
|
479
|
+
parametros={"uploadType": "multipart", "fields": "id,name"},
|
|
480
|
+
corpo=corpo,
|
|
481
|
+
tipo=f"multipart/related; boundary={fronteira}",
|
|
482
|
+
idempotencia=marca,
|
|
483
|
+
repetir_depois_do_envio=False,
|
|
484
|
+
)
|
|
485
|
+
except OSError as exc:
|
|
486
|
+
raise _cliente.falha_de_escrita("enviar_arquivo", exc) from exc
|
|
487
|
+
_cliente.checar_escrita("enviar_arquivo", resposta)
|
|
488
|
+
try:
|
|
489
|
+
criado = resposta.json()
|
|
490
|
+
except ErroDoGoogle as exc:
|
|
491
|
+
raise GoogleIncerto(
|
|
492
|
+
"Google enviar_arquivo: o Drive confirmou com um corpo ilegível; o arquivo pode estar "
|
|
493
|
+
"lá com a marca desta chamada",
|
|
494
|
+
status=resposta.status,
|
|
495
|
+
) from exc
|
|
496
|
+
return {"id": criado.get("id", ""), "nome": criado.get("name", ""), "reaproveitado": False}
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def _json(dados: Any) -> bytes:
|
|
500
|
+
import json
|
|
501
|
+
|
|
502
|
+
return json.dumps(dados, ensure_ascii=False).encode("utf-8")
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def _multipart(fronteira: str, metadados: dict[str, Any], tipo: str, dados: bytes) -> bytes:
|
|
506
|
+
"""O corpo ``multipart/related`` do upload do Drive: os metadados em JSON e o conteúdo. A
|
|
507
|
+
fronteira é aleatória e o JSON é serializado (nenhum texto do robô monta a estrutura)."""
|
|
508
|
+
inicio = (f"--{fronteira}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n").encode(
|
|
509
|
+
"ascii"
|
|
510
|
+
)
|
|
511
|
+
meio = f"\r\n--{fronteira}\r\nContent-Type: {tipo}\r\n\r\n".encode("latin-1")
|
|
512
|
+
fim = f"\r\n--{fronteira}--\r\n".encode("ascii")
|
|
513
|
+
return inicio + _json(metadados) + meio + dados + fim
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""O cliente HTTP das APIs do Google: o token da conexão, o prazo da chamada e a retentativa.
|
|
2
|
+
|
|
3
|
+
Fala com ``sheets.googleapis.com`` e ``www.googleapis.com`` (os hosts que o plugin declara),
|
|
4
|
+
com ``chamada.destino(host)`` antes de conectar. O certificado é verificado; o ``HTTPS_PROXY`` do
|
|
5
|
+
ambiente é respeitado (no sandbox, o proxy da allowlist). Não segue redirecionamento: o token
|
|
6
|
+
não vai a outro host.
|
|
7
|
+
|
|
8
|
+
O token vem de ``chamada.token(CONEXAO)``. O ``401`` (o token expirou ou foi revogado antes da
|
|
9
|
+
hora) troca o token uma vez (``renovar=True``) e repete: o pedido recusado não teve efeito.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import re
|
|
16
|
+
import ssl
|
|
17
|
+
import time
|
|
18
|
+
import urllib.error
|
|
19
|
+
import urllib.parse
|
|
20
|
+
import urllib.request
|
|
21
|
+
from collections.abc import Callable, Mapping
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from shade_sdk import http
|
|
27
|
+
|
|
28
|
+
from shade_plugins_google.erros import ErroDoGoogle, GoogleIncerto, GoogleNaoSaiu, NaoEncontrado
|
|
29
|
+
|
|
30
|
+
#: A conexão OAuth da plataforma de que o plugin pede o token (o provedor do catálogo).
|
|
31
|
+
CONEXAO = "google-drive"
|
|
32
|
+
SHEETS = "sheets.googleapis.com"
|
|
33
|
+
DRIVE = "www.googleapis.com"
|
|
34
|
+
#: Quantas vezes o pedido é tentado quando a rede ou o Google falham de forma transitória.
|
|
35
|
+
TENTATIVAS = 3
|
|
36
|
+
#: A espera antes da 2ª e da 3ª tentativa (a régua do ``shade_sdk.http``).
|
|
37
|
+
ESPERAS = (0.5, 1.0)
|
|
38
|
+
#: O teto do corpo de uma resposta que o plugin lê na memória (a planilha, a listagem).
|
|
39
|
+
RESPOSTA_MAX = 16 * 1024 * 1024
|
|
40
|
+
BLOCO = 1024 * 1024
|
|
41
|
+
#: O motivo que o Google põe no erro, como vai para a mensagem.
|
|
42
|
+
_MOTIVO = re.compile(r"^[A-Za-z_]{1,64}$")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Prazo:
|
|
46
|
+
"""O ``timeout`` da chamada como um prazo só: cada etapa usa o que sobrou."""
|
|
47
|
+
|
|
48
|
+
def __init__(self, segundos: float) -> None:
|
|
49
|
+
self.fim = time.monotonic() + segundos
|
|
50
|
+
|
|
51
|
+
def restante(self) -> float:
|
|
52
|
+
sobra = self.fim - time.monotonic()
|
|
53
|
+
if sobra <= 0:
|
|
54
|
+
raise TimeoutError("o prazo da chamada acabou")
|
|
55
|
+
return sobra
|
|
56
|
+
|
|
57
|
+
def cabe(self, espera: float) -> bool:
|
|
58
|
+
return self.fim - time.monotonic() > espera
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class _SemRedirecionamento(urllib.request.HTTPRedirectHandler):
|
|
62
|
+
def redirect_request(self, *args: Any, **kwargs: Any) -> None:
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _abridor() -> Callable[..., Any]:
|
|
67
|
+
contexto = ssl.create_default_context()
|
|
68
|
+
contexto.minimum_version = ssl.TLSVersion.TLSv1_2
|
|
69
|
+
return urllib.request.build_opener(
|
|
70
|
+
urllib.request.ProxyHandler(),
|
|
71
|
+
urllib.request.HTTPSHandler(context=contexto),
|
|
72
|
+
_SemRedirecionamento(),
|
|
73
|
+
).open
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass
|
|
77
|
+
class Resposta:
|
|
78
|
+
status: int
|
|
79
|
+
cabecalhos: Mapping[str, str]
|
|
80
|
+
corpo: bytes = b""
|
|
81
|
+
#: Onde o corpo foi gravado, quando o pedido pediu ``para_arquivo``.
|
|
82
|
+
arquivo: Path | None = None
|
|
83
|
+
tamanho: int = 0
|
|
84
|
+
motivo: str = field(default="")
|
|
85
|
+
|
|
86
|
+
def json(self) -> Any:
|
|
87
|
+
try:
|
|
88
|
+
return json.loads(self.corpo)
|
|
89
|
+
except ValueError as exc:
|
|
90
|
+
raise ErroDoGoogle("Google: a resposta não é JSON", status=self.status) from exc
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def motivo_do_erro(corpo: bytes) -> str:
|
|
94
|
+
"""O motivo do erro do Google (``error.status`` ou ``error.errors[0].reason``), só se for um
|
|
95
|
+
nome curto: nunca o texto da mensagem, que pode repetir o pedido."""
|
|
96
|
+
try:
|
|
97
|
+
erro = json.loads(corpo[:65536]).get("error") or {}
|
|
98
|
+
except (ValueError, AttributeError):
|
|
99
|
+
return ""
|
|
100
|
+
candidatos = [erro.get("status")]
|
|
101
|
+
detalhes = erro.get("errors")
|
|
102
|
+
if isinstance(detalhes, list) and detalhes and isinstance(detalhes[0], dict):
|
|
103
|
+
candidatos.append(detalhes[0].get("reason"))
|
|
104
|
+
for candidato in candidatos:
|
|
105
|
+
if isinstance(candidato, str) and _MOTIVO.fullmatch(candidato):
|
|
106
|
+
return candidato
|
|
107
|
+
return ""
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def transitorio(exc: BaseException) -> bool:
|
|
111
|
+
"""Falha de rede em que repetir pode dar certo. O certificado inválido e o prazo esgotado,
|
|
112
|
+
não."""
|
|
113
|
+
if isinstance(exc, TimeoutError):
|
|
114
|
+
return False
|
|
115
|
+
return isinstance(exc, urllib.error.URLError | ConnectionError | ssl.SSLError) and not (
|
|
116
|
+
isinstance(exc, urllib.error.URLError)
|
|
117
|
+
and isinstance(exc.reason, ssl.SSLCertVerificationError)
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@dataclass
|
|
122
|
+
class Cliente:
|
|
123
|
+
chamada: Any
|
|
124
|
+
prazo: Prazo
|
|
125
|
+
porta: int | None = None
|
|
126
|
+
_token: str | None = None
|
|
127
|
+
_renovou: bool = False
|
|
128
|
+
|
|
129
|
+
def url(self, host: str, caminho: str, parametros: Mapping[str, str] | None = None) -> str:
|
|
130
|
+
endereco = host if self.porta in (None, 443) else f"{host}:{self.porta}"
|
|
131
|
+
consulta = urllib.parse.urlencode(dict(parametros or {}), quote_via=urllib.parse.quote)
|
|
132
|
+
return f"https://{endereco}{caminho}" + (f"?{consulta}" if consulta else "")
|
|
133
|
+
|
|
134
|
+
def _bearer(self, *, renovar: bool = False) -> str:
|
|
135
|
+
if self._token is None or renovar:
|
|
136
|
+
self._token = self.chamada.token(CONEXAO, renovar=renovar)
|
|
137
|
+
return self._token
|
|
138
|
+
|
|
139
|
+
def pedir(
|
|
140
|
+
self,
|
|
141
|
+
metodo: str,
|
|
142
|
+
host: str,
|
|
143
|
+
caminho: str,
|
|
144
|
+
*,
|
|
145
|
+
parametros: Mapping[str, str] | None = None,
|
|
146
|
+
corpo: bytes | None = None,
|
|
147
|
+
tipo: str | None = None,
|
|
148
|
+
para_arquivo: Path | None = None,
|
|
149
|
+
tamanho_max: int = RESPOSTA_MAX,
|
|
150
|
+
idempotencia: str | None = None,
|
|
151
|
+
repetir_depois_do_envio: bool = True,
|
|
152
|
+
) -> Resposta:
|
|
153
|
+
"""Um pedido com o token da conexão, dentro do prazo. Repete a falha transitória de rede,
|
|
154
|
+
o ``429`` e o ``5xx`` quando ``repetir_depois_do_envio`` (a leitura); senão, só o que
|
|
155
|
+
certamente não saiu (a rede que recusou antes do envio, o ``429``). O ``401`` troca o
|
|
156
|
+
token uma vez e repete. ``idempotencia`` vai no ``Idempotency-Key``, como o
|
|
157
|
+
``shade_sdk.http`` faz nas escritas: o Google o ignora, e quem observa o tráfego (o proxy,
|
|
158
|
+
o servidor falso) distingue a execução."""
|
|
159
|
+
self.chamada.destino(host)
|
|
160
|
+
url = self.url(host, caminho, parametros)
|
|
161
|
+
abrir = _abridor()
|
|
162
|
+
ultima_falha: BaseException | None = None
|
|
163
|
+
ultima_resposta: Resposta | None = None
|
|
164
|
+
tentativa = 0
|
|
165
|
+
while tentativa < TENTATIVAS:
|
|
166
|
+
if tentativa:
|
|
167
|
+
espera = ESPERAS[min(tentativa - 1, len(ESPERAS) - 1)]
|
|
168
|
+
if not self.prazo.cabe(espera):
|
|
169
|
+
break
|
|
170
|
+
time.sleep(espera)
|
|
171
|
+
tentativa += 1
|
|
172
|
+
cabecalhos = {"Authorization": f"Bearer {self._bearer()}", "Accept": "application/json"}
|
|
173
|
+
if tipo:
|
|
174
|
+
cabecalhos["Content-Type"] = tipo
|
|
175
|
+
if idempotencia:
|
|
176
|
+
cabecalhos["Idempotency-Key"] = idempotencia
|
|
177
|
+
pedido = urllib.request.Request(url, data=corpo, headers=cabecalhos, method=metodo)
|
|
178
|
+
try:
|
|
179
|
+
resposta = self._despachar(abrir, pedido, para_arquivo, tamanho_max)
|
|
180
|
+
except Exception as exc:
|
|
181
|
+
if not transitorio(exc) or not (repetir_depois_do_envio or http.nada_saiu(exc)):
|
|
182
|
+
raise
|
|
183
|
+
ultima_falha, ultima_resposta = exc, None
|
|
184
|
+
continue
|
|
185
|
+
if resposta.status == 401 and not self._renovou:
|
|
186
|
+
# O token venceu antes da hora ou foi revogado: o pedido não teve efeito.
|
|
187
|
+
self._renovou = True
|
|
188
|
+
self._bearer(renovar=True)
|
|
189
|
+
tentativa -= 1
|
|
190
|
+
continue
|
|
191
|
+
if resposta.status == 429 or (resposta.status >= 500 and repetir_depois_do_envio):
|
|
192
|
+
ultima_falha, ultima_resposta = None, resposta
|
|
193
|
+
continue
|
|
194
|
+
return resposta
|
|
195
|
+
if ultima_resposta is not None:
|
|
196
|
+
return ultima_resposta
|
|
197
|
+
if ultima_falha is None:
|
|
198
|
+
raise TimeoutError("o prazo da chamada acabou")
|
|
199
|
+
raise ultima_falha
|
|
200
|
+
|
|
201
|
+
def _despachar(
|
|
202
|
+
self, abrir: Callable[..., Any], pedido: Any, para_arquivo: Path | None, tamanho_max: int
|
|
203
|
+
) -> Resposta:
|
|
204
|
+
try:
|
|
205
|
+
with abrir(pedido, timeout=self.prazo.restante()) as resposta:
|
|
206
|
+
return self._ler(resposta, resposta.status, para_arquivo, tamanho_max)
|
|
207
|
+
except urllib.error.HTTPError as exc:
|
|
208
|
+
corpo = exc.read(65536) if exc.fp else b""
|
|
209
|
+
return Resposta(
|
|
210
|
+
exc.code, dict(exc.headers.items()), corpo, motivo=motivo_do_erro(corpo)
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
def _ler(
|
|
214
|
+
self, resposta: Any, status: int, para_arquivo: Path | None, tamanho_max: int
|
|
215
|
+
) -> Resposta:
|
|
216
|
+
cabecalhos = dict(resposta.headers.items())
|
|
217
|
+
if para_arquivo is None:
|
|
218
|
+
corpo = resposta.read(tamanho_max + 1)
|
|
219
|
+
if len(corpo) > tamanho_max:
|
|
220
|
+
raise ErroDoGoogle("Google: a resposta passa do teto de leitura")
|
|
221
|
+
return Resposta(status, cabecalhos, corpo, tamanho=len(corpo))
|
|
222
|
+
tamanho = 0
|
|
223
|
+
with para_arquivo.open("wb") as saida:
|
|
224
|
+
while bloco := resposta.read(BLOCO):
|
|
225
|
+
tamanho += len(bloco)
|
|
226
|
+
if tamanho > tamanho_max:
|
|
227
|
+
raise ErroDoGoogle("Google: o arquivo passa do teto de download")
|
|
228
|
+
saida.write(bloco)
|
|
229
|
+
self.prazo.restante()
|
|
230
|
+
esperado = cabecalhos.get("Content-Length", "")
|
|
231
|
+
if esperado.isdigit() and int(esperado) != tamanho:
|
|
232
|
+
# O ``read`` devolve vazio, sem levantar, quando a conexão cai no meio do corpo.
|
|
233
|
+
raise ErroDoGoogle(
|
|
234
|
+
f"Google: o download veio incompleto ({tamanho} de {esperado} bytes)"
|
|
235
|
+
)
|
|
236
|
+
return Resposta(status, cabecalhos, arquivo=para_arquivo, tamanho=tamanho)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _descricao(resposta: Resposta) -> str:
|
|
240
|
+
return f"{resposta.status} {resposta.motivo}".strip()
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def checar_leitura(operacao: str, resposta: Resposta) -> None:
|
|
244
|
+
if 200 <= resposta.status < 300:
|
|
245
|
+
return
|
|
246
|
+
if resposta.status == 404:
|
|
247
|
+
raise NaoEncontrado(
|
|
248
|
+
f"Google {operacao}: não existe, ou a conta conectada não o vê "
|
|
249
|
+
f"({_descricao(resposta)}); no Drive, o app vê só o que enviou ou o que a conta "
|
|
250
|
+
"abriu com ele",
|
|
251
|
+
status=404,
|
|
252
|
+
)
|
|
253
|
+
if resposta.status == 403:
|
|
254
|
+
raise ErroDoGoogle(
|
|
255
|
+
f"Google {operacao}: a conta conectada não tem permissão ({_descricao(resposta)}); "
|
|
256
|
+
"compartilhe a planilha ou o arquivo com ela",
|
|
257
|
+
status=403,
|
|
258
|
+
)
|
|
259
|
+
raise ErroDoGoogle(
|
|
260
|
+
f"Google {operacao}: o Google devolveu {_descricao(resposta)}", status=resposta.status
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def checar_escrita(operacao: str, resposta: Resposta) -> None:
|
|
265
|
+
if 200 <= resposta.status < 300:
|
|
266
|
+
return
|
|
267
|
+
if 400 <= resposta.status < 500:
|
|
268
|
+
# O 429 também: o Google limitou antes de aplicar, e o cliente já tentou de novo.
|
|
269
|
+
raise GoogleNaoSaiu(
|
|
270
|
+
f"Google {operacao}: o Google recusou o pedido ({_descricao(resposta)})",
|
|
271
|
+
status=resposta.status,
|
|
272
|
+
)
|
|
273
|
+
raise GoogleIncerto(
|
|
274
|
+
f"Google {operacao}: o Google devolveu {_descricao(resposta)}", status=resposta.status
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def falha_de_leitura(operacao: str, exc: BaseException) -> ErroDoGoogle:
|
|
279
|
+
return ErroDoGoogle(f"Google {operacao}: a conexão falhou ({type(exc).__name__})")
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def falha_de_escrita(operacao: str, exc: BaseException) -> Exception:
|
|
283
|
+
if http.nada_saiu(exc):
|
|
284
|
+
return GoogleNaoSaiu(f"Google {operacao}: a conexão não abriu ({type(exc).__name__})")
|
|
285
|
+
return GoogleIncerto(
|
|
286
|
+
f"Google {operacao}: a conexão falhou depois do envio ({type(exc).__name__}); "
|
|
287
|
+
"a escrita pode ter chegado"
|
|
288
|
+
)
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Os erros do plugin ``google``.
|
|
2
|
+
|
|
3
|
+
Separam o que **certamente não chegou** ao Google (``GoogleNaoSaiu``, um ``http.NadaSaiu``) do
|
|
4
|
+
que **pode ter chegado** (``GoogleIncerto``, um ``http.ResultadoIncerto``). O token que não veio
|
|
5
|
+
é o ``TokenIndisponivel`` do ``shade_sdk.plugins`` (também um ``http.NadaSaiu``).
|
|
6
|
+
|
|
7
|
+
As mensagens dizem a operação, o status HTTP e o motivo que o Google dá (``PERMISSION_DENIED``,
|
|
8
|
+
``insufficientPermissions``), nunca o corpo, o conteúdo da planilha nem o token.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from shade_sdk import http
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ErroDoGoogle(Exception):
|
|
17
|
+
"""A leitura não deu certo: conexão, TLS, permissão ou o Google 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(ErroDoGoogle):
|
|
25
|
+
"""A planilha, a aba ou o arquivo não existe, ou a conta conectada não o vê (404)."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class GoogleNaoSaiu(http.NadaSaiu):
|
|
29
|
+
"""Certamente sem efeito: o Google recusou o pedido (4xx, inclusive o 429 que sobrou das
|
|
30
|
+
retentativas) ou a rede falhou antes de enviá-lo."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class GoogleIncerto(http.ResultadoIncerto):
|
|
34
|
+
"""Pode ter tido efeito: o pedido foi enviado e a resposta não veio, veio com erro do
|
|
35
|
+
servidor (5xx) ou não se leu. Conferir antes de refazer: a linha pode ter entrado na
|
|
36
|
+
planilha, e o arquivo pode estar no Drive."""
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: shade-plugins-google
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Ler e escrever no Google Sheets e listar, baixar e enviar no Google Drive, 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-google
|
|
13
|
+
|
|
14
|
+
Lê e escreve no Google Sheets e lista, baixa e envia arquivos no Google Drive de dentro de um robô
|
|
15
|
+
do [`shade-sdk`](https://pypi.org/project/shade-sdk/). A conta Google é a conexão OAuth da
|
|
16
|
+
plataforma: o robô recebe só o token de acesso, sob demanda, e nunca vê a senha nem o refresh
|
|
17
|
+
token. Só a biblioteca padrão do Python: nenhuma dependência além do `shade-sdk`.
|
|
18
|
+
|
|
19
|
+
No `shade.toml` do robô, os hosts das APIs vão em `[hosts] permitidos` e a conexão em `[conexoes]`:
|
|
20
|
+
|
|
21
|
+
```toml
|
|
22
|
+
[hosts]
|
|
23
|
+
permitidos = ["sheets.googleapis.com", "www.googleapis.com"]
|
|
24
|
+
|
|
25
|
+
[conexoes]
|
|
26
|
+
nomes = ["google-drive"]
|
|
27
|
+
|
|
28
|
+
[plugins]
|
|
29
|
+
google = "0.1.0"
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
import shade_plugins_google as google
|
|
34
|
+
|
|
35
|
+
# Leitura: a qualquer momento, inclusive no ensaio.
|
|
36
|
+
for pedido in google.ler_planilha("1AbC...", "Pedidos!A1:D"): # uma linha por dict
|
|
37
|
+
...
|
|
38
|
+
for arquivo in google.listar_arquivos(nome="comprovante", tipo="application/pdf"):
|
|
39
|
+
google.baixar_arquivo(arquivo["id"]) # grava em google/<nome> no diretório de trabalho
|
|
40
|
+
|
|
41
|
+
# Escrita: só dentro de item.efetivar() (no ensaio não roda).
|
|
42
|
+
with item.efetivar("registrar na planilha"):
|
|
43
|
+
google.escrever_linha("1AbC...", "Pedidos!A1", [item["pedido"], item["cliente"], "ok"])
|
|
44
|
+
|
|
45
|
+
with item.efetivar("guardar o comprovante"):
|
|
46
|
+
google.enviar_arquivo("comprovante.pdf", pasta="1XyZ...")
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## A conta e o escopo
|
|
50
|
+
|
|
51
|
+
- Na plataforma, conecte a conta em **Conectores → Google Drive**. O robô usa a conexão de quem
|
|
52
|
+
aprovou a versão dele; no ensaio antes da aprovação, a de quem a enviou.
|
|
53
|
+
- A conexão pede os escopos `spreadsheets` (qualquer planilha que a conta veja) e `drive.file`
|
|
54
|
+
(no Drive, só o que o próprio app enviou ou que a conta abriu com ele: `listar_arquivos` e
|
|
55
|
+
`baixar_arquivo` não veem o resto do Drive, e a `pasta` de `enviar_arquivo` também tem de ser
|
|
56
|
+
uma que o app vê). Uma conexão feita antes de o escopo `spreadsheets` existir precisa ser
|
|
57
|
+
refeita.
|
|
58
|
+
- No laptop (`shade run`), ponha um token de acesso da sua conta em `SHADE_TOKEN_GOOGLE_DRIVE`
|
|
59
|
+
(no `.env`). O do Google costuma valer uma hora, e o laptop não renova.
|
|
60
|
+
|
|
61
|
+
## O que o plugin garante
|
|
62
|
+
|
|
63
|
+
- **Um envio, um arquivo:** `enviar_arquivo` marca o arquivo com uma chave derivada do item, do
|
|
64
|
+
nome da efetivação e da ordem do envio, e procura a marca antes de criar. A retentativa e uma
|
|
65
|
+
nova execução do mesmo item acham o arquivo que já subiu, em vez de criar outro, enquanto a
|
|
66
|
+
busca do Drive o enxergar: logo depois de um envio sem confirmação, a busca pode ainda não
|
|
67
|
+
vê-lo. Por isso o envio sem confirmação é `GoogleIncerto` e o item fica retido para
|
|
68
|
+
conferência.
|
|
69
|
+
- **Linha sem duplicata escondida:** o Sheets não reconhece repetição, então `escrever_linha` só
|
|
70
|
+
repete o que certamente não chegou (a conexão recusada, o `429`). Se o pedido saiu e a
|
|
71
|
+
confirmação não veio, o erro é `GoogleIncerto` e o item fica retido para conferência.
|
|
72
|
+
- **Texto é texto:** `escrever_linha` grava cru (`RAW`): `=HYPERLINK(...)` vira texto, nunca
|
|
73
|
+
fórmula.
|
|
74
|
+
- **Token renovado pela plataforma:** o `401` troca o token uma vez e repete o pedido, que não
|
|
75
|
+
teve efeito. O `429` que sobra das retentativas é `GoogleNaoSaiu`: o Google limitou antes de
|
|
76
|
+
aplicar.
|
|
77
|
+
- **Prazo:** `timeout=` (30 s) vale para a chamada inteira, retentativas incluídas. Cada chamada
|
|
78
|
+
vira um evento com a operação, o host, a duração e o status, sem conteúdo nem token.
|
|
79
|
+
|
|
80
|
+
## Limites desta versão
|
|
81
|
+
|
|
82
|
+
- O envio é de um pedido só, até 5 MB.
|
|
83
|
+
- Arquivos nativos do Google (Docs, Planilhas, Apresentações) não se baixam; a planilha se lê com
|
|
84
|
+
`ler_planilha`.
|
|
85
|
+
|
|
86
|
+
Licença Apache-2.0.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
shade_plugins_google/__init__.py,sha256=twhEGSK5XM6mKaHLKY_8ZDmdbfInmPJ_3Gn9LEuuLtk,21829
|
|
2
|
+
shade_plugins_google/_cliente.py,sha256=G9xzskTlQgAORdqbUziJhxDmQHsoRl8P1yslrsKyF4I,11453
|
|
3
|
+
shade_plugins_google/erros.py,sha256=V9yHsKkRV6PI7-c6uZ6gp-DU7p0QWP6LBVoau87LivM,1426
|
|
4
|
+
shade_plugins_google-0.1.0.dist-info/METADATA,sha256=zdDVlHmRh33Rp3qEF_eCAuM6UjTteCL4T8zkT0ELzhM,3986
|
|
5
|
+
shade_plugins_google-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
6
|
+
shade_plugins_google-0.1.0.dist-info/entry_points.txt,sha256=kLhU1O4Q9YkM8ZA4S5f5iDXFb8QcbKXMQzqPj0hR8b0,57
|
|
7
|
+
shade_plugins_google-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
8
|
+
shade_plugins_google-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.
|