#!/usr/bin/env python3 """Customer-operated starter: authorized standard Teams channel only.""" import argparse, datetime, hashlib, json, os, sys, urllib.parse, urllib.request, urllib.error from html.parser import HTMLParser GRAPH = "https://graph.microsoft.com/v1.0" FC = "https://field-connect.floot.app/_api/commercial" class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, *args, **kwargs): raise RuntimeError("Unexpected redirect") opener = urllib.request.build_opener(NoRedirect()) def need(key): value = os.environ.get(key, "").strip() if not value: raise RuntimeError("Missing setting " + key) return value def call(url, token, payload=None): headers = {"Authorization": "Bearer " + token, "Accept": "application/json"} body = None if payload is not None: headers["Content-Type"] = "application/json" body = json.dumps(payload).encode() req = urllib.request.Request(url, data=body, headers=headers) with opener.open(req, timeout=25) as response: raw = response.read(2000000) return json.loads(raw) if raw else {} def stable(*parts): return "graph-" + hashlib.sha256(json.dumps(parts, sort_keys=True).encode()).hexdigest() def official(url): u = urllib.parse.urlsplit(url) return u.scheme == "https" and u.hostname in ("teams.microsoft.com","teams.cloud.microsoft") and not u.username and not u.password and not u.port class Plain(HTMLParser): def __init__(self): super().__init__(convert_charrefs=True) self.parts = [] self.hidden = 0 def handle_starttag(self, tag, attrs): if tag in ("script","style"): self.hidden += 1 elif tag in ("p","br","div","li") and not self.hidden: self.parts.append("\n") def handle_endtag(self, tag): if tag in ("script","style") and self.hidden: self.hidden -= 1 def handle_data(self, data): if not self.hidden: self.parts.append(data) def text(body): raw = body.get("content", "") if body.get("contentType") == "html": p = Plain() p.feed(raw) raw = "".join(p.parts) raw = raw.strip() return raw if len(raw)<=3500 else raw[:3470]+"\n[Source text truncated]" def main(): parser = argparse.ArgumentParser(description="Default dry-run. Customer authorization required.") parser.add_argument("action", choices=["metadata","messages","dispatch"]) parser.add_argument("--apply", action="store_true") args = parser.parse_args() token = need("FC_TEAMS_ACCESS_TOKEN") company, project = need("FC_COMPANY_ID"), need("FC_PROJECT_ID") key = need("FC_CONNECTOR_KEY") if args.apply else "" team, channel = need("FC_TEAMS_TEAM_ID"), need("FC_TEAMS_CHANNEL_ID") path = "/teams/"+urllib.parse.quote(team,safe="")+"/channels/"+urllib.parse.quote(channel,safe="") info = call(GRAPH+path,token) url = info.get("webUrl","") if info.get("membershipType")!="standard" or not official(url): raise RuntimeError("Channel not eligible") envelope = {"companyId":company,"projectId":project,"system":"microsoft-teams"} def stage(event): if args.apply: call(FC+"/integration-intake",key,{**envelope,"event":event}) if args.action=="metadata": at=info.get("createdDateTime") or datetime.datetime.now(datetime.timezone.utc).isoformat() data={"team":team,"channel":info.get("displayName",channel)[:180],"teamId":team,"channelId":channel,"membershipType":"standard","description":(info.get("description") or "")[:400],"webUrl":url} stage({"kind":"teams-channel","externalId":stable(team,channel,data,at),"sourceAt":at,"data":data}) print("Channel metadata submitted for review." if args.apply else "Dry-run: channel validated.") elif args.action=="messages": rows=call(GRAPH+path+"/messages?$top=50",token).get("value",[]) count=0 for row in rows[:50]: if row.get("deletedDateTime") or row.get("messageType") not in (None,"message"): continue body=text(row.get("body") or {}) mid=str(row.get("id","")) at=row.get("lastModifiedDateTime") or row.get("createdDateTime") if not body or not mid or not at: continue author=row.get("from") or {} name=(author.get("user") or author.get("application") or {}).get("displayName") or "Unknown Teams author" source=row.get("webUrl") or url data={"teamId":team,"channelId":channel,"membershipType":"standard","messageId":mid,"author":name[:180],"body":body,"webUrl":source if official(source) else url} stage({"kind":"teams-message","externalId":stable(team,channel,mid,at),"sourceAt":at,"data":data}) count+=1 print(("Staged " if args.apply else "Validated ")+str(count)+" root messages; no private chats or attachments.") else: if not args.apply: print("Dry-run: no item claimed or message sent.") return item=call(FC+"/connector-dispatch",key,{**envelope,"action":"claim"}).get("item") if not item: print("No pending outbound item.") return p=item["payload"] receipt={**envelope,"action":"receipt","id":item["id"],"claimToken":item["claimToken"]} if p.get("kind")!="teams-post" or p.get("teamId")!=team or p.get("channelId")!=channel: call(FC+"/connector-dispatch",key,{**receipt,"state":"failed","providerRef":"local-channel-not-approved","note":"Local channel allowlist rejected destination. Nothing sent."}) print("Destination rejected.") return try: result=call(GRAPH+path+"/messages",token,{"body":{"contentType":"text","content":p["body"]}}) mid=result.get("id") if not mid: raise RuntimeError("Missing provider ID") except Exception: call(FC+"/connector-dispatch",key,{**receipt,"state":"failed","providerRef":"uncertain-"+item["id"],"note":"Provider result uncertain. Verify Teams before any new send; no automatic retry."}) print("Uncertain send; reconcile manually.") return call(FC+"/connector-dispatch",key,{**receipt,"state":"accepted","providerRef":str(mid),"note":"Graph returned a message ID, not a read receipt."}) print("Provider acceptance recorded.") if __name__=="__main__": try: main() except Exception as error: print("Stopped: "+type(error).__name__+". Check authorized settings and provider status.",file=sys.stderr) sys.exit(1)