shade-plugins-slack 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.
@@ -0,0 +1,307 @@
1
+ """O plugin ``slack``: listar os canais e enviar mensagem no Slack, pela Web API, sob o contrato de
2
+ plugin do shade-sdk, com o token OAuth da conexão da plataforma.
3
+
4
+ ```toml
5
+ [hosts]
6
+ permitidos = ["slack.com"]
7
+
8
+ [conexoes]
9
+ nomes = ["slack"]
10
+
11
+ [plugins]
12
+ slack = "0.1.0"
13
+ ```
14
+
15
+ ```python
16
+ import shade_plugins_slack as slack
17
+
18
+ canal = next(c["id"] for c in slack.listar_canais() if c["nome"] == "financeiro")
19
+
20
+ with item.efetivar("avisar o time"):
21
+ slack.enviar_mensagem(canal, f"Pedido {item['pedido']} conferido.")
22
+ ```
23
+
24
+ - **Conta:** a conexão ``slack`` da plataforma (Conectores). O robô nunca vê a senha nem o
25
+ refresh token: o token de acesso chega sob demanda e é renovado pela plataforma. No laptop, ponha
26
+ um token de acesso em ``SHADE_TOKEN_SLACK``. Os escopos são ``channels:read``, ``chat:write`` e
27
+ ``channels:history``; o app precisa estar no canal para ler o histórico e postar.
28
+ - **Ler não muda nada:** ``listar_canais`` roda inclusive no ensaio.
29
+ - **Escrever só dentro de** ``item.efetivar()`` (no ensaio não roda). ``enviar_mensagem`` não
30
+ duplica: a mensagem leva no ``metadata`` a chave do item, e antes de postar o plugin lê o
31
+ histórico recente do canal e devolve a mensagem que já tiver a chave. Depois que o envio saiu
32
+ sem confirmação, o plugin não posta de novo: ele confere o histórico e, sem achar, o erro é
33
+ ``SlackIncerto`` (o item fica retido para conferência).
34
+ - **Prazo:** ``timeout=`` (30 s) vale para a chamada inteira, retentativas incluídas.
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import re
40
+ from collections.abc import Callable
41
+ from typing import Any
42
+
43
+ from shade_sdk.plugins import Plugin
44
+
45
+ from shade_plugins_slack import _cliente
46
+ from shade_plugins_slack._cliente import CONEXAO, SLACK, Cliente, Prazo
47
+ from shade_plugins_slack.erros import ErroDoSlack, NaoEncontrado, SlackIncerto, SlackNaoSaiu
48
+
49
+ __version__ = "0.1.0"
50
+
51
+ #: O ``event_type`` do ``metadata`` das mensagens do plugin: o histórico se lê por ele.
52
+ EVENTO_DA_MENSAGEM = "shade_item"
53
+ #: Quantos canais ``listar_canais`` devolve, no máximo, e quantos o Slack dá por página.
54
+ LIMITE_CANAIS_MAX = 10_000
55
+ POR_PAGINA = 200
56
+ #: Quantas páginas de canais e de histórico o plugin percorre.
57
+ PAGINAS_DE_CANAIS_MAX = 50
58
+ #: O histórico recente que se lê atrás da chave antes de postar: 5 páginas de 100 mensagens.
59
+ PAGINAS_DE_HISTORICO = 5
60
+ POR_PAGINA_DE_HISTORICO = 100
61
+ #: O teto do texto (o Slack corta em 40 000 caracteres).
62
+ TEXTO_MAX = 40_000
63
+ _CONTROLE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
64
+ #: O id de um canal público (``C...``), privado ou grupo antigo (``G...``) ou conversa (``D...``).
65
+ _CANAL = re.compile(r"^[CGD][A-Z0-9]{6,30}$")
66
+ _CURSOR = re.compile(r"^[A-Za-z0-9+/=_\-%.]{1,512}$")
67
+
68
+ PLUGIN = Plugin(
69
+ "slack",
70
+ __version__,
71
+ shade_sdk=">=0.22.3,<0.23",
72
+ dono="Equipe de integrações da ShadeOne",
73
+ hosts=[SLACK],
74
+ conexoes=[CONEXAO],
75
+ )
76
+
77
+ __all__ = [
78
+ "PLUGIN",
79
+ "ErroDoSlack",
80
+ "NaoEncontrado",
81
+ "SlackIncerto",
82
+ "SlackNaoSaiu",
83
+ "enviar_mensagem",
84
+ "listar_canais",
85
+ ]
86
+
87
+
88
+ def _porta(porta: Any) -> int | None:
89
+ if porta is not None and (
90
+ not isinstance(porta, int) or isinstance(porta, bool) or not 0 < porta < 65536
91
+ ):
92
+ raise ValueError(f"porta é um número de 1 a 65535, não {porta!r}")
93
+ return porta
94
+
95
+
96
+ def _canal(valor: Any) -> str:
97
+ if not isinstance(valor, str) or not _CANAL.fullmatch(valor):
98
+ raise ValueError(
99
+ "canal é o id do canal (como C0123ABCD, o que listar_canais devolve), não o nome"
100
+ )
101
+ return valor
102
+
103
+
104
+ def _limite(valor: Any, maximo: int) -> int:
105
+ if not isinstance(valor, int) or isinstance(valor, bool) or not 0 < valor <= maximo:
106
+ raise ValueError(f"limite é um número de 1 a {maximo}")
107
+ return valor
108
+
109
+
110
+ def _texto_do_slack(texto: Any) -> str:
111
+ """O texto do item como o Slack o quer: ``&``, ``<`` e ``>`` viram as entidades que a Web API
112
+ documenta, para que ``<!channel>``, ``<@U123>`` e ``<http://...|texto>`` que vierem de um dado
113
+ não virem menção nem link."""
114
+ if not isinstance(texto, str) or not texto.strip() or len(texto) > TEXTO_MAX:
115
+ raise ValueError(f"texto é uma mensagem de 1 a {TEXTO_MAX} caracteres")
116
+ if _CONTROLE.search(texto):
117
+ raise ValueError("texto não pode ter caractere de controle (a não ser quebra de linha)")
118
+ return texto.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
119
+
120
+
121
+ def _cliente_da_chamada(chamada: Any, porta: Any) -> Cliente:
122
+ return Cliente(chamada=chamada, prazo=Prazo(chamada.timeout), porta=_porta(porta))
123
+
124
+
125
+ def _lendo(operacao: str, funcao: Callable[[], Any]) -> Any:
126
+ """A falha de rede no meio da leitura vira ``ErroDoSlack``."""
127
+ try:
128
+ return funcao()
129
+ except ErroDoSlack:
130
+ raise
131
+ except OSError as exc:
132
+ raise _cliente.falha_de_leitura(operacao, exc) from exc
133
+
134
+
135
+ def _proximo_cursor(dados: dict[str, Any]) -> str:
136
+ meta = dados.get("response_metadata")
137
+ cursor = meta.get("next_cursor") if isinstance(meta, dict) else ""
138
+ return cursor if isinstance(cursor, str) and _CURSOR.fullmatch(cursor) else ""
139
+
140
+
141
+ # ── Canais ───────────────────────────────────────────────────────────────────────────────
142
+
143
+
144
+ def _resumo_do_canal(canal: dict[str, Any]) -> dict[str, Any]:
145
+ membros = canal.get("num_members")
146
+ return {
147
+ "id": canal.get("id", ""),
148
+ "nome": canal.get("name", ""),
149
+ "arquivado": bool(canal.get("is_archived")),
150
+ "membro": bool(canal.get("is_member")),
151
+ "membros": membros if isinstance(membros, int) and not isinstance(membros, bool) else None,
152
+ }
153
+
154
+
155
+ @PLUGIN.operacao
156
+ def listar_canais(
157
+ chamada: Any,
158
+ *,
159
+ limite: int = 1_000,
160
+ arquivados: bool = False,
161
+ porta: int | None = None,
162
+ ) -> list[dict[str, Any]]:
163
+ """Os canais públicos do workspace, até ``limite``, seguindo o cursor do Slack. Cada um: ``id``
164
+ (o que ``enviar_mensagem`` pede), ``nome``, ``arquivado``, ``membro`` (o app está no canal) e
165
+ ``membros``. ``arquivados=True`` inclui os arquivados. Nada muda no Slack."""
166
+ limite = _limite(limite, LIMITE_CANAIS_MAX)
167
+ if not isinstance(arquivados, bool):
168
+ raise ValueError("arquivados é verdadeiro ou falso")
169
+ cliente = _cliente_da_chamada(chamada, porta)
170
+
171
+ def ler() -> list[dict[str, Any]]:
172
+ achados: list[dict[str, Any]] = []
173
+ cursor = ""
174
+ for _ in range(PAGINAS_DE_CANAIS_MAX):
175
+ parametros = {
176
+ "types": "public_channel",
177
+ "exclude_archived": "false" if arquivados else "true",
178
+ "limit": str(min(POR_PAGINA, limite)),
179
+ }
180
+ if cursor:
181
+ parametros["cursor"] = cursor
182
+ resposta = cliente.pedir("conversations.list", parametros=parametros)
183
+ dados = _cliente.checar_leitura("listar_canais", resposta)
184
+ for canal in dados.get("channels") or []:
185
+ if isinstance(canal, dict):
186
+ achados.append(_resumo_do_canal(canal))
187
+ if len(achados) >= limite:
188
+ return achados
189
+ proximo = _proximo_cursor(dados)
190
+ if not proximo or proximo == cursor:
191
+ break
192
+ cursor = proximo
193
+ return achados
194
+
195
+ return _lendo("listar_canais", ler)
196
+
197
+
198
+ # ── Mensagem ─────────────────────────────────────────────────────────────────────────────
199
+
200
+
201
+ def _mensagem_com_a_chave(cliente: Cliente, canal: str, chave: str) -> dict[str, Any] | None:
202
+ """A mensagem recente do canal cujo ``metadata`` leva esta chave. Sem ler o histórico não se
203
+ posta: a falha daqui é ``SlackNaoSaiu`` (o token que não veio já é um ``http.NadaSaiu``)."""
204
+ cursor = ""
205
+ for _ in range(PAGINAS_DE_HISTORICO):
206
+ parametros = {
207
+ "channel": canal,
208
+ "limit": str(POR_PAGINA_DE_HISTORICO),
209
+ "include_all_metadata": "true",
210
+ }
211
+ if cursor:
212
+ parametros["cursor"] = cursor
213
+ try:
214
+ resposta = cliente.pedir(
215
+ "conversations.history", parametros=parametros, idempotencia=chave
216
+ )
217
+ if not resposta.ok:
218
+ raise _cliente.recusa_antes_de_postar("enviar_mensagem", resposta)
219
+ dados = resposta.dados()
220
+ except (ErroDoSlack, OSError) as exc:
221
+ if isinstance(exc, SlackNaoSaiu):
222
+ raise
223
+ raise SlackNaoSaiu(
224
+ f"Slack enviar_mensagem: o histórico do canal não foi lido ({type(exc).__name__}); "
225
+ "nada foi postado"
226
+ ) from exc
227
+ for mensagem in dados.get("messages") or []:
228
+ if _leva_a_chave(mensagem, chave):
229
+ return mensagem
230
+ proximo = _proximo_cursor(dados)
231
+ if not dados.get("has_more") or not proximo or proximo == cursor:
232
+ break
233
+ cursor = proximo
234
+ return None
235
+
236
+
237
+ def _leva_a_chave(mensagem: Any, chave: str) -> bool:
238
+ if not isinstance(mensagem, dict):
239
+ return False
240
+ metadata = mensagem.get("metadata")
241
+ if not isinstance(metadata, dict) or metadata.get("event_type") != EVENTO_DA_MENSAGEM:
242
+ return False
243
+ payload = metadata.get("event_payload")
244
+ return isinstance(payload, dict) and payload.get("chave") == chave
245
+
246
+
247
+ def _resultado(canal: str, ts: Any, *, reaproveitada: bool) -> dict[str, Any]:
248
+ return {"canal": canal, "ts": ts if isinstance(ts, str) else "", "reaproveitada": reaproveitada}
249
+
250
+
251
+ def _postar(cliente: Cliente, canal: str, texto: str, chave: str) -> dict[str, Any]:
252
+ """O ``chat.postMessage``. Depois de despachado, nada o repete: a dúvida confere o histórico
253
+ e, sem achar, é ``SlackIncerto``."""
254
+ corpo = {
255
+ "channel": canal,
256
+ "text": texto,
257
+ "mrkdwn": False,
258
+ "metadata": {"event_type": EVENTO_DA_MENSAGEM, "event_payload": {"chave": chave}},
259
+ }
260
+ try:
261
+ resposta = cliente.pedir(
262
+ "chat.postMessage", corpo=corpo, idempotencia=chave, repetir_depois_do_envio=False
263
+ )
264
+ dados = _cliente.checar_escrita("enviar_mensagem", resposta)
265
+ return _resultado(canal, dados.get("ts"), reaproveitada=False)
266
+ except SlackIncerto as incerto:
267
+ duvida: Exception = incerto
268
+ except OSError as exc:
269
+ duvida = _cliente.falha_de_escrita("enviar_mensagem", exc)
270
+ if isinstance(duvida, SlackNaoSaiu):
271
+ raise duvida from exc
272
+ # A mensagem pode ter saído: o que a confirma é o histórico.
273
+ try:
274
+ achada = _mensagem_com_a_chave(cliente, canal, chave)
275
+ except SlackNaoSaiu:
276
+ achada = None
277
+ if achada is None:
278
+ raise duvida
279
+ return _resultado(canal, achada.get("ts"), reaproveitada=True)
280
+
281
+
282
+ @PLUGIN.efeito
283
+ def enviar_mensagem(
284
+ chamada: Any,
285
+ canal: str,
286
+ texto: str,
287
+ *,
288
+ porta: int | None = None,
289
+ ) -> dict[str, Any]:
290
+ """Posta ``texto`` no canal (o id que ``listar_canais`` devolve), só dentro de
291
+ ``item.efetivar()``. O texto é literal: ``&``, ``<`` e ``>`` vão como entidade, e menção ou
292
+ link vindos de um dado não disparam. Devolve ``canal``, ``ts`` (o id da mensagem no canal) e
293
+ ``reaproveitada`` (``True`` quando a mensagem desta mesma chamada já estava no histórico).
294
+
295
+ Não duplica: a mensagem leva a chave do item no ``metadata`` e, antes de postar, o plugin lê as
296
+ últimas mensagens do canal e devolve a que tiver a chave. ``SlackNaoSaiu``: nada foi postado
297
+ (o Slack recusou, a rede não abriu, o histórico não foi lido, inclusive a conexão sem
298
+ ``channels:history``). ``SlackIncerto``: o envio saiu sem confirmação e a mensagem não está
299
+ no histórico; o plugin não posta de novo."""
300
+ canal = _canal(canal)
301
+ texto = _texto_do_slack(texto)
302
+ chave = chamada.idempotencia
303
+ cliente = _cliente_da_chamada(chamada, porta)
304
+ existente = _mensagem_com_a_chave(cliente, canal, chave)
305
+ if existente is not None:
306
+ return _resultado(canal, existente.get("ts"), reaproveitada=True)
307
+ return _postar(cliente, canal, texto, chave)
@@ -0,0 +1,321 @@
1
+ """O cliente HTTP da Web API do Slack: o token da conexão, o prazo da chamada e a retentativa.
2
+
3
+ Fala só com ``slack.com`` (o host que o plugin declara), sempre com ``chamada.destino(host)`` antes
4
+ de conectar. O certificado é verificado; o ``HTTPS_PROXY`` do ambiente é respeitado (no sandbox, o
5
+ proxy da allowlist). Não segue redirecionamento: o token não vai a outro host.
6
+
7
+ O Slack responde ``200`` com ``{"ok": false, "error": "..."}`` até no erro de autenticação. O token
8
+ vem de ``chamada.token(CONEXAO)``; o ``401`` e o ``token_expired``/``invalid_auth`` (o token
9
+ expirou ou foi revogado antes da hora) trocam o token uma vez (``renovar=True``) e repetem: o pedido
10
+ recusado não teve efeito.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import re
17
+ import ssl
18
+ import time
19
+ import urllib.error
20
+ import urllib.parse
21
+ import urllib.request
22
+ from collections.abc import Callable, Mapping
23
+ from dataclasses import dataclass
24
+ from typing import Any
25
+
26
+ from shade_sdk import http
27
+
28
+ from shade_plugins_slack.erros import ErroDoSlack, NaoEncontrado, SlackIncerto, SlackNaoSaiu
29
+
30
+ #: A conexão OAuth da plataforma de que o plugin pede o token (o provedor do catálogo).
31
+ CONEXAO = "slack"
32
+ SLACK = "slack.com"
33
+ RAIZ = "/api"
34
+ #: Quantas vezes o pedido é tentado quando a rede ou o Slack 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 maior ``Retry-After`` que o plugin honra; acima disso, devolve o que recebeu.
39
+ ESPERA_MAX = 10.0
40
+ #: O teto do corpo de uma resposta lida na memória.
41
+ RESPOSTA_MAX = 8 * 1024 * 1024
42
+ #: O que o Slack põe em ``error``: um nome curto, nunca o texto do pedido.
43
+ _CODIGO = re.compile(r"^[a-z0-9_]{1,64}$")
44
+ #: Os erros de autenticação em que um token novo pode resolver; o pedido não teve efeito.
45
+ RENOVAVEIS = frozenset({"token_expired", "invalid_auth", "not_authed"})
46
+ #: Os erros do servidor do Slack em que não se sabe se a mensagem foi postada.
47
+ DO_SERVIDOR = frozenset(
48
+ {"internal_error", "fatal_error", "service_unavailable", "request_timeout", "internal"}
49
+ )
50
+
51
+
52
+ class Prazo:
53
+ """O ``timeout`` da chamada como um prazo só: cada etapa usa o que sobrou."""
54
+
55
+ def __init__(self, segundos: float) -> None:
56
+ self.fim = time.monotonic() + segundos
57
+
58
+ def restante(self) -> float:
59
+ sobra = self.fim - time.monotonic()
60
+ if sobra <= 0:
61
+ raise TimeoutError("o prazo da chamada acabou")
62
+ return sobra
63
+
64
+ def cabe(self, espera: float) -> bool:
65
+ return self.fim - time.monotonic() > espera
66
+
67
+
68
+ class _SemRedirecionamento(urllib.request.HTTPRedirectHandler):
69
+ def redirect_request(self, *args: Any, **kwargs: Any) -> None:
70
+ return None
71
+
72
+
73
+ def _abridor() -> Callable[..., Any]:
74
+ contexto = ssl.create_default_context()
75
+ contexto.minimum_version = ssl.TLSVersion.TLSv1_2
76
+ return urllib.request.build_opener(
77
+ urllib.request.ProxyHandler(),
78
+ urllib.request.HTTPSHandler(context=contexto),
79
+ _SemRedirecionamento(),
80
+ ).open
81
+
82
+
83
+ @dataclass
84
+ class Resposta:
85
+ status: int
86
+ cabecalhos: Mapping[str, str]
87
+ corpo: bytes = b""
88
+
89
+ def cabecalho(self, nome: str) -> str:
90
+ for chave, valor in self.cabecalhos.items():
91
+ if chave.lower() == nome.lower():
92
+ return valor
93
+ return ""
94
+
95
+ def dados(self) -> dict[str, Any]:
96
+ try:
97
+ dados = json.loads(self.corpo)
98
+ except ValueError as exc:
99
+ raise ErroDoSlack("Slack: a resposta não é JSON", status=self.status) from exc
100
+ if not isinstance(dados, dict):
101
+ raise ErroDoSlack("Slack: a resposta não é um objeto JSON", status=self.status)
102
+ return dados
103
+
104
+ @property
105
+ def erro(self) -> str:
106
+ """O código de ``error`` quando o Slack recusou (``ok: false``), só se for um nome curto;
107
+ vazio quando deu certo ou o corpo não é o do Slack."""
108
+ try:
109
+ dados = json.loads(self.corpo[:65536])
110
+ except ValueError:
111
+ return ""
112
+ if not isinstance(dados, dict) or dados.get("ok") is not False:
113
+ return ""
114
+ codigo = dados.get("error")
115
+ return codigo if isinstance(codigo, str) and _CODIGO.fullmatch(codigo) else "desconhecido"
116
+
117
+ @property
118
+ def ok(self) -> bool:
119
+ if self.status != 200:
120
+ return False
121
+ try:
122
+ dados = json.loads(self.corpo)
123
+ except ValueError:
124
+ return False
125
+ return isinstance(dados, dict) and dados.get("ok") is True
126
+
127
+
128
+ def transitorio(exc: BaseException) -> bool:
129
+ """Falha de rede em que repetir pode dar certo. O certificado inválido e o prazo esgotado,
130
+ não."""
131
+ if isinstance(exc, TimeoutError):
132
+ return False
133
+ return isinstance(exc, urllib.error.URLError | ConnectionError | ssl.SSLError) and not (
134
+ isinstance(exc, urllib.error.URLError)
135
+ and isinstance(exc.reason, ssl.SSLCertVerificationError)
136
+ )
137
+
138
+
139
+ def _retry_after(resposta: Resposta) -> float:
140
+ """O ``Retry-After`` em segundos (o Slack manda o número), limitado a ``ESPERA_MAX``."""
141
+ texto = resposta.cabecalho("Retry-After").strip()
142
+ if not texto.isdigit():
143
+ return 0.0
144
+ return min(float(texto), ESPERA_MAX)
145
+
146
+
147
+ @dataclass
148
+ class Cliente:
149
+ chamada: Any
150
+ prazo: Prazo
151
+ porta: int | None = None
152
+ _token: str | None = None
153
+ _renovou: bool = False
154
+
155
+ def url(self, metodo: str, parametros: Mapping[str, str] | None = None) -> str:
156
+ endereco = SLACK if self.porta in (None, 443) else f"{SLACK}:{self.porta}"
157
+ consulta = urllib.parse.urlencode(dict(parametros or {}))
158
+ return f"https://{endereco}{RAIZ}/{metodo}" + (f"?{consulta}" if consulta else "")
159
+
160
+ def _bearer(self, *, renovar: bool = False) -> str:
161
+ if self._token is None or renovar:
162
+ self._token = self.chamada.token(CONEXAO, renovar=renovar)
163
+ return self._token
164
+
165
+ def pedir(
166
+ self,
167
+ metodo: str,
168
+ *,
169
+ parametros: Mapping[str, str] | None = None,
170
+ corpo: Mapping[str, Any] | None = None,
171
+ idempotencia: str | None = None,
172
+ repetir_depois_do_envio: bool = True,
173
+ ) -> Resposta:
174
+ """Um método da Web API com o token da conexão, dentro do prazo: ``GET`` com os
175
+ ``parametros`` ou ``POST`` do ``corpo`` em JSON (o ``json.dumps`` escapa o valor). Repete a
176
+ falha transitória de rede, o ``429`` e o ``5xx`` quando ``repetir_depois_do_envio`` (a
177
+ leitura); senão, só o que certamente não saiu (a rede que recusou antes do envio, o
178
+ ``429``). A autenticação vencida troca o token uma vez e repete. ``idempotencia`` vai no
179
+ ``Idempotency-Key``: o Slack o ignora, e quem observa o tráfego (o proxy, o servidor
180
+ falso) distingue a execução."""
181
+ self.chamada.destino(SLACK)
182
+ url = self.url(metodo, parametros)
183
+ dados = None if corpo is None else json.dumps(corpo, ensure_ascii=False).encode("utf-8")
184
+ abrir = _abridor()
185
+ ultima_falha: BaseException | None = None
186
+ ultima_resposta: Resposta | None = None
187
+ tentativa = 0
188
+ while tentativa < TENTATIVAS:
189
+ if tentativa:
190
+ espera = ESPERAS[min(tentativa - 1, len(ESPERAS) - 1)]
191
+ if ultima_resposta is not None:
192
+ espera = max(espera, _retry_after(ultima_resposta))
193
+ if not self.prazo.cabe(espera):
194
+ break
195
+ time.sleep(espera)
196
+ tentativa += 1
197
+ enviados = {
198
+ "Accept": "application/json",
199
+ "Authorization": f"Bearer {self._bearer()}",
200
+ }
201
+ if dados is not None:
202
+ enviados["Content-Type"] = "application/json; charset=utf-8"
203
+ if idempotencia:
204
+ enviados["Idempotency-Key"] = idempotencia
205
+ pedido = urllib.request.Request(
206
+ url, data=dados, headers=enviados, method="GET" if dados is None else "POST"
207
+ )
208
+ try:
209
+ resposta = self._despachar(abrir, pedido)
210
+ except Exception as exc:
211
+ if not transitorio(exc) or not (repetir_depois_do_envio or http.nada_saiu(exc)):
212
+ raise
213
+ ultima_falha, ultima_resposta = exc, None
214
+ continue
215
+ if not self._renovou and (resposta.status == 401 or resposta.erro in RENOVAVEIS):
216
+ # O token venceu antes da hora ou foi revogado: o pedido não teve efeito.
217
+ self._renovou = True
218
+ self._bearer(renovar=True)
219
+ tentativa -= 1
220
+ continue
221
+ if resposta.status == 429 or (resposta.status >= 500 and repetir_depois_do_envio):
222
+ ultima_falha, ultima_resposta = None, resposta
223
+ continue
224
+ return resposta
225
+ if ultima_resposta is not None:
226
+ return ultima_resposta
227
+ if ultima_falha is None:
228
+ raise TimeoutError("o prazo da chamada acabou")
229
+ raise ultima_falha
230
+
231
+ def _despachar(self, abrir: Callable[..., Any], pedido: Any) -> Resposta:
232
+ try:
233
+ with abrir(pedido, timeout=self.prazo.restante()) as resposta:
234
+ corpo = resposta.read(RESPOSTA_MAX + 1)
235
+ if len(corpo) > RESPOSTA_MAX:
236
+ raise ErroDoSlack("Slack: a resposta passa do teto de leitura")
237
+ return Resposta(resposta.status, dict(resposta.headers.items()), corpo)
238
+ except urllib.error.HTTPError as exc:
239
+ corpo = exc.read(65536) if exc.fp else b""
240
+ return Resposta(exc.code, dict(exc.headers.items()), corpo)
241
+
242
+
243
+ def _descricao(resposta: Resposta) -> str:
244
+ return f"{resposta.status} {resposta.erro}".strip()
245
+
246
+
247
+ def checar_leitura(operacao: str, resposta: Resposta) -> dict[str, Any]:
248
+ """Os dados da resposta de uma leitura; o erro vira ``ErroDoSlack`` com o código do Slack."""
249
+ if resposta.ok:
250
+ return resposta.dados()
251
+ erro = resposta.erro
252
+ if erro in ("channel_not_found", "not_in_channel") or resposta.status == 404:
253
+ raise NaoEncontrado(
254
+ f"Slack {operacao}: o canal não existe, ou a conta conectada não o vê "
255
+ f"({_descricao(resposta)})",
256
+ status=resposta.status,
257
+ codigo=erro,
258
+ )
259
+ if erro in ("missing_scope", "no_permission", "access_denied"):
260
+ raise ErroDoSlack(
261
+ f"Slack {operacao}: a conexão não tem permissão ({_descricao(resposta)}); "
262
+ "reconecte o Slack para conceder os escopos que faltam",
263
+ status=resposta.status,
264
+ codigo=erro,
265
+ )
266
+ raise ErroDoSlack(
267
+ f"Slack {operacao}: o Slack devolveu {_descricao(resposta)}",
268
+ status=resposta.status,
269
+ codigo=erro,
270
+ )
271
+
272
+
273
+ def recusa_antes_de_postar(operacao: str, resposta: Resposta) -> SlackNaoSaiu:
274
+ """A leitura do histórico (antes de postar) que o Slack recusou: nada foi postado."""
275
+ erro = resposta.erro
276
+ dica = (
277
+ "; reconecte o Slack para conceder o escopo channels:history"
278
+ if erro == "missing_scope"
279
+ else ""
280
+ )
281
+ return SlackNaoSaiu(
282
+ f"Slack {operacao}: o histórico do canal não foi lido ({_descricao(resposta)}){dica}; "
283
+ "nada foi postado",
284
+ status=resposta.status,
285
+ codigo=erro,
286
+ )
287
+
288
+
289
+ def checar_escrita(operacao: str, resposta: Resposta) -> dict[str, Any]:
290
+ """``ok: true`` passa; o ``ok: false`` e o 4xx são ``SlackNaoSaiu`` (o Slack recusou antes de
291
+ postar; o 429 também: o cliente já tentou de novo); o erro do servidor e o corpo que não se
292
+ lê são dúvida."""
293
+ if resposta.status >= 500 or resposta.erro in DO_SERVIDOR:
294
+ raise SlackIncerto(
295
+ f"Slack {operacao}: o Slack devolveu {_descricao(resposta)}",
296
+ status=resposta.status,
297
+ codigo=resposta.erro,
298
+ )
299
+ if resposta.ok:
300
+ return resposta.dados()
301
+ if resposta.status != 200 or resposta.erro:
302
+ raise SlackNaoSaiu(
303
+ f"Slack {operacao}: o Slack recusou o pedido ({_descricao(resposta)})",
304
+ status=resposta.status,
305
+ codigo=resposta.erro,
306
+ )
307
+ # 200 sem ``ok``: o corpo não é o do Slack, e a mensagem pode ter saído.
308
+ raise SlackIncerto(f"Slack {operacao}: a resposta não confirma o envio", status=resposta.status)
309
+
310
+
311
+ def falha_de_leitura(operacao: str, exc: BaseException) -> ErroDoSlack:
312
+ return ErroDoSlack(f"Slack {operacao}: a conexão falhou ({type(exc).__name__})")
313
+
314
+
315
+ def falha_de_escrita(operacao: str, exc: BaseException) -> Exception:
316
+ if http.nada_saiu(exc):
317
+ return SlackNaoSaiu(f"Slack {operacao}: a conexão não abriu ({type(exc).__name__})")
318
+ return SlackIncerto(
319
+ f"Slack {operacao}: a conexão falhou depois do envio ({type(exc).__name__}); "
320
+ "a mensagem pode ter chegado"
321
+ )
@@ -0,0 +1,48 @@
1
+ """Os erros do plugin ``slack``.
2
+
3
+ Separam o que **certamente não chegou** ao canal (``SlackNaoSaiu``, um ``http.NadaSaiu``) do que
4
+ **pode ter chegado** (``SlackIncerto``, 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, o status HTTP e o código que o Slack dá (``channel_not_found``,
8
+ ``missing_scope``), nunca o corpo, o texto da mensagem, o id do canal nem o token.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from shade_sdk import http
14
+
15
+
16
+ class ErroDoSlack(Exception):
17
+ """A leitura não deu certo: conexão, TLS, permissão ou o Slack recusou o pedido."""
18
+
19
+ def __init__(self, mensagem: str, *, status: int | None = None, codigo: str = "") -> None:
20
+ super().__init__(mensagem)
21
+ self.status = status
22
+ self.codigo = codigo
23
+
24
+
25
+ class NaoEncontrado(ErroDoSlack):
26
+ """O canal não existe, ou a conta conectada não o vê (``channel_not_found``)."""
27
+
28
+
29
+ class SlackNaoSaiu(http.NadaSaiu):
30
+ """Certamente sem efeito: o Slack recusou o pedido (``ok: false``, 4xx, inclusive o 429 que
31
+ sobrou das retentativas), a leitura do histórico antes de postar falhou, ou a rede falhou
32
+ antes do envio."""
33
+
34
+ def __init__(self, mensagem: str, *, status: int | None = None, codigo: str = "") -> None:
35
+ super().__init__(mensagem)
36
+ self.status = status
37
+ self.codigo = codigo
38
+
39
+
40
+ class SlackIncerto(http.ResultadoIncerto):
41
+ """Pode ter tido efeito: o pedido foi enviado e a resposta não veio, veio com erro do servidor
42
+ ou não se leu, e a mensagem não está no histórico. Conferir no canal antes de refazer: a
43
+ mensagem pode ter sido postada."""
44
+
45
+ def __init__(self, mensagem: str, *, status: int | None = None, codigo: str = "") -> None:
46
+ super().__init__(mensagem)
47
+ self.status = status
48
+ self.codigo = codigo
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.5
2
+ Name: shade-plugins-slack
3
+ Version: 0.1.0
4
+ Summary: Listar canais e enviar mensagem no Slack sem duplicar, pela Web API, 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-slack
13
+
14
+ Lista os canais e envia mensagem no [Slack](https://api.slack.com/web), de dentro de um robô do
15
+ [`shade-sdk`](https://pypi.org/project/shade-sdk/), com o token OAuth da conexão do Slack na
16
+ plataforma. Só a biblioteca padrão do Python: nenhuma dependência além do `shade-sdk`.
17
+
18
+ No `shade.toml` do robô, o host da API vai em `[hosts] permitidos` e a conexão em `[conexoes]`:
19
+
20
+ ```toml
21
+ [hosts]
22
+ permitidos = ["slack.com"]
23
+
24
+ [conexoes]
25
+ nomes = ["slack"]
26
+
27
+ [plugins]
28
+ slack = "0.1.0"
29
+ ```
30
+
31
+ ```python
32
+ import shade_plugins_slack as slack
33
+
34
+ # Leitura: roda inclusive no ensaio.
35
+ canal = next(c["id"] for c in slack.listar_canais() if c["nome"] == "financeiro")
36
+
37
+ # Escrita: só dentro de item.efetivar() (no ensaio não roda).
38
+ with item.efetivar("avisar o time"):
39
+ slack.enviar_mensagem(canal, f"Pedido {item['pedido']} conferido.")
40
+ ```
41
+
42
+ ## A conta
43
+
44
+ - **Conexão:** o robô nunca vê a senha nem o refresh token. O token de acesso chega sob demanda da
45
+ conexão `slack` da plataforma e é renovado por ela. Fora da plataforma (no laptop), ponha um
46
+ token de acesso em `SHADE_TOKEN_SLACK`.
47
+ - **Escopos:** `channels:read` (listar os canais), `chat:write` (postar) e `channels:history` (ler o
48
+ histórico recente, que é o que evita a mensagem duplicada). A conexão sem `channels:history` não
49
+ posta nada e o erro manda reconectar o Slack.
50
+ - **Canais:** os públicos. O app precisa ter sido adicionado ao canal para ler o histórico e postar.
51
+ O `canal` das operações é o **id** (como `C0123ABCD`, o que `listar_canais` devolve), não o nome.
52
+
53
+ ## O que o plugin garante
54
+
55
+ - **Não duplica a mensagem.** O Slack não reconhece repetição. O plugin grava a chave do item no
56
+ `metadata` da mensagem e, antes de postar, lê as últimas mensagens do canal (até 500) e devolve a
57
+ que já tiver a chave. Depois que o envio saiu sem confirmação (a conexão caiu, o `5xx`, a
58
+ resposta que não se lê), o plugin não posta de novo: ele confere o histórico e, sem achar, o
59
+ erro é `SlackIncerto` (o item fica retido para uma pessoa conferir no canal e, só se a mensagem
60
+ não chegou, mandar refazer).
61
+ - **O texto é literal.** `&`, `<` e `>` vão como as entidades que a API documenta, então
62
+ `<!channel>`, `<@U123>` e `<https://...|texto>` vindos de um dado não viram menção nem link. A
63
+ mensagem sai sem formatação (`mrkdwn` desligado), e o corpo é montado como objeto e serializado
64
+ pelo `shade_sdk.http`, nunca por concatenação de texto.
65
+ - **Retentativa só onde é segura:** a leitura e o `429` (nada foi postado) repetem dentro do
66
+ `timeout=`; depois do despacho do `chat.postMessage`, nada repete.
67
+ - **Só dentro de `item.efetivar()`.** Fora dele, a operação é um erro de contrato antes de qualquer
68
+ byte; no ensaio, o bloco é pulado e nada é enviado.
69
+ - **Host e prazo:** só `slack.com`, com o certificado verificado, sem seguir redirecionamento; toda
70
+ chamada aceita `timeout=` (30 s por padrão), que vale para a chamada inteira.
71
+ - **Sem conteúdo em evento nem em erro:** cada chamada emite um evento com a operação, o host, a
72
+ duração e o status. Nunca o texto, o id do canal, o token nem o corpo da resposta; o erro da API
73
+ chega só pelo código que o Slack dá (`channel_not_found`, `missing_scope`).
74
+
75
+ ## Operações
76
+
77
+ | Operação | Efeito | O que faz |
78
+ |---|---|---|
79
+ | `listar_canais(*, limite=1000, arquivados=False)` | não | Os canais públicos: `id`, `nome`, `arquivado`, `membro`, `membros`. |
80
+ | `enviar_mensagem(canal, texto)` | sim | Posta `texto` (até 40 000 caracteres) no canal. Devolve `canal`, `ts` e `reaproveitada`. |
81
+
82
+ ## Limites
83
+
84
+ O histórico do Slack é de leitura limitada para alguns apps (os não listados no Marketplace têm
85
+ cota baixa em `conversations.history`). Se a leitura for recusada com `ratelimited`, a mensagem não
86
+ é postada (`SlackNaoSaiu`), em vez de arriscar o duplicado.
87
+
88
+ ## Testes
89
+
90
+ A suíte de contrato do `shade_sdk.testing.plugins` e um servidor falso da Web API (TLS de uma CA de
91
+ teste, que responde `ok: false` com `200` e não reconhece repetição, como a de verdade) acompanham o
92
+ código-fonte em `tests/`.
@@ -0,0 +1,8 @@
1
+ shade_plugins_slack/__init__.py,sha256=SGIsBlgPrSIDTlzpYa_7Av5WUiiEn5Z5kL8orj0EJo4,12337
2
+ shade_plugins_slack/_cliente.py,sha256=qtCZe6HbZaCS1sZRsJI-7R8n50nde9iEVND-n0phOjc,12880
3
+ shade_plugins_slack/erros.py,sha256=c8nml5EIsVxOEID7t09BjMNPWT7JI3r_rpUI__iWpZo,1906
4
+ shade_plugins_slack-0.1.0.dist-info/METADATA,sha256=5e776ljdhcOuJ_Wd-5mpjIKHtD0gzHRi9BdLEmmBmak,4479
5
+ shade_plugins_slack-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
6
+ shade_plugins_slack-0.1.0.dist-info/entry_points.txt,sha256=0ETm3PTvHIMm4BJ5c0UN2Ndk0cVCidvwTl5_shCrrO0,55
7
+ shade_plugins_slack-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
8
+ shade_plugins_slack-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [shade_sdk.plugins]
2
+ slack = shade_plugins_slack:PLUGIN
@@ -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.