shade-plugins-hubspot 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,422 @@
1
+ """O plugin ``hubspot``: buscar contatos e negócios, criar ou atualizar um contato pelo e-mail e
2
+ mover um negócio de estágio no HubSpot CRM, pela API v3, sob o contrato de plugin do shade-sdk, com
3
+ o token OAuth da conexão da plataforma.
4
+
5
+ ```toml
6
+ [hosts]
7
+ permitidos = ["api.hubapi.com"]
8
+
9
+ [conexoes]
10
+ nomes = ["hubspot"]
11
+
12
+ [plugins]
13
+ hubspot = "0.1.0"
14
+ ```
15
+
16
+ ```python
17
+ import shade_plugins_hubspot as hubspot
18
+
19
+ abertos = hubspot.buscar_negocios({"dealstage": "contractsent"}, propriedades=["dealname"])
20
+
21
+ with item.efetivar("registrar o cliente"):
22
+ hubspot.upsert_contato(item["email"], {"firstname": item["nome"], "phone": item["fone"]})
23
+ hubspot.mover_negocio(abertos[0]["id"], "closedwon")
24
+ ```
25
+
26
+ - **Conta:** a conexão ``hubspot`` da plataforma (Conectores). O robô nunca vê a senha nem o
27
+ refresh token: o token de acesso chega sob demanda e é renovado pela plataforma. No laptop, ponha
28
+ um token de acesso em ``SHADE_TOKEN_HUBSPOT``. Os escopos são ``crm.objects.contacts.read``,
29
+ ``crm.objects.contacts.write``, ``crm.objects.deals.read`` e ``crm.objects.deals.write``.
30
+ - **Ler não muda nada:** ``buscar_contatos`` e ``buscar_negocios`` rodam inclusive no ensaio.
31
+ - **Escrever só dentro de** ``item.efetivar()`` (no ensaio não roda). Nenhuma escrita duplica:
32
+ ``upsert_contato`` é o upsert em lote do HubSpot com ``idProperty=email`` (o mesmo e-mail é um
33
+ contato só, e a segunda chamada atualiza as propriedades), e ``mover_negocio`` lê o estágio antes
34
+ e não faz ``PATCH`` se o negócio já está nele. Como as duas se repetem sem efeito duplo, a falha
35
+ transitória é repetida; ``mover_negocio`` ainda confere o estágio depois de uma resposta
36
+ perdida, e sem confirmar o erro é ``HubSpotIncerto``.
37
+ - **Fora do plugin:** criar negócio e propriedade customizada.
38
+ - **Prazo:** ``timeout=`` (30 s) vale para a chamada inteira, retentativas incluídas.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import math
44
+ import re
45
+ from collections.abc import Callable, Mapping
46
+ from typing import Any
47
+
48
+ from shade_sdk.plugins import Plugin
49
+
50
+ from shade_plugins_hubspot import _cliente
51
+ from shade_plugins_hubspot._cliente import CONEXAO, HUBSPOT, Cliente, Prazo
52
+ from shade_plugins_hubspot.erros import (
53
+ ErroDoHubSpot,
54
+ HubSpotIncerto,
55
+ HubSpotNaoSaiu,
56
+ NaoEncontrado,
57
+ )
58
+
59
+ __version__ = "0.1.0"
60
+
61
+ #: Quantos registros as buscas devolvem, no máximo, e quantos o HubSpot dá por página (o teto da
62
+ #: busca dele é 10 000 por consulta).
63
+ LIMITE_MAX = 10_000
64
+ POR_PAGINA = 200
65
+ PAGINAS_MAX = 50
66
+ #: O que o HubSpot aceita por pedido de busca: 5 grupos de 6 filtros (aqui um grupo, com E).
67
+ FILTROS_MAX = 6
68
+ PROPRIEDADES_MAX = 200
69
+ VALOR_MAX = 65_536
70
+ #: Os operadores da busca que o plugin expõe (o valor é sempre um só).
71
+ OPERADORES_COM_VALOR = frozenset(
72
+ {"EQ", "NEQ", "LT", "LTE", "GT", "GTE", "CONTAINS_TOKEN", "NOT_CONTAINS_TOKEN"}
73
+ )
74
+ OPERADORES_SEM_VALOR = frozenset({"HAS_PROPERTY", "NOT_HAS_PROPERTY"})
75
+ #: O nome interno de uma propriedade do HubSpot (minúsculas, dígitos e ``_``).
76
+ _PROPRIEDADE = re.compile(r"^[a-z][a-z0-9_]{0,99}$")
77
+ _EMAIL = re.compile(r"^[^@\s,;<>\"']{1,64}@[^@\s,;<>\"']{1,255}$")
78
+ _ID = re.compile(r"^[0-9]{1,20}$")
79
+ _ESTAGIO = re.compile(r"^[A-Za-z0-9_\-]{1,100}$")
80
+ _CURSOR = re.compile(r"^[A-Za-z0-9_\-]{1,100}$")
81
+
82
+ PROPRIEDADES_DE_CONTATO = ("email", "firstname", "lastname", "phone", "lifecyclestage")
83
+ PROPRIEDADES_DE_NEGOCIO = ("dealname", "dealstage", "pipeline", "amount", "closedate")
84
+
85
+ PLUGIN = Plugin(
86
+ "hubspot",
87
+ __version__,
88
+ shade_sdk=">=0.22.3,<0.23",
89
+ dono="Equipe de integrações da ShadeOne",
90
+ hosts=[HUBSPOT],
91
+ conexoes=[CONEXAO],
92
+ )
93
+
94
+ __all__ = [
95
+ "PLUGIN",
96
+ "ErroDoHubSpot",
97
+ "HubSpotIncerto",
98
+ "HubSpotNaoSaiu",
99
+ "NaoEncontrado",
100
+ "buscar_contatos",
101
+ "buscar_negocios",
102
+ "mover_negocio",
103
+ "upsert_contato",
104
+ ]
105
+
106
+
107
+ def _porta(porta: Any) -> int | None:
108
+ if porta is not None and (
109
+ not isinstance(porta, int) or isinstance(porta, bool) or not 0 < porta < 65536
110
+ ):
111
+ raise ValueError(f"porta é um número de 1 a 65535, não {porta!r}")
112
+ return porta
113
+
114
+
115
+ def _limite(valor: Any) -> int:
116
+ if not isinstance(valor, int) or isinstance(valor, bool) or not 0 < valor <= LIMITE_MAX:
117
+ raise ValueError(f"limite é um número de 1 a {LIMITE_MAX}")
118
+ return valor
119
+
120
+
121
+ def _nome_da_propriedade(nome: Any) -> str:
122
+ if not isinstance(nome, str) or not _PROPRIEDADE.fullmatch(nome):
123
+ raise ValueError(
124
+ "o nome de uma propriedade é o nome interno do HubSpot (minúsculas, dígitos e _), "
125
+ f"não {nome!r}"
126
+ )
127
+ return nome
128
+
129
+
130
+ def _valor(valor: Any) -> str:
131
+ """O valor de uma propriedade como o HubSpot o recebe: sempre texto."""
132
+ if isinstance(valor, bool):
133
+ texto = "true" if valor else "false"
134
+ elif isinstance(valor, int):
135
+ texto = str(valor)
136
+ elif isinstance(valor, float) and math.isfinite(valor):
137
+ texto = repr(valor)
138
+ elif isinstance(valor, str):
139
+ texto = valor
140
+ else:
141
+ raise ValueError("o valor de uma propriedade é texto, número ou verdadeiro/falso")
142
+ if len(texto) > VALOR_MAX:
143
+ raise ValueError(f"o valor de uma propriedade passa de {VALOR_MAX} caracteres")
144
+ return texto
145
+
146
+
147
+ def _filtros(filtros: Any) -> list[dict[str, Any]]:
148
+ """``{"dealstage": "contractsent"}`` (igual) ou ``{"amount": ["GTE", 1000]}`` (operador e valor;
149
+ ``["HAS_PROPERTY"]`` sem valor). Todos valem ao mesmo tempo (E)."""
150
+ if not isinstance(filtros, Mapping):
151
+ raise ValueError("filtros é um dicionário de propriedade para valor (ou [operador, valor])")
152
+ if len(filtros) > FILTROS_MAX:
153
+ raise ValueError(f"filtros aceita até {FILTROS_MAX} propriedades")
154
+ saida: list[dict[str, Any]] = []
155
+ for nome, pedido in filtros.items():
156
+ filtro: dict[str, Any] = {"propertyName": _nome_da_propriedade(nome)}
157
+ if isinstance(pedido, list | tuple):
158
+ operador = pedido[0] if pedido else None
159
+ if operador in OPERADORES_SEM_VALOR and len(pedido) == 1:
160
+ filtro["operator"] = operador
161
+ elif operador in OPERADORES_COM_VALOR and len(pedido) == 2:
162
+ filtro["operator"] = operador
163
+ filtro["value"] = _valor(pedido[1])
164
+ else:
165
+ raise ValueError(
166
+ "um filtro com operador é [operador, valor] (EQ, NEQ, LT, LTE, GT, GTE, "
167
+ "CONTAINS_TOKEN, NOT_CONTAINS_TOKEN) ou [HAS_PROPERTY]/[NOT_HAS_PROPERTY]"
168
+ )
169
+ else:
170
+ filtro["operator"] = "EQ"
171
+ filtro["value"] = _valor(pedido)
172
+ saida.append(filtro)
173
+ return saida
174
+
175
+
176
+ def _propriedades_pedidas(propriedades: Any, padrao: tuple[str, ...]) -> list[str]:
177
+ if propriedades is None:
178
+ return list(padrao)
179
+ if not isinstance(propriedades, list | tuple) or not 0 < len(propriedades) <= PROPRIEDADES_MAX:
180
+ raise ValueError(f"propriedades é uma lista de 1 a {PROPRIEDADES_MAX} nomes")
181
+ return [_nome_da_propriedade(p) for p in propriedades]
182
+
183
+
184
+ def _email(valor: Any) -> str:
185
+ if not isinstance(valor, str):
186
+ raise ValueError("email é um endereço de e-mail")
187
+ email = valor.strip()
188
+ if len(email) > 254 or not _EMAIL.fullmatch(email):
189
+ raise ValueError("email é um endereço de e-mail válido")
190
+ return email
191
+
192
+
193
+ def _id_do_negocio(valor: Any) -> str:
194
+ texto = str(valor) if isinstance(valor, int) and not isinstance(valor, bool) else valor
195
+ if not isinstance(texto, str) or not _ID.fullmatch(texto):
196
+ raise ValueError("id é o número do negócio no HubSpot (só dígitos)")
197
+ return texto
198
+
199
+
200
+ def _estagio(valor: Any) -> str:
201
+ if not isinstance(valor, str) or not _ESTAGIO.fullmatch(valor):
202
+ raise ValueError(
203
+ "estagio é o id interno do estágio do funil (como closedwon), não o nome da tela"
204
+ )
205
+ return valor
206
+
207
+
208
+ def _cliente_da_chamada(chamada: Any, porta: Any) -> Cliente:
209
+ return Cliente(chamada=chamada, prazo=Prazo(chamada.timeout), porta=_porta(porta))
210
+
211
+
212
+ def _lendo(operacao: str, funcao: Callable[[], Any]) -> Any:
213
+ """A falha de rede no meio da leitura vira ``ErroDoHubSpot``."""
214
+ try:
215
+ return funcao()
216
+ except ErroDoHubSpot:
217
+ raise
218
+ except OSError as exc:
219
+ raise _cliente.falha_de_leitura(operacao, exc) from exc
220
+
221
+
222
+ # ── Buscas ───────────────────────────────────────────────────────────────────────────────
223
+
224
+
225
+ def _buscar(
226
+ operacao: str,
227
+ objeto: str,
228
+ chamada: Any,
229
+ filtros: Any,
230
+ propriedades: list[str],
231
+ limite: int,
232
+ porta: Any,
233
+ ) -> list[dict[str, Any]]:
234
+ grupos = _filtros(filtros)
235
+ cliente = _cliente_da_chamada(chamada, porta)
236
+
237
+ def ler() -> list[dict[str, Any]]:
238
+ achados: list[dict[str, Any]] = []
239
+ depois = ""
240
+ for _ in range(PAGINAS_MAX):
241
+ # O OpenAPI do HubSpot marca os cinco campos como obrigatórios; o ``after`` da primeira
242
+ # página fica de fora (a documentação manda omitir, e o Backlot recusa ``"0"``).
243
+ corpo: dict[str, Any] = {
244
+ "filterGroups": [{"filters": grupos}] if grupos else [],
245
+ "properties": propriedades,
246
+ "limit": min(POR_PAGINA, limite - len(achados)),
247
+ "sorts": [],
248
+ }
249
+ if depois:
250
+ corpo["after"] = depois
251
+ resposta = cliente.pedir("POST", f"/crm/v3/objects/{objeto}/search", corpo=corpo)
252
+ dados = _cliente.checar_leitura(operacao, resposta)
253
+ for registro in dados.get("results") or []:
254
+ if isinstance(registro, dict):
255
+ props = registro.get("properties")
256
+ achados.append(
257
+ {
258
+ "id": str(registro.get("id", "")),
259
+ "propriedades": props if isinstance(props, dict) else {},
260
+ }
261
+ )
262
+ if len(achados) >= limite:
263
+ return achados
264
+ paginacao = dados.get("paging")
265
+ proximo = (
266
+ (paginacao.get("next") or {}).get("after") if isinstance(paginacao, dict) else ""
267
+ )
268
+ if not isinstance(proximo, str) or not _CURSOR.fullmatch(proximo) or proximo == depois:
269
+ break
270
+ depois = proximo
271
+ return achados
272
+
273
+ return _lendo(operacao, ler)
274
+
275
+
276
+ @PLUGIN.operacao
277
+ def buscar_contatos(
278
+ chamada: Any,
279
+ filtros: Mapping[str, Any],
280
+ propriedades: list[str] | None = None,
281
+ *,
282
+ limite: int = 100,
283
+ porta: int | None = None,
284
+ ) -> list[dict[str, Any]]:
285
+ """Os contatos que atendem a todos os ``filtros`` (``{"email": "ana@exemplo.com"}`` ou
286
+ ``{"lifecyclestage": ["NEQ", "customer"]}``), até ``limite``, seguindo o cursor ``after`` do
287
+ HubSpot. Cada um: ``id`` e ``propriedades`` (as pedidas em ``propriedades``; sem elas,
288
+ ``email``, ``firstname``, ``lastname``, ``phone`` e ``lifecyclestage``). Nada muda no HubSpot.
289
+ A busca do HubSpot enxerga o contato criado há alguns segundos com atraso."""
290
+ limite = _limite(limite)
291
+ pedidas = _propriedades_pedidas(propriedades, PROPRIEDADES_DE_CONTATO)
292
+ return _buscar("buscar_contatos", "contacts", chamada, filtros, pedidas, limite, porta)
293
+
294
+
295
+ @PLUGIN.operacao
296
+ def buscar_negocios(
297
+ chamada: Any,
298
+ filtros: Mapping[str, Any],
299
+ propriedades: list[str] | None = None,
300
+ *,
301
+ limite: int = 100,
302
+ porta: int | None = None,
303
+ ) -> list[dict[str, Any]]:
304
+ """Os negócios que atendem a todos os ``filtros`` (``{"dealstage": "contractsent"}``), até
305
+ ``limite``. Cada um: ``id`` (o que ``mover_negocio`` pede) e ``propriedades`` (sem
306
+ ``propriedades``, ``dealname``, ``dealstage``, ``pipeline``, ``amount`` e ``closedate``). Nada
307
+ muda no HubSpot."""
308
+ limite = _limite(limite)
309
+ pedidas = _propriedades_pedidas(propriedades, PROPRIEDADES_DE_NEGOCIO)
310
+ return _buscar("buscar_negocios", "deals", chamada, filtros, pedidas, limite, porta)
311
+
312
+
313
+ # ── Contato ──────────────────────────────────────────────────────────────────────────────
314
+
315
+
316
+ @PLUGIN.efeito
317
+ def upsert_contato(
318
+ chamada: Any,
319
+ email: str,
320
+ propriedades: Mapping[str, Any],
321
+ *,
322
+ porta: int | None = None,
323
+ ) -> dict[str, Any]:
324
+ """Cria o contato com este ``email`` ou atualiza o que já existe, só dentro de
325
+ ``item.efetivar()``. É o upsert em lote do HubSpot com ``idProperty=email``: o mesmo e-mail é
326
+ sempre um contato só, e as ``propriedades`` da chamada ficam no contato (as que a chamada não
327
+ cita não mudam). Devolve ``id``, ``email`` e ``novo`` (``True`` se este pedido criou o contato).
328
+ Repetir é seguro, e a falha transitória é repetida. ``HubSpotNaoSaiu``: o HubSpot recusou
329
+ (propriedade inexistente, escopo faltando). ``HubSpotIncerto``: sem confirmação do HubSpot;
330
+ repetir a operação é seguro."""
331
+ email = _email(email)
332
+ if not isinstance(propriedades, Mapping) or len(propriedades) > PROPRIEDADES_MAX:
333
+ raise ValueError(f"propriedades é um dicionário de até {PROPRIEDADES_MAX} propriedades")
334
+ props = {_nome_da_propriedade(n): _valor(v) for n, v in propriedades.items()}
335
+ if "email" in props:
336
+ raise ValueError("o e-mail é o argumento email, não uma propriedade")
337
+ cliente = _cliente_da_chamada(chamada, porta)
338
+ corpo = {"inputs": [{"idProperty": "email", "id": email, "properties": props}]}
339
+ try:
340
+ resposta = cliente.pedir(
341
+ "POST",
342
+ "/crm/v3/objects/contacts/batch/upsert",
343
+ corpo=corpo,
344
+ idempotencia=chamada.idempotencia,
345
+ )
346
+ dados = _cliente.checar_escrita("upsert_contato", resposta)
347
+ except OSError as exc:
348
+ raise _cliente.falha_de_escrita("upsert_contato", exc) from exc
349
+ resultados = dados.get("results")
350
+ registro = resultados[0] if isinstance(resultados, list) and resultados else None
351
+ if not isinstance(registro, dict) or not registro.get("id"):
352
+ raise HubSpotIncerto(
353
+ "HubSpot upsert_contato: a resposta não confirma o contato", status=resposta.status
354
+ )
355
+ return {"id": str(registro["id"]), "email": email, "novo": registro.get("new") is True}
356
+
357
+
358
+ # ── Negócio ──────────────────────────────────────────────────────────────────────────────
359
+
360
+
361
+ def _estagio_atual(cliente: Cliente, operacao: str, negocio: str, chave: str) -> str:
362
+ """O estágio de hoje do negócio. A chave do item vai no ``Idempotency-Key`` da leitura também:
363
+ o HubSpot a ignora, e quem observa o tráfego liga a leitura ao ``PATCH`` do mesmo item."""
364
+ resposta = cliente.pedir(
365
+ "GET",
366
+ f"/crm/v3/objects/deals/{negocio}",
367
+ parametros={"properties": "dealstage"},
368
+ idempotencia=chave,
369
+ )
370
+ dados = _cliente.checar_leitura(operacao, resposta)
371
+ props = dados.get("properties")
372
+ atual = props.get("dealstage") if isinstance(props, dict) else None
373
+ return atual if isinstance(atual, str) else ""
374
+
375
+
376
+ @PLUGIN.efeito
377
+ def mover_negocio(
378
+ chamada: Any,
379
+ id: str,
380
+ estagio: str,
381
+ *,
382
+ porta: int | None = None,
383
+ ) -> dict[str, Any]:
384
+ """Move o negócio ``id`` (o que ``buscar_negocios`` devolve) para o ``estagio`` (o id interno
385
+ do estágio do funil, como ``closedwon``), só dentro de ``item.efetivar()``. Lê o estágio antes
386
+ e **não faz ``PATCH``** se o negócio já está nele. Devolve ``id``, ``estagio`` e ``movido``
387
+ (``False`` quando já estava). ``NaoEncontrado``: o negócio não existe para a conta.
388
+ ``HubSpotNaoSaiu``: o HubSpot recusou (estágio de outro funil, escopo faltando).
389
+ ``HubSpotIncerto``: o ``PATCH`` saiu sem confirmação e o estágio lido depois não é o pedido;
390
+ repetir é seguro."""
391
+ negocio = _id_do_negocio(id)
392
+ estagio = _estagio(estagio)
393
+ cliente = _cliente_da_chamada(chamada, porta)
394
+ try:
395
+ atual = _estagio_atual(cliente, "mover_negocio", negocio, chamada.idempotencia)
396
+ except OSError as exc:
397
+ raise _cliente.falha_de_leitura("mover_negocio", exc) from exc
398
+ if atual == estagio:
399
+ return {"id": negocio, "estagio": estagio, "movido": False}
400
+ try:
401
+ resposta = cliente.pedir(
402
+ "PATCH",
403
+ f"/crm/v3/objects/deals/{negocio}",
404
+ corpo={"properties": {"dealstage": estagio}},
405
+ idempotencia=chamada.idempotencia,
406
+ )
407
+ _cliente.checar_escrita("mover_negocio", resposta)
408
+ return {"id": negocio, "estagio": estagio, "movido": True}
409
+ except HubSpotIncerto as incerto:
410
+ duvida: Exception = incerto
411
+ except OSError as exc:
412
+ duvida = _cliente.falha_de_escrita("mover_negocio", exc)
413
+ if isinstance(duvida, HubSpotNaoSaiu):
414
+ raise duvida from exc
415
+ # O PATCH pode ter sido aplicado: o que o confirma é o estágio.
416
+ try:
417
+ conferido = _estagio_atual(cliente, "mover_negocio", negocio, chamada.idempotencia)
418
+ except (ErroDoHubSpot, OSError):
419
+ raise duvida from None
420
+ if conferido == estagio:
421
+ return {"id": negocio, "estagio": estagio, "movido": True}
422
+ raise duvida
@@ -0,0 +1,301 @@
1
+ """O cliente HTTP da API v3 do HubSpot CRM: o token da conexão, o prazo da chamada e a retentativa.
2
+
3
+ Fala só com ``api.hubapi.com`` (o host que o plugin declara), sempre com ``chamada.destino(host)``
4
+ antes de conectar. O certificado é verificado; o ``HTTPS_PROXY`` do ambiente é respeitado (no
5
+ sandbox, o proxy da allowlist). Não segue redirecionamento: o token não vai a outro host.
6
+
7
+ O token vem de ``chamada.token(CONEXAO)``; o ``401`` (o token venceu antes da hora ou foi revogado)
8
+ troca o token uma vez (``renovar=True``) e repete: o pedido recusado não teve efeito.
9
+
10
+ Toda operação do plugin é repetível sem efeito duplo (o upsert por e-mail, o ``PATCH`` do estágio e
11
+ as leituras), então a falha transitória, o ``429`` e o ``5xx`` são repetidos mesmo depois do envio.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import re
18
+ import ssl
19
+ import time
20
+ import urllib.error
21
+ import urllib.parse
22
+ import urllib.request
23
+ from collections.abc import Callable, Mapping
24
+ from dataclasses import dataclass
25
+ from typing import Any
26
+
27
+ from shade_sdk import http
28
+
29
+ from shade_plugins_hubspot.erros import (
30
+ ErroDoHubSpot,
31
+ HubSpotIncerto,
32
+ HubSpotNaoSaiu,
33
+ NaoEncontrado,
34
+ )
35
+
36
+ #: A conexão OAuth da plataforma de que o plugin pede o token (o provedor do catálogo).
37
+ CONEXAO = "hubspot"
38
+ HUBSPOT = "api.hubapi.com"
39
+ #: Quantas vezes o pedido é tentado quando a rede ou o HubSpot falham de forma transitória.
40
+ TENTATIVAS = 3
41
+ #: A espera antes da 2ª e da 3ª tentativa (a régua do ``shade_sdk.http``).
42
+ ESPERAS = (0.5, 1.0)
43
+ #: O maior ``Retry-After`` que o plugin honra; acima disso, devolve o que recebeu.
44
+ ESPERA_MAX = 10.0
45
+ #: O teto do corpo de uma resposta lida na memória.
46
+ RESPOSTA_MAX = 8 * 1024 * 1024
47
+ #: A ``category`` do erro do HubSpot: um nome curto em maiúsculas, nunca o texto do pedido.
48
+ _CATEGORIA = re.compile(r"^[A-Z0-9_]{1,64}$")
49
+
50
+
51
+ class Prazo:
52
+ """O ``timeout`` da chamada como um prazo só: cada etapa usa o que sobrou."""
53
+
54
+ def __init__(self, segundos: float) -> None:
55
+ self.fim = time.monotonic() + segundos
56
+
57
+ def restante(self) -> float:
58
+ sobra = self.fim - time.monotonic()
59
+ if sobra <= 0:
60
+ raise TimeoutError("o prazo da chamada acabou")
61
+ return sobra
62
+
63
+ def cabe(self, espera: float) -> bool:
64
+ return self.fim - time.monotonic() > espera
65
+
66
+
67
+ class _SemRedirecionamento(urllib.request.HTTPRedirectHandler):
68
+ def redirect_request(self, *args: Any, **kwargs: Any) -> None:
69
+ return None
70
+
71
+
72
+ def _abridor() -> Callable[..., Any]:
73
+ contexto = ssl.create_default_context()
74
+ contexto.minimum_version = ssl.TLSVersion.TLSv1_2
75
+ return urllib.request.build_opener(
76
+ urllib.request.ProxyHandler(),
77
+ urllib.request.HTTPSHandler(context=contexto),
78
+ _SemRedirecionamento(),
79
+ ).open
80
+
81
+
82
+ @dataclass
83
+ class Resposta:
84
+ status: int
85
+ cabecalhos: Mapping[str, str]
86
+ corpo: bytes = b""
87
+
88
+ def cabecalho(self, nome: str) -> str:
89
+ for chave, valor in self.cabecalhos.items():
90
+ if chave.lower() == nome.lower():
91
+ return valor
92
+ return ""
93
+
94
+ @property
95
+ def ok(self) -> bool:
96
+ return 200 <= self.status < 300
97
+
98
+ def dados(self) -> dict[str, Any]:
99
+ try:
100
+ dados = json.loads(self.corpo)
101
+ except ValueError as exc:
102
+ raise ErroDoHubSpot("HubSpot: a resposta não é JSON", status=self.status) from exc
103
+ if not isinstance(dados, dict):
104
+ raise ErroDoHubSpot("HubSpot: a resposta não é um objeto JSON", status=self.status)
105
+ return dados
106
+
107
+ @property
108
+ def categoria(self) -> str:
109
+ """A ``category`` do erro (``VALIDATION_ERROR``, ``MISSING_SCOPES``...), só se for um nome
110
+ curto; vazia quando o corpo não é o do HubSpot."""
111
+ try:
112
+ dados = json.loads(self.corpo[:65536])
113
+ except ValueError:
114
+ return ""
115
+ if not isinstance(dados, dict):
116
+ return ""
117
+ categoria = dados.get("category")
118
+ return categoria if isinstance(categoria, str) and _CATEGORIA.fullmatch(categoria) else ""
119
+
120
+
121
+ def transitorio(exc: BaseException) -> bool:
122
+ """Falha de rede em que repetir pode dar certo. O certificado inválido e o prazo esgotado,
123
+ não."""
124
+ if isinstance(exc, TimeoutError):
125
+ return False
126
+ return isinstance(exc, urllib.error.URLError | ConnectionError | ssl.SSLError) and not (
127
+ isinstance(exc, urllib.error.URLError)
128
+ and isinstance(exc.reason, ssl.SSLCertVerificationError)
129
+ )
130
+
131
+
132
+ def _retry_after(resposta: Resposta) -> float:
133
+ """O ``Retry-After`` em segundos, limitado a ``ESPERA_MAX``."""
134
+ texto = resposta.cabecalho("Retry-After").strip()
135
+ if not texto.isdigit():
136
+ return 0.0
137
+ return min(float(texto), ESPERA_MAX)
138
+
139
+
140
+ @dataclass
141
+ class Cliente:
142
+ chamada: Any
143
+ prazo: Prazo
144
+ porta: int | None = None
145
+ _token: str | None = None
146
+ _renovou: bool = False
147
+
148
+ def url(self, caminho: str) -> str:
149
+ endereco = HUBSPOT if self.porta in (None, 443) else f"{HUBSPOT}:{self.porta}"
150
+ return f"https://{endereco}{caminho}"
151
+
152
+ def _bearer(self, *, renovar: bool = False) -> str:
153
+ if self._token is None or renovar:
154
+ self._token = self.chamada.token(CONEXAO, renovar=renovar)
155
+ return self._token
156
+
157
+ def pedir(
158
+ self,
159
+ metodo: str,
160
+ caminho: str,
161
+ *,
162
+ parametros: Mapping[str, str] | None = None,
163
+ corpo: Mapping[str, Any] | None = None,
164
+ idempotencia: str | None = None,
165
+ ) -> Resposta:
166
+ """Um pedido da API v3 com o token da conexão, dentro do prazo: o ``corpo`` vai em JSON (o
167
+ ``json.dumps`` escapa o valor) e os ``parametros`` na consulta. Repete a falha transitória
168
+ de rede, o ``429`` e o ``5xx``; a autenticação vencida troca o token uma vez e repete.
169
+ ``idempotencia`` vai no ``Idempotency-Key``: o HubSpot o ignora (o upsert e o ``PATCH`` já
170
+ são repetíveis), e quem observa o tráfego (o proxy, o servidor falso) distingue a
171
+ execução."""
172
+ self.chamada.destino(HUBSPOT)
173
+ url = self.url(caminho)
174
+ if parametros:
175
+ url += "?" + urllib.parse.urlencode(dict(parametros))
176
+ dados = None if corpo is None else json.dumps(corpo, ensure_ascii=False).encode("utf-8")
177
+ abrir = _abridor()
178
+ ultima_falha: BaseException | None = None
179
+ ultima_resposta: Resposta | None = None
180
+ tentativa = 0
181
+ while tentativa < TENTATIVAS:
182
+ if tentativa:
183
+ espera = ESPERAS[min(tentativa - 1, len(ESPERAS) - 1)]
184
+ if ultima_resposta is not None:
185
+ espera = max(espera, _retry_after(ultima_resposta))
186
+ if not self.prazo.cabe(espera):
187
+ break
188
+ time.sleep(espera)
189
+ tentativa += 1
190
+ enviados = {
191
+ "Accept": "application/json",
192
+ "Authorization": f"Bearer {self._bearer()}",
193
+ }
194
+ if dados is not None:
195
+ enviados["Content-Type"] = "application/json; charset=utf-8"
196
+ if idempotencia:
197
+ enviados["Idempotency-Key"] = idempotencia
198
+ pedido = urllib.request.Request(url, data=dados, headers=enviados, method=metodo)
199
+ try:
200
+ resposta = self._despachar(abrir, pedido)
201
+ except Exception as exc:
202
+ if not transitorio(exc):
203
+ raise
204
+ ultima_falha, ultima_resposta = exc, None
205
+ continue
206
+ if not self._renovou and resposta.status == 401:
207
+ # O token venceu antes da hora ou foi revogado: o pedido não teve efeito.
208
+ self._renovou = True
209
+ self._bearer(renovar=True)
210
+ tentativa -= 1
211
+ continue
212
+ if resposta.status == 429 or resposta.status >= 500:
213
+ ultima_falha, ultima_resposta = None, resposta
214
+ continue
215
+ return resposta
216
+ if ultima_resposta is not None:
217
+ return ultima_resposta
218
+ if ultima_falha is None:
219
+ raise TimeoutError("o prazo da chamada acabou")
220
+ raise ultima_falha
221
+
222
+ def _despachar(self, abrir: Callable[..., Any], pedido: Any) -> Resposta:
223
+ try:
224
+ with abrir(pedido, timeout=self.prazo.restante()) as resposta:
225
+ corpo = resposta.read(RESPOSTA_MAX + 1)
226
+ if len(corpo) > RESPOSTA_MAX:
227
+ raise ErroDoHubSpot("HubSpot: a resposta passa do teto de leitura")
228
+ return Resposta(resposta.status, dict(resposta.headers.items()), corpo)
229
+ except urllib.error.HTTPError as exc:
230
+ corpo = exc.read(65536) if exc.fp else b""
231
+ return Resposta(exc.code, dict(exc.headers.items()), corpo)
232
+
233
+
234
+ def _descricao(resposta: Resposta) -> str:
235
+ return f"{resposta.status} {resposta.categoria}".strip()
236
+
237
+
238
+ def checar_leitura(operacao: str, resposta: Resposta) -> dict[str, Any]:
239
+ """Os dados da resposta de uma leitura; o erro vira ``ErroDoHubSpot`` com a categoria."""
240
+ if resposta.ok:
241
+ return resposta.dados()
242
+ if resposta.status == 404:
243
+ raise NaoEncontrado(
244
+ f"HubSpot {operacao}: o registro não existe, ou a conta conectada não o vê "
245
+ f"({_descricao(resposta)})",
246
+ status=resposta.status,
247
+ categoria=resposta.categoria,
248
+ )
249
+ if resposta.status == 403 or resposta.categoria == "MISSING_SCOPES":
250
+ raise ErroDoHubSpot(
251
+ f"HubSpot {operacao}: a conexão não tem permissão ({_descricao(resposta)}); "
252
+ "reconecte o HubSpot para conceder os escopos que faltam",
253
+ status=resposta.status,
254
+ categoria=resposta.categoria,
255
+ )
256
+ raise ErroDoHubSpot(
257
+ f"HubSpot {operacao}: o HubSpot devolveu {_descricao(resposta)}",
258
+ status=resposta.status,
259
+ categoria=resposta.categoria,
260
+ )
261
+
262
+
263
+ def checar_escrita(operacao: str, resposta: Resposta) -> dict[str, Any]:
264
+ """O 2xx passa; o 4xx (e o 429 que sobrou das tentativas) é ``HubSpotNaoSaiu``; o erro do
265
+ servidor e o corpo que não se lê são dúvida (``HubSpotIncerto``)."""
266
+ if resposta.status >= 500:
267
+ raise HubSpotIncerto(
268
+ f"HubSpot {operacao}: o HubSpot devolveu {_descricao(resposta)}",
269
+ status=resposta.status,
270
+ categoria=resposta.categoria,
271
+ )
272
+ if resposta.ok:
273
+ try:
274
+ return resposta.dados()
275
+ except ErroDoHubSpot as exc:
276
+ raise HubSpotIncerto(
277
+ f"HubSpot {operacao}: a resposta não confirma o efeito", status=resposta.status
278
+ ) from exc
279
+ dica = (
280
+ "; reconecte o HubSpot para conceder os escopos que faltam"
281
+ if resposta.status == 403 or resposta.categoria == "MISSING_SCOPES"
282
+ else ""
283
+ )
284
+ raise HubSpotNaoSaiu(
285
+ f"HubSpot {operacao}: o HubSpot recusou o pedido ({_descricao(resposta)}){dica}",
286
+ status=resposta.status,
287
+ categoria=resposta.categoria,
288
+ )
289
+
290
+
291
+ def falha_de_leitura(operacao: str, exc: BaseException) -> ErroDoHubSpot:
292
+ return ErroDoHubSpot(f"HubSpot {operacao}: a conexão falhou ({type(exc).__name__})")
293
+
294
+
295
+ def falha_de_escrita(operacao: str, exc: BaseException) -> Exception:
296
+ if http.nada_saiu(exc):
297
+ return HubSpotNaoSaiu(f"HubSpot {operacao}: a conexão não abriu ({type(exc).__name__})")
298
+ return HubSpotIncerto(
299
+ f"HubSpot {operacao}: a conexão falhou depois do envio ({type(exc).__name__}); "
300
+ "a alteração pode ter chegado"
301
+ )
@@ -0,0 +1,46 @@
1
+ """Os erros do plugin ``hubspot``.
2
+
3
+ Separam o que **certamente não chegou** ao CRM (``HubSpotNaoSaiu``, um ``http.NadaSaiu``) do que
4
+ **pode ter chegado** (``HubSpotIncerto``, 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 a categoria que o HubSpot dá (``VALIDATION_ERROR``,
8
+ ``MISSING_SCOPES``), nunca o corpo, o e-mail, as propriedades nem o token.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from shade_sdk import http
14
+
15
+
16
+ class ErroDoHubSpot(Exception):
17
+ """A leitura não deu certo: conexão, TLS, permissão ou o HubSpot recusou o pedido."""
18
+
19
+ def __init__(self, mensagem: str, *, status: int | None = None, categoria: str = "") -> None:
20
+ super().__init__(mensagem)
21
+ self.status = status
22
+ self.categoria = categoria
23
+
24
+
25
+ class NaoEncontrado(ErroDoHubSpot):
26
+ """O negócio não existe, ou a conta conectada não o vê (``404``)."""
27
+
28
+
29
+ class HubSpotNaoSaiu(http.NadaSaiu):
30
+ """Certamente sem efeito: o HubSpot recusou o pedido (4xx, inclusive o 429 que sobrou das
31
+ retentativas) ou a rede falhou antes do envio."""
32
+
33
+ def __init__(self, mensagem: str, *, status: int | None = None, categoria: str = "") -> None:
34
+ super().__init__(mensagem)
35
+ self.status = status
36
+ self.categoria = categoria
37
+
38
+
39
+ class HubSpotIncerto(http.ResultadoIncerto):
40
+ """Pode ter tido efeito: o pedido foi enviado e a resposta não veio, veio com erro do servidor
41
+ ou não se leu. Conferir no CRM antes de concluir que não chegou."""
42
+
43
+ def __init__(self, mensagem: str, *, status: int | None = None, categoria: str = "") -> None:
44
+ super().__init__(mensagem)
45
+ self.status = status
46
+ self.categoria = categoria
@@ -0,0 +1,100 @@
1
+ Metadata-Version: 2.5
2
+ Name: shade-plugins-hubspot
3
+ Version: 0.1.0
4
+ Summary: Buscar e atualizar contatos e negócios do HubSpot CRM (upsert por e-mail, negócio por estágio) pela API v3, 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-hubspot
13
+
14
+ Busca contatos e negócios, cria ou atualiza um contato pelo e-mail e move um negócio de estágio no
15
+ [HubSpot CRM](https://developers.hubspot.com/docs/api/crm/understanding-the-crm) (API v3), de dentro
16
+ de um robô do [`shade-sdk`](https://pypi.org/project/shade-sdk/), com o token OAuth da conexão do
17
+ HubSpot na plataforma. Só a biblioteca padrão do Python: nenhuma dependência além do `shade-sdk`.
18
+
19
+ No `shade.toml` do robô, o host da API vai em `[hosts] permitidos` e a conexão em `[conexoes]`:
20
+
21
+ ```toml
22
+ [hosts]
23
+ permitidos = ["api.hubapi.com"]
24
+
25
+ [conexoes]
26
+ nomes = ["hubspot"]
27
+
28
+ [plugins]
29
+ hubspot = "0.1.0"
30
+ ```
31
+
32
+ ```python
33
+ import shade_plugins_hubspot as hubspot
34
+
35
+ # Leitura: roda inclusive no ensaio.
36
+ negocios = hubspot.buscar_negocios({"dealstage": "contractsent"}, propriedades=["dealname"])
37
+
38
+ # Escrita: só dentro de item.efetivar() (no ensaio não roda).
39
+ with item.efetivar("registrar o cliente"):
40
+ hubspot.upsert_contato(item["email"], {"firstname": item["nome"], "phone": item["fone"]})
41
+ hubspot.mover_negocio(negocios[0]["id"], "closedwon")
42
+ ```
43
+
44
+ ## A conta
45
+
46
+ - **Conexão:** o robô nunca vê a senha nem o refresh token. O token de acesso chega sob demanda da
47
+ conexão `hubspot` da plataforma e é renovado por ela. Fora da plataforma (no laptop), ponha um
48
+ token de acesso em `SHADE_TOKEN_HUBSPOT`.
49
+ - **Escopos:** `crm.objects.contacts.read`, `crm.objects.contacts.write`,
50
+ `crm.objects.deals.read` e `crm.objects.deals.write`. A conexão sem o escopo de uma operação é
51
+ recusada pelo HubSpot, e o erro manda reconectar o HubSpot.
52
+ - **Propriedades** são os nomes internos do HubSpot (`firstname`, `dealstage`), e o estágio do
53
+ negócio é o id interno do estágio do funil (`closedwon`), não o nome que aparece na tela.
54
+
55
+ ## O que o plugin garante
56
+
57
+ - **Contato sem duplicar.** `upsert_contato` usa o upsert em lote do HubSpot com `idProperty=email`:
58
+ o mesmo e-mail é sempre um contato só, e a segunda chamada atualiza as propriedades que cita (as
59
+ outras ficam como estavam). Repetir a chamada é seguro, então a falha transitória é repetida
60
+ dentro do `timeout=`.
61
+ - **Negócio sem `PATCH` à toa.** `mover_negocio` lê o estágio e, se o negócio já está no estágio
62
+ pedido, não escreve nada (`movido=False`). Se o `PATCH` sai sem confirmação, o plugin confere o
63
+ estágio: igual ao pedido é sucesso; diferente é `HubSpotIncerto`.
64
+ - **Só dentro de `item.efetivar()`.** Fora dele, a operação é um erro de contrato antes de qualquer
65
+ byte; no ensaio, o bloco é pulado e nada é enviado.
66
+ - **Valores literais.** Os valores vão como texto, num corpo montado como objeto e serializado pelo
67
+ `shade_sdk.http`, nunca por concatenação. O nome de propriedade, o id e o estágio são validados
68
+ antes de qualquer pedido.
69
+ - **Host e prazo:** só `api.hubapi.com`, com o certificado verificado, sem seguir redirecionamento;
70
+ toda 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 e-mail, as propriedades, o token nem o corpo da resposta; o erro da
73
+ API chega só pela categoria que o HubSpot dá (`VALIDATION_ERROR`, `MISSING_SCOPES`).
74
+
75
+ ## Operações
76
+
77
+ | Operação | Efeito | O que faz |
78
+ |---|---|---|
79
+ | `buscar_contatos(filtros, propriedades=None, *, limite=100)` | não | Contatos que atendem a todos os `filtros`: `id` e `propriedades`. |
80
+ | `upsert_contato(email, propriedades)` | sim | Cria ou atualiza o contato do e-mail. Devolve `id`, `email` e `novo`. |
81
+ | `buscar_negocios(filtros, propriedades=None, *, limite=100)` | não | Negócios que atendem a todos os `filtros`: `id` e `propriedades`. |
82
+ | `mover_negocio(id, estagio)` | sim | Move o negócio para o estágio. Devolve `id`, `estagio` e `movido`. |
83
+
84
+ Os `filtros` são um dicionário: `{"dealstage": "contractsent"}` (igual) ou
85
+ `{"amount": ["GTE", 1000]}` (operador e valor: `EQ`, `NEQ`, `LT`, `LTE`, `GT`, `GTE`,
86
+ `CONTAINS_TOKEN`, `NOT_CONTAINS_TOKEN`; `["HAS_PROPERTY"]` e `["NOT_HAS_PROPERTY"]` sem valor). Todos
87
+ valem ao mesmo tempo, até 6 por busca.
88
+
89
+ ## Limites
90
+
91
+ - A busca do HubSpot devolve no máximo 10 000 registros por consulta e enxerga o que acabou de ser
92
+ criado com um pequeno atraso: não use `buscar_contatos` para conferir o contato que o
93
+ `upsert_contato` acabou de gravar (o upsert já devolve o `id`).
94
+ - Criar negócio e propriedade customizada ficam fora do plugin.
95
+
96
+ ## Testes
97
+
98
+ A suíte de contrato do `shade_sdk.testing.plugins` e um servidor falso da API (TLS de uma CA de
99
+ teste, que só aceita valor em texto e recusa propriedade e estágio inexistentes, como a de
100
+ verdade) acompanham o código-fonte em `tests/`.
@@ -0,0 +1,8 @@
1
+ shade_plugins_hubspot/__init__.py,sha256=eH4D5HaWDPnXLoFEiX3bP-mOscjLt747fQ7iMysLZ1Q,17534
2
+ shade_plugins_hubspot/_cliente.py,sha256=Jyneayq9pSOv5ZUO9m9iTT6uG724QeCtQhB19Z_CwNM,11594
3
+ shade_plugins_hubspot/erros.py,sha256=Rs7ATj9vftaokOjDk2c0lVSa-CyuPXt1RB7BQXvpJLI,1803
4
+ shade_plugins_hubspot-0.1.0.dist-info/METADATA,sha256=wQi76HbeMIlK0ZFodtOrdFKVwNtK4yKjxIU97EUQnnc,5147
5
+ shade_plugins_hubspot-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
6
+ shade_plugins_hubspot-0.1.0.dist-info/entry_points.txt,sha256=N-s2wOPOpRwsOgggoHLSf6tiVdZCwdVu6L4juZn-8TY,59
7
+ shade_plugins_hubspot-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
8
+ shade_plugins_hubspot-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
+ hubspot = shade_plugins_hubspot: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.